hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
2465fa6319322a5c4e3c96fd8605ef2adc597147
1,098
package biz.orgin.minecraft.hothgenerator.schematic; import biz.orgin.minecraft.hothgenerator.HothUtils; public class DoorNS implements Schematic { private static final long serialVersionUID = 299532124330599474L; public static Schematic instance = new DoorNS(); private static int WIDTH = 3; private static int LENGTH = 1; private static int HEIGHT = 3; private static String name = "DoorNS"; private final int[][][] matrix = new int[][][] { // TYPEID DATAID { // Layer 0 { 98, 98, 98, 0, 3, 0} }, { // Layer 1 { 98, 89, 98, 3, 0, 3} }, { // Layer 2 { 98, 98, 98, 0, 3, 0} }, }; private DoorNS() { } public int getWidth() // Inner { return DoorNS.WIDTH; } public int getLength() // Middle { return DoorNS.LENGTH; } public int getHeight() // Outer { return DoorNS.HEIGHT; } public int[][][] getMatrix() { return this.matrix; } @Override public String getName() { return DoorNS.name; } @Override public Schematic rotate(int direction) { return HothUtils.rotateSchematic(direction, this); } }
18
66
0.636612
16724ba59a3338e219086439a6b6765c4b6e11cf
2,979
package com.sohu.cache.web.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; /** * ip工具 * * @author leifu */ @Component public class IpUtil { public static String domain; @Value("${server.port}") private int port; public static Logger logger = LoggerFactory.getLogger(IpUtil.class); public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } public int getLocalPort() { return port; } public String getLocalIP() { InetAddress inetAddress = getLocalHostLANAddress(); return inetAddress.getHostAddress(); } public String getCurrentIpPort() { return getLocalIP() + ":" + port; } public InetAddress getLocalHostLANAddress() { try { InetAddress candidateAddress = null; // 遍历所有的网络接口 for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); // 所有的接口下遍历IP for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址 if (inetAddr.isSiteLocalAddress()) { // 优先site-local地址 return inetAddr; } else if (candidateAddress == null) { candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress; } // 如果没有发现 non-loopback地址.用次选方案 InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); return jdkSuppliedAddress; } catch (Exception e) { logger.error(e.getMessage(), e); } return null; } @Value("${server.domain}") public void setDomain(String ccdomain){ domain = ccdomain; } }
32.380435
109
0.558577
7ad188c45f589bc74c9cd5f2437b8288eb1c5d84
7,789
package org.crawler.monitor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MonitorRequester { private static String server; //服务端ip和端口号 private static String appkey; //每个爬虫任务分配的appkey private static int interval; //间隔时间 private static int dailyId = -1; //本次任务对应的日志id private static final Logger logger = LoggerFactory.getLogger(MonitorRequester.class); @Value("${crawler.monitor.url}") public void setServer(String url) { //给静态变量赋值 server = url; } @Value("${crawler.monitor.appkey}") public void setAppkey(String appkey0){ appkey = appkey0; } @Value("${crawler.monitor.interval}") public void setInterval(int interval0){ interval = interval0; } /** * 监控开始 * 参数拼接 * @param monitorParam * @return */ private static String getStartParamString(MonitorParam monitorParam){ String crawlerCount = monitorParam.getCrawlerCount()+""; String saveCount = monitorParam.getSaveCount()+""; String ram = monitorParam.getRam(); String cpu = monitorParam.getCpu(); //得到当前时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = sdf.format(new Date()); //生成密钥 String sign = appkey+timestamp+crawlerCount+saveCount+ram+cpu+interval+appkey; String secret = MD5(sign); //拼接参数 String param = "appkey="+appkey+"&secret="+secret+"&timestamp="+timestamp+ "&cpu="+cpu+"&ram="+ram+"&crawlerCount="+crawlerCount+"&saveCount="+saveCount+"&interval="+interval; return param; } /** * 状态监控 * 生成密钥、拼接请求参数 * @return */ private static String getCrawlerParamString(MonitorParam monitorParam){ String crawlerCount = monitorParam.getCrawlerCount()+""; String saveCount = monitorParam.getSaveCount()+""; String ram = monitorParam.getRam(); String cpu = monitorParam.getCpu(); //得到当前时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = sdf.format(new Date()); //生成密钥 String sign = appkey+timestamp+crawlerCount+saveCount+ram+cpu+dailyId+appkey; String secret = MD5(sign); //拼接参数 String param = "appkey="+appkey+"&secret="+secret+"&timestamp="+timestamp+ "&cpu="+cpu+"&ram="+ram+"&crawlerCount="+crawlerCount+"&saveCount="+saveCount+"&dailyId="+dailyId;; return param; } /** * 日报生成 * 生成密钥、拼接求参数 * @return */ private static String getDailyParamString(MonitorParam monitorParam){ String totalCount = monitorParam.getTotalCount()+""; String totalSold = monitorParam.getTotalSold()+""; //得到当前时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = sdf.format(new Date()); //生成密钥 String sign = appkey + timestamp + totalCount + totalSold + dailyId + appkey; String secret = MD5(sign); //拼接参数 String param = "appkey="+appkey+"&secret="+secret+"&timestamp="+timestamp+ "&totalCount="+totalCount+"&totalSold="+totalSold+"&dailyId="+dailyId; return param; } /** * 错误日志参数 * @param monitorParam * @return */ private static String getExceptionParamString(MonitorParam monitorParam){ String exception = monitorParam.getException(); // 得到当前时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = sdf.format(new Date()); // 生成密钥 String sign = appkey + timestamp + exception + appkey; String secret = MD5(sign); // 拼接参数 String param = "appkey=" + appkey + "&secret=" + secret + "&timestamp=" + timestamp + "&exception=" + exception; return param; } //监控开始 public static String start(MonitorParam monitorParam){ String url = server+"/sys/start"; String param = getStartParamString(monitorParam); String result = sendPost(param,url); try { dailyId = Integer.parseInt(result.trim()); } catch (NumberFormatException e) { dailyId = -1; result = -1+""; logger.error("dailyId get error:",e); } return result; } //发送爬虫状态信息 public static String sendMessage(MonitorParam monitorParam){ String url = server+"/sys/sendMessage"; String param = getCrawlerParamString(monitorParam); return sendPost(param,url); } //发送日报信息 public static String sendDaily(MonitorParam monitorParam){ String url = server+"/sys/sendDaily"; String param = getDailyParamString(monitorParam); return sendPost(param,url); } //发生错误时给监控中心发出警告 public static String sendException(MonitorParam monitorParam){ String url = server+"/sys/sendException"; String param = getExceptionParamString(monitorParam); return sendPost(param,url); } /** * 向URL发送post请求 * * @param url * 发送请求的URL * @param param * 请求参数, name1=value1&name2=value2 * @return result 响应结果 */ private static String sendPost(String param,String url) { logger.info(url+"-------------"+param); PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { logger.error("monitorRequester post error:",e); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } logger.info("Monitor Result:"+result); return result; } private static String MD5(String s){ char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; try { byte[] btInput = s.getBytes("UTF-8"); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { logger.error("monitorRequester md5 error"+e); return null; } } }
31.281124
105
0.602773
6beaaffa5847b7ac8d69ba118cbef4408d3def25
5,216
/* * The MIT License (MIT) * * Copyright (c) 2014-2015 abel533@gmail.com * * 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 net.huadong.tech.echarts.series.force; import lombok.Getter; import lombok.Setter; import net.huadong.tech.echarts.style.ItemStyle; import java.io.Serializable; import java.util.HashMap; /** * 力导向图的顶点数据 * * @author liuzh */ @Getter @Setter public class Node extends HashMap<String, Object> implements Serializable { private static final long serialVersionUID = 4254895945303983318L; /** * 构造函数 */ public Node() { super(); } /** * 构造函数,参数:category,name,value * * @param category * @param name * @param value */ public Node(Integer category, String name, Integer value) { super(); put("category", category); put("name", name); put("value", value); } /** * 获取name值 */ public String name() { return (String) get("name"); } /** * 设置name值 * * @param name */ public Node name(String name) { put("name", name); return this; } /** * 获取label值 * * @since 2.1.9 */ public String label() { return (String) get("label"); } /** * 设置label值 * * @param label * @since 2.1.9 */ public Node label(String label) { put("label", label); return this; } /** * 获取value值 */ public Integer value() { return (Integer) get("value"); } /** * 设置value值 * * @param value */ public Node value(Integer value) { put("value", value); return this; } /** * 获取initial值 */ public Object initial() { return get("initial"); } /** * 设置initial值 * * @param initial */ public Node initial(Object initial) { put("initial", initial); return this; } /** * 获取fixX值 */ public Boolean fixX() { return (Boolean) get("fixX"); } /** * 设置fixX值 * * @param fixX */ public Node fixX(Boolean fixX) { put("fixX", fixX); return this; } /** * 获取fixY值 */ public Boolean fixY() { return (Boolean) get("fixY"); } /** * 设置fixY值 * * @param fixY */ public Node fixY(Boolean fixY) { put("fixY", fixY); return this; } /** * 获取ignore值 */ public Boolean ignore() { return (Boolean) get("ignore"); } /** * 设置ignore值 * * @param ignore */ public Node ignore(Boolean ignore) { put("ignore", ignore); return this; } /** * 获取symbol值 */ public Object symbol() { return get("symbol"); } /** * 设置symbol值 * * @param symbol */ public Node symbol(Object symbol) { put("symbol", symbol); return this; } /** * 获取symbolSize值 */ public Object symbolSize() { return get("symbolSize"); } /** * 设置symbolSize值 * * @param symbolSize */ public Node symbolSize(Object symbolSize) { put("symbolSize", symbolSize); return this; } /** * 获取draggable值 */ public Boolean draggable() { return (Boolean) get("draggable"); } /** * 设置draggable值 * * @param draggable */ public Node draggable(Boolean draggable) { put("draggable", draggable); return this; } /** * 获取category值 */ public Integer category() { return (Integer) get("category"); } /** * 设置category值 * * @param category */ public Node category(Integer category) { put("category", category); return this; } /** * 详见 itemStyle * * @see net.huadong.tech.echarts.style.ItemStyle */ public ItemStyle itemStyle() { if (get("itemStyle") == null) { put("itemStyle", new ItemStyle()); } return (ItemStyle) get("itemStyle"); } }
19.462687
80
0.549271
30ffc8b3d7960c4215840170422a5161d0023a98
445
package com.inconvenience.apkdecompiler; import java.util.Comparator; import java.util.Locale; import com.inconvenience.apkdecompiler.AppListItem; public class SortOptions { public Comparator<AppListItem> AppListItemDefault = new Comparator<AppListItem>() { @Override public int compare(AppListItem o1, AppListItem o2) { return o1.appName.toLowerCase().compareTo(o2.appName.toLowerCase()); } }; }
26.176471
87
0.723596
65b7ddef52d015860240d892016bc6edb615ae07
2,472
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4048.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc4048.Robot; /** * */ public class Drive extends Command { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS double fwd, str, rcw; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public Drive() { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.drivetrain); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time @Override protected void initialize() { } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { fwd = -Robot.oi.getLeftJoystick().getY(); str = Robot.oi.getLeftJoystick().getX(); rcw = Robot.oi.getRightJoystick().getX(); //Square the values for finer movement if(fwd < 0) fwd *= fwd * -1; else fwd *= fwd; if(str < 0) str *= str * -1; else str *= str; if(rcw < 0) rcw *= rcw * -1; else rcw *= rcw; Robot.drivetrain.move(fwd, str, rcw); //System.out.println("RUNNING DRIVE"); } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return false; } // Called once after isFinished returns true @Override protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { } }
28.413793
79
0.67233
d2a0b79aa822a11a16c18e64f4aa7a45393d6df9
515
package com.almasb.lang; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; /** * @author Almas Baimagambetov (almaslvl@gmail.com) */ public class Env { private Map<String, Object> memory = new HashMap<>(); private Consumer<String> output; public Env(Consumer<String> output) { this.output = output; } public Consumer<String> getOutput() { return output; } public Map<String, Object> getMemory() { return memory; } }
18.392857
57
0.650485
f7fdced6e7e485ee0a56fb76588abd422346f44d
1,204
package com.ruoyi.project.elevator.service.service; import com.ruoyi.project.elevator.service.domain.Service; import com.ruoyi.project.elevator.service.mapper.ServiceMapper; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; @org.springframework.stereotype.Service("ServiceService") public class ServiceServiceImpl implements ServiceService { @Autowired private ServiceMapper serviceMapper; @Override public int insertTask(Service service) { return serviceMapper.insertTask(service); } @Override public int saveTask(Service service) { int count = serviceMapper.insertTask(service); return count; } @Override public List<Service> selectServiceList(Service service) { return serviceMapper.selectServiceList(service); } @Override public Service selectServiceById(long id) { return serviceMapper.selectServiceById(id); } @Override public int selectTaskById(long service_id) { return serviceMapper.selectTaskById(service_id); } @Override public Service selectServiceByServiceId(Long id) { return serviceMapper.selectServiceBySerivceId(id); } }
25.617021
63
0.743355
ecd349161700efb13e15b0644aa8f01b621f0b4e
1,037
/* * Copyright (C) 2014-2018 LinkedIn Corp. (pinot-core@linkedin.com) * * 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.pinot.thirdeye.detection.spec; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class MockGrouperSpec extends AbstractSpec { private double mockParam = Double.NaN; public double getMockParam() { return mockParam; } public void setMockParam(double mockParam) { this.mockParam = mockParam; } }
29.628571
75
0.746384
ff78fb0b9931b74095af50d7fd22deddb5b869b9
399
package com.ablanco.zoomy; import android.app.Activity; import android.view.ViewGroup; public class ActivityContainer implements TargetContainer { private Activity mActivity; ActivityContainer(Activity activity) { this.mActivity = activity; } public ViewGroup getDecorView() { return (ViewGroup) this.mActivity.getWindow().getDecorView(); } }
23.470588
70
0.699248
640dcc6618db517159eb2e6eea99438074fcd0de
1,891
import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("ex") public class class138 { @ObfuscatedName("o") @ObfuscatedGetter( longValue = 8571598183286101587L ) static long field2048; @ObfuscatedName("dy") @ObfuscatedGetter( intValue = 1707259621 ) @Export("myWorldPort") static int myWorldPort; @ObfuscatedName("ev") @ObfuscatedGetter( intValue = 1602829299 ) @Export("baseX") static int baseX; @ObfuscatedName("t") @ObfuscatedSignature( signature = "(IIII)V", garbageValue = "2131638771" ) static final void method3049(int var0, int var1, int var2) { int var3; for(var3 = 0; var3 < 8; ++var3) { for(int var4 = 0; var4 < 8; ++var4) { class62.tileHeights[var0][var3 + var1][var4 + var2] = 0; } } if(var1 > 0) { for(var3 = 1; var3 < 8; ++var3) { class62.tileHeights[var0][var1][var3 + var2] = class62.tileHeights[var0][var1 - 1][var3 + var2]; } } if(var2 > 0) { for(var3 = 1; var3 < 8; ++var3) { class62.tileHeights[var0][var3 + var1][var2] = class62.tileHeights[var0][var3 + var1][var2 - 1]; } } if(var1 > 0 && class62.tileHeights[var0][var1 - 1][var2] != 0) { class62.tileHeights[var0][var1][var2] = class62.tileHeights[var0][var1 - 1][var2]; } else if(var2 > 0 && class62.tileHeights[var0][var1][var2 - 1] != 0) { class62.tileHeights[var0][var1][var2] = class62.tileHeights[var0][var1][var2 - 1]; } else if(var1 > 0 && var2 > 0 && class62.tileHeights[var0][var1 - 1][var2 - 1] != 0) { class62.tileHeights[var0][var1][var2] = class62.tileHeights[var0][var1 - 1][var2 - 1]; } } }
31
108
0.595981
768ffb7e9de397e066b3ec9f1532dbb0fc90a5f1
5,178
/** * 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.deephacks.tools4j.config.internal.core.xml; import static org.deephacks.tools4j.config.model.Events.CFG101_SCHEMA_NOT_EXIST; import static org.deephacks.tools4j.config.model.Events.CFG202_XML_SCHEMA_FILE_MISSING; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import javax.xml.bind.Unmarshaller; import org.deephacks.tools4j.config.internal.core.xml.XmlSchemaAdapter.XmlSchemas; import org.deephacks.tools4j.config.model.Schema; import org.deephacks.tools4j.config.spi.SchemaManager; import org.deephacks.tools4j.support.ServiceProvider; import org.deephacks.tools4j.support.SystemProperties; import com.google.common.io.Files; @ServiceProvider(service = SchemaManager.class) public class XmlSchemaManager extends SchemaManager { public static final String XML_CONFIG_SCHEMA_FILE_STORAGE_DIR_PROP = "config.spi.schema.xml.dir"; public static final String XML_SCHEMA_FILE_NAME = "schema.xml"; private static final SystemProperties PROP = SystemProperties.createDefault(); private static final long serialVersionUID = 8979172640204086999L; @Override public Map<String, Schema> getSchemas() { return readValues(); } @Override public Schema getSchema(String schemaName) { Map<String, Schema> values = readValues(); Schema schema = values.get(schemaName); if (schema == null) { throw CFG101_SCHEMA_NOT_EXIST(schemaName); } return schema; } @Override public void regsiterSchema(Schema... schemas) { Map<String, Schema> values = readValues(); for (Schema schema : schemas) { values.put(schema.getName(), schema); writeValues(values); } } @Override public void removeSchema(String schemaName) { Map<String, Schema> values = readValues(); values.remove(schemaName); writeValues(values); } private Map<String, Schema> readValues() { String dirValue = PROP.get(XML_CONFIG_SCHEMA_FILE_STORAGE_DIR_PROP); if (dirValue == null || "".equals(dirValue)) { dirValue = System.getProperty("java.io.tmpdir"); } File file = new File(new File(dirValue), XML_SCHEMA_FILE_NAME); try { if (!file.exists()) { Files.write("<schema-xml></schema-xml>", file, Charset.defaultCharset()); } FileInputStream in = new FileInputStream(file); JAXBContext context = JAXBContext.newInstance(XmlSchemas.class); Unmarshaller unmarshaller = context.createUnmarshaller(); XmlSchemas schemas = (XmlSchemas) unmarshaller.unmarshal(in); return schemas.getSchemas(); } catch (JAXBException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw CFG202_XML_SCHEMA_FILE_MISSING(file); } catch (IOException e) { throw new RuntimeException(e); } } private void writeValues(Map<String, Schema> values) { String dirValue = PROP.get(XML_CONFIG_SCHEMA_FILE_STORAGE_DIR_PROP); if (dirValue == null || "".equals(dirValue)) { dirValue = System.getProperty("java.io.tmpdir"); } File dir = new File(dirValue); if (!dir.exists()) { try { dir.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } } File file = new File(dir, XML_SCHEMA_FILE_NAME); PrintWriter pw = null; try { XmlSchemas schemas = new XmlSchemas(values); pw = new PrintWriter(file, "UTF-8"); JAXBContext context = JAXBContext.newInstance(XmlSchemas.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(schemas, pw); } catch (PropertyException e) { throw new RuntimeException(e); } catch (JAXBException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if (pw != null) { pw.flush(); pw.close(); } } } }
35.958333
101
0.658749
b0fa94db2e452d01f7254af1eff1993deb6d79b4
689
package io.github.jzdayz.jdk.type; import org.apache.ibatis.reflection.TypeParameterResolver; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class Tests { public interface B<T> { List<T> list(); } public interface C extends B<String> { } public static void main(String[] args) throws Exception { final Method t1 = B.class.getDeclaredMethod("list"); t1.setAccessible(true); // String.class Type type = TypeParameterResolver.resolveReturnType(t1, C.class); System.out.println(type); List<String> list = new ArrayList<>(); } }
21.53125
73
0.667634
9362acf9acd6e7e70db54ff64ef2868e06552c39
3,439
package com.sendtomoon.eroica.common.beans.map; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.sendtomoon.eroica.common.beans.BeanTransformException; import com.sendtomoon.eroica.common.beans.BeansConfigInfo; import com.sendtomoon.eroica.common.beans.ParameterInfo; class Bean2Map { private BeansConfigInfo beansConfigInfo; public Bean2Map(BeansConfigInfo beansConfigInfo){ this.beansConfigInfo=beansConfigInfo; } public Bean2Map(){ this.beansConfigInfo=new BeansConfigInfo(); } Object toMap(Object value){ try{ return _toMap(value); }catch(Throwable th){ if(th!=null && th instanceof InvocationTargetException){ th=th.getCause(); } throw new BeanTransformException("Class["+value.getClass().getName()+"] to map error:"+th.getMessage(),th); } } private Object _toMap(Object value) throws Throwable{ //-------------------------- if(value==null)return null; if(value.getClass().isArray()){ Class<?> clazz=value.getClass().getComponentType(); if(clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || String.class.equals(clazz) || Character.class.equals(clazz) || Boolean.class.equals(clazz)){ return value; }else{ int len=Array.getLength(value); Object arr=Array.newInstance(Object.class,len); for(int i=0;i<len;i++){ Object v=Array.get(value, i); if(v==null){ Array.set(arr, i,null); }else{ Array.set(arr, i,_toMap(v)); } } return arr; } }else if(value instanceof Collection){ List list=new ArrayList(((Collection)value).size()); for(Object v:((Collection)value)){ if(v!=null){ list.add(_toMap(v)); }else{ list.add(null); } } return list; }else if( value instanceof Map){ Map map=(Map)value; Map res=new HashMap(map.size()); Iterator i=map.entrySet().iterator(); while(i.hasNext()){ Map.Entry entry=(Map.Entry)i.next(); Object v=entry.getValue(); if(v!=null ){ res.put(entry.getKey(),_toMap(v)); } } return res; }else if(value instanceof Enum){ return ((Enum)value).name(); }else if(!value.getClass().getName().startsWith("java")){ return bean2map(value); } return value; } public Object toMapField(ParameterInfo ps,Object value){ try{ return _toMapField(ps,value); }catch(Throwable th){ if(th!=null && th instanceof InvocationTargetException){ th=th.getCause(); } throw new BeanTransformException("Class["+value.getClass().getName()+"] to map error:"+th.getMessage(),th); } } private Object _toMapField(ParameterInfo ps,Object value) throws Throwable{ Object v=_toMap(value); if(v!=null && ps.getFormatter()!=null){ v=ps.getFormatter().print(value); } return v; } private Map<Object,Object> bean2map(Object bean) throws Throwable{ HashMap<Object,Object> datas=new HashMap<Object,Object>(8); List<ParameterInfo> params=beansConfigInfo.getRestFields(bean.getClass()); for(ParameterInfo ps:params){ Object tv= ps.get(bean); if(tv!=null){ if(ps.getComponentType()==ParameterInfo.CT_NOT){ datas.put(ps.getName(), _toMapField(ps,tv)); }else{ datas.put(ps.getName(), _toMap(tv)); } } } return datas; } }
25.474074
111
0.674033
61d1c275195f2c40178f8a790bb9c9c5592e4cfd
1,531
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.accessibility.talkback.tutorial; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.Button; public class HoverTrackingButton extends Button { private boolean didHoverEnter; public HoverTrackingButton(Context context) { super(context); } public HoverTrackingButton(Context context, AttributeSet attrs) { super(context, attrs); } public HoverTrackingButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onHoverEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER) { didHoverEnter = true; } return super.onHoverEvent(event); } public void clearTracking() { didHoverEnter = false; } public boolean didHoverEnter() { return didHoverEnter; } }
27.339286
85
0.742652
349e20c01a6952ae1c1037b5057eed6484eed22b
5,066
/* Copyright 2014 Twitter, 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.twitter.hraven; import org.apache.hadoop.hbase.util.Bytes; /** * defines the aggregation related constants * */ public class AggregationConstants { // name the table as job_history_agg_daily public static final String AGG_DAILY_TABLE = Constants.HISTORY_TABLE + "_agg_daily"; public static final byte[] AGG_DAILY_TABLE_BYTES = Bytes.toBytes(AGG_DAILY_TABLE); //name the table as job_history_agg_weekly public static final String AGG_WEEKLY_TABLE = Constants.HISTORY_TABLE + "_agg_weekly"; public static final byte[] AGG_WEEKLY_TABLE_BYTES = Bytes.toBytes(AGG_WEEKLY_TABLE); public static final String INFO_FAM = "i"; public static final byte[] INFO_FAM_BYTES = Bytes.toBytes(INFO_FAM); /** * The s column family has a TTL of 30 days * It's used as a scratch column family * It stores the run ids that are seen for that day * we assume that a flow will not run for more than 30 days, * hence it's fine to "expire" that data */ public static final String SCRATCH_FAM = "s"; public static final byte[] SCRATCH_FAM_BYTES = Bytes.toBytes(SCRATCH_FAM); /** parameter that specifies whether or not to aggregate */ public static final String AGGREGATION_FLAG_NAME = "aggregate"; /** * name of the flag that determines whether or not re-aggregate * (overrides aggregation status in raw table for that job) */ public static final String RE_AGGREGATION_FLAG_NAME = "reaggregate"; /** column name for app id in aggregation table */ public static final String APP_ID_COL = "app_id"; public static final byte[] APP_ID_COL_BYTES = Bytes.toBytes(APP_ID_COL.toLowerCase()); /** * the number of runs in an aggregation */ public static final String NUMBER_RUNS = "number_runs"; /** raw bytes representation of the number of runs parameter */ public static final byte[] NUMBER_RUNS_BYTES = Bytes.toBytes(NUMBER_RUNS.toLowerCase()); /** * the user who ran this app */ public static final String USER = "user"; public static final byte[] USER_BYTES = Bytes.toBytes(USER.toLowerCase()); /** * the number of jobs in an aggregation */ public static final String TOTAL_JOBS = "total_jobs"; /** raw bytes representation of the number jobs parameter */ public static final byte[] TOTAL_JOBS_BYTES = Bytes.toBytes(TOTAL_JOBS.toLowerCase()); /** * use this config setting to define an hadoop-version-independent property for queuename */ public static final String HRAVEN_QUEUE = "queue"; /** raw bytes representation of the queue parameter */ public static final byte[] HRAVEN_QUEUE_BYTES = Bytes.toBytes(HRAVEN_QUEUE.toLowerCase()); /** total maps and reduces */ public static final String TOTAL_MAPS = "total_maps"; public static final byte[] TOTAL_MAPS_BYTES = Bytes.toBytes(TOTAL_MAPS.toLowerCase()); public static final String TOTAL_REDUCES = "total_reduces"; public static final byte[] TOTAL_REDUCES_BYTES = Bytes.toBytes(TOTAL_REDUCES.toLowerCase()); /** slot millis for maps and reduces */ public static final String SLOTS_MILLIS_MAPS = "slots_millis_maps"; public static final byte[] SLOTS_MILLIS_MAPS_BYTES = Bytes.toBytes(SLOTS_MILLIS_MAPS .toLowerCase()); public static final String SLOTS_MILLIS_REDUCES = "slots_millis_reduces"; public static final byte[] SLOTS_MILLIS_REDUCES_BYTES = Bytes.toBytes(SLOTS_MILLIS_REDUCES .toLowerCase()); /** used to indicate how expensive a job is in terms of memory and time taken */ public static final String MEGABYTEMILLIS = "megabytemillis"; public static final byte[] MEGABYTEMILLIS_BYTES = Bytes.toBytes(MEGABYTEMILLIS.toLowerCase()); /** used to indicate the cost of a job is in terms of currency units */ public static final String JOBCOST = "jobcost"; public static final byte[] JOBCOST_BYTES = Bytes.toBytes(JOBCOST.toLowerCase()); public static final String JOB_DAILY_AGGREGATION_STATUS_COL = "daily_aggregation_status"; public static final byte[] JOB_DAILY_AGGREGATION_STATUS_COL_BYTES = Bytes.toBytes(JOB_DAILY_AGGREGATION_STATUS_COL); public static final String JOB_WEEKLY_AGGREGATION_STATUS_COL = "weekly_aggregation_status"; public static final byte[] JOB_WEEKLY_AGGREGATION_STATUS_COL_BYTES = Bytes.toBytes(JOB_WEEKLY_AGGREGATION_STATUS_COL); /** * number of retries for check and put */ public static final int RETRY_COUNT = 100; /** * type of aggregation : daily, weekly */ public enum AGGREGATION_TYPE { DAILY, WEEKLY; } }
37.80597
96
0.750888
dc228c04f141662328714e3eac3b004951a0051d
464
package com.weique.overhaul.v2.di.module; import com.weique.overhaul.v2.mvp.contract.SignInContract; import com.weique.overhaul.v2.mvp.model.SignInModel; import dagger.Binds; import dagger.Module; /** * ================================================ * Description: * <p> * ================================================ */ @Module public abstract class SignInModule { @Binds abstract SignInContract.Model bindSignInModel(SignInModel model); }
22.095238
69
0.592672
314cf506ffeaade3dee58a58c14bc418a66ae96b
2,404
/* * Copyright 2016 The Bazel Authors. 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. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.android.sync.model; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.idea.blaze.base.ideinfo.TargetKey; import com.google.idea.blaze.base.model.primitives.Label; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** Keeps track of which resource modules correspond to which resource target. */ public class AndroidResourceModuleRegistry { private final BiMap<Module, TargetKey> moduleToTarget = HashBiMap.create(); private final Map<TargetKey, AndroidResourceModule> targetToResourceModule = new HashMap<>(); public static AndroidResourceModuleRegistry getInstance(Project project) { return ServiceManager.getService(project, AndroidResourceModuleRegistry.class); } public Label getLabel(Module module) { TargetKey targetKey = getTargetKey(module); return targetKey == null ? null : targetKey.getLabel(); } public TargetKey getTargetKey(Module module) { return moduleToTarget.get(module); } @Nullable public AndroidResourceModule get(Module module) { TargetKey target = moduleToTarget.get(module); return target == null ? null : targetToResourceModule.get(target); } public Module getModule(TargetKey target) { return moduleToTarget.inverse().get(target); } public void put(Module module, AndroidResourceModule resourceModule) { moduleToTarget.put(module, resourceModule.targetKey); targetToResourceModule.put(resourceModule.targetKey, resourceModule); } public void clear() { moduleToTarget.clear(); targetToResourceModule.clear(); } }
35.880597
95
0.767887
dd054957fd0a311321945ae0f0ef3aec1fba3e07
2,666
/** * Copyright © 2015 Pablo Grela Palleiro (pablogp_9@hotmail.com) * * 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.cuacfm.members.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.*; /** The Class WebAppInitializer. */ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { /** Instantiates a new webb app initializer. */ public WebAppInitializer() { // Default empty constructor. } /** * getServletMappings. * * @return String[] */ @Override protected String[] getServletMappings() { return new String[] { "/" }; } /** * getRootConfigClasses. * * @return Class<?>[] */ @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { ApplicationConfig.class, JpaConfig.class, SecurityConfig.class }; } /** * getServletConfigClasses. * * @return Class<?>[] */ @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebMvcConfig.class }; } /** * getServletFilters. * * @return Filter[] */ @Override protected Filter[] getServletFilters() { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); DelegatingFilterProxy securityFilterChain = new DelegatingFilterProxy( "springSecurityFilterChain"); return new Filter[] { characterEncodingFilter, securityFilterChain }; } /** * ustomizeRegistration. * * @param ServletRegistration * .Dynamic registration */ @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("defaultHtmlEscape", "true"); registration.setInitParameter("spring.profiles.active", "default"); } }
29.622222
100
0.69805
b266c6309e06d7107627a47d4c4b9c7864cdef67
4,489
/* * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. */ package gov.opm.scrd.services.impl.reporting; import gov.opm.scrd.services.impl.BaseReportResponse; import java.util.Map; /** * This class represents the response for the namesake report. <p> <strong>Thread-safety:</strong> This class is mutable * and not thread - safe. </p> * * @author AleaActaEst, RaitoShum * @version 1.0 */ public class AccountTypeTotalsReportResponse extends BaseReportResponse { /** * Represents the totals of CSRS accounts. It is accessible by getter and modified by setter. It can be any value. * The default value is null. */ private Map<String, Integer> csrsAccounts; /** * Represents the totals of FERS accounts. It is accessible by getter and modified by setter. It can be any value. * The default value is null. */ private Map<String, Integer> fersAccounts; /** * Represents the totals unknown new accounts. It is accessible by getter and modified by setter. It can be any * value. The default value is null. */ private Integer unknownNewAccounts; /** * Represents the totals of unknown active accounts. It is accessible by getter and modified by setter. It can be * any value. The default value is null. */ private Integer unknownActiveAccounts; /** * Represents the totals of unknown accounts. It is accessible by getter and modified by setter. It can be any * value. The default value is null. */ private Integer unknownTotal; /** * Represents total of accounts. It is accessible by getter and modified by setter. It can be any value. The default * value is null. */ private Integer totalAccounts; /** * Creates a new instance of the {@link AccountTypeTotalsReportResponse} class. */ public AccountTypeTotalsReportResponse() { super(); } /** * Gets the total of CSRS accounts. * * @return the field value */ public Map<String, Integer> getCsrsAccounts() { return csrsAccounts; } /** * Sets the total of CSRS accounts. * * @param csrsAccounts * the field value. */ public void setCsrsAccounts(Map<String, Integer> csrsAccounts) { this.csrsAccounts = csrsAccounts; } /** * Gets the total of FERS accounts. * * @return the field value */ public Map<String, Integer> getFersAccounts() { return fersAccounts; } /** * Sets the total of FERS accounts. * * @param fersAccounts * the field value. */ public void setFersAccounts(Map<String, Integer> fersAccounts) { this.fersAccounts = fersAccounts; } /** * Gets the total of unknown new accounts. * * @return the field value */ public Integer getUnknownNewAccounts() { return unknownNewAccounts; } /** * Sets the total of unknown new accounts. * * @param unknownNewAccounts * the field value. */ public void setUnknownNewAccounts(Integer unknownNewAccounts) { this.unknownNewAccounts = unknownNewAccounts; } /** * Gets the total of unknown active accounts. * * @return the field value */ public Integer getUnknownActiveAccounts() { return unknownActiveAccounts; } /** * Sets the total of unknown active accounts. * * @param unknownActiveAccounts * the field value. */ public void setUnknownActiveAccounts(Integer unknownActiveAccounts) { this.unknownActiveAccounts = unknownActiveAccounts; } /** * Gets the total of unknown accounts. * * @return the field value */ public Integer getUnknownTotal() { return unknownTotal; } /** * Sets the total of unknwon accounts. * * @param unknownTotal * the field value. */ public void setUnknownTotal(Integer unknownTotal) { this.unknownTotal = unknownTotal; } /** * Gets the total of accounts. * * @return the field value */ public Integer getTotalAccounts() { return totalAccounts; } /** * Sets the total accounts. * * @param totalAccounts * the field value. */ public void setTotalAccounts(Integer totalAccounts) { this.totalAccounts = totalAccounts; } }
25.651429
120
0.625306
7d1160fd32fe9ce2d0f6bda9d8a4851c8c41128f
576
package com.fxb.demo1; import redis.clients.jedis.Jedis; import java.util.Iterator; import java.util.Set; /** * @author fangxiaobai on 2017/10/20 14:45. * @description */ public class demo4_RedisKeyJava { public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); System.out.println("connect success"); Set<String> keys = jedis.keys("*"); Iterator<String> it = keys.iterator(); while(it.hasNext()){ String key = it.next(); System.out.println(key); } } }
21.333333
47
0.592014
5bbfb5fc3f8b124f6d7d9e1567e12ca54c6d7c11
5,822
package net.minecraft.server.commands; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.FloatArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import java.util.Collection; import java.util.Iterator; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.EntityArgument; import net.minecraft.commands.arguments.ResourceLocationArgument; import net.minecraft.commands.arguments.coordinates.Vec3Argument; import net.minecraft.commands.synchronization.SuggestionProviders; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.network.protocol.game.ClientboundCustomSoundPacket; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundSource; import net.minecraft.world.phys.Vec3; public class PlaySoundCommand { private static final SimpleCommandExceptionType ERROR_TOO_FAR = new SimpleCommandExceptionType(new TranslatableComponent("commands.playsound.failed")); public static void register(CommandDispatcher<CommandSourceStack> p_138157_) { RequiredArgumentBuilder<CommandSourceStack, ResourceLocation> requiredargumentbuilder = Commands.argument("sound", ResourceLocationArgument.id()).suggests(SuggestionProviders.AVAILABLE_SOUNDS); for(SoundSource soundsource : SoundSource.values()) { requiredargumentbuilder.then(source(soundsource)); } p_138157_.register(Commands.literal("playsound").requires((p_138159_) -> { return p_138159_.hasPermission(2); }).then(requiredargumentbuilder)); } private static LiteralArgumentBuilder<CommandSourceStack> source(SoundSource p_138152_) { return Commands.literal(p_138152_.getName()).then(Commands.argument("targets", EntityArgument.players()).executes((p_138180_) -> { return playSound(p_138180_.getSource(), EntityArgument.getPlayers(p_138180_, "targets"), ResourceLocationArgument.getId(p_138180_, "sound"), p_138152_, p_138180_.getSource().getPosition(), 1.0F, 1.0F, 0.0F); }).then(Commands.argument("pos", Vec3Argument.vec3()).executes((p_138177_) -> { return playSound(p_138177_.getSource(), EntityArgument.getPlayers(p_138177_, "targets"), ResourceLocationArgument.getId(p_138177_, "sound"), p_138152_, Vec3Argument.getVec3(p_138177_, "pos"), 1.0F, 1.0F, 0.0F); }).then(Commands.argument("volume", FloatArgumentType.floatArg(0.0F)).executes((p_138174_) -> { return playSound(p_138174_.getSource(), EntityArgument.getPlayers(p_138174_, "targets"), ResourceLocationArgument.getId(p_138174_, "sound"), p_138152_, Vec3Argument.getVec3(p_138174_, "pos"), p_138174_.getArgument("volume", Float.class), 1.0F, 0.0F); }).then(Commands.argument("pitch", FloatArgumentType.floatArg(0.0F, 2.0F)).executes((p_138171_) -> { return playSound(p_138171_.getSource(), EntityArgument.getPlayers(p_138171_, "targets"), ResourceLocationArgument.getId(p_138171_, "sound"), p_138152_, Vec3Argument.getVec3(p_138171_, "pos"), p_138171_.getArgument("volume", Float.class), p_138171_.getArgument("pitch", Float.class), 0.0F); }).then(Commands.argument("minVolume", FloatArgumentType.floatArg(0.0F, 1.0F)).executes((p_138155_) -> { return playSound(p_138155_.getSource(), EntityArgument.getPlayers(p_138155_, "targets"), ResourceLocationArgument.getId(p_138155_, "sound"), p_138152_, Vec3Argument.getVec3(p_138155_, "pos"), p_138155_.getArgument("volume", Float.class), p_138155_.getArgument("pitch", Float.class), p_138155_.getArgument("minVolume", Float.class)); })))))); } private static int playSound(CommandSourceStack p_138161_, Collection<ServerPlayer> p_138162_, ResourceLocation p_138163_, SoundSource p_138164_, Vec3 p_138165_, float p_138166_, float p_138167_, float p_138168_) throws CommandSyntaxException { double d0 = Math.pow(p_138166_ > 1.0F ? (double)(p_138166_ * 16.0F) : 16.0D, 2.0D); int i = 0; Iterator iterator = p_138162_.iterator(); while(true) { ServerPlayer serverplayer; Vec3 vec3; float f; while(true) { if (!iterator.hasNext()) { if (i == 0) { throw ERROR_TOO_FAR.create(); } if (p_138162_.size() == 1) { p_138161_.sendSuccess(new TranslatableComponent("commands.playsound.success.single", p_138163_, p_138162_.iterator().next().getDisplayName()), true); } else { p_138161_.sendSuccess(new TranslatableComponent("commands.playsound.success.multiple", p_138163_, p_138162_.size()), true); } return i; } serverplayer = (ServerPlayer)iterator.next(); double d1 = p_138165_.x - serverplayer.getX(); double d2 = p_138165_.y - serverplayer.getY(); double d3 = p_138165_.z - serverplayer.getZ(); double d4 = d1 * d1 + d2 * d2 + d3 * d3; vec3 = p_138165_; f = p_138166_; if (!(d4 > d0)) { break; } if (!(p_138168_ <= 0.0F)) { double d5 = Math.sqrt(d4); vec3 = new Vec3(serverplayer.getX() + d1 / d5 * 2.0D, serverplayer.getY() + d2 / d5 * 2.0D, serverplayer.getZ() + d3 / d5 * 2.0D); f = p_138168_; break; } } serverplayer.connection.send(new ClientboundCustomSoundPacket(p_138163_, p_138164_, vec3, f, p_138167_)); ++i; } } }
58.22
341
0.704741
9350de4339d1135a61cfd686d72f01d2c89436c9
796
package mx.uam.archinaut.services; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; import mx.uam.archinaut.data.loader.YamlLoader; import mx.uam.archinaut.model.yaml.YamlConfigurationEntry; public class AbstractServiceTest { @Autowired private YamlLoader yamlLoader; protected YamlConfigurationEntry dependsConfigurationEntry; protected List<YamlConfigurationEntry> nonDependsConfigurationEntries; @BeforeEach public void prepare() throws FileNotFoundException { dependsConfigurationEntry = yamlLoader.getDependsConfigurationEntry("archinaut.yml"); nonDependsConfigurationEntries = yamlLoader.getNonDependsConfigurationEntries("archinaut.yml"); } }
26.533333
97
0.830402
b7bd5b3186a49faa61143a6fde77e619617fa7bc
2,459
package com.wj.spring.encache.Service.impl; import com.wj.spring.encache.Service.DemoInfoService; import com.wj.spring.encache.entity.DemoInfo; import com.wj.spring.encache.exception.NotFoundException; import com.wj.spring.encache.repository.DemoInfoRepository; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class DemoInfoServiceImpl implements DemoInfoService { //这里的单引号不能少,否则会报错,被识别是一个对象; private static final String CACHE_KEY = "'demoInfo'"; @Resource private DemoInfoRepository demoInfoRepository; /** * value属性表示使用哪个缓存策略,缓存策略在ehcache.xml */ private static final String DEMO_CACHE_NAME = "demo"; /** * 保存数据. */ @CacheEvict(value = DEMO_CACHE_NAME, key = CACHE_KEY) @Override public DemoInfo save(DemoInfo demoInfo) { return demoInfoRepository.save(demoInfo); } /** * 查询数据. */ @Cacheable(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#id") @Override public DemoInfo findById(Long id) { System.err.println("没有走缓存!" + id); return demoInfoRepository.findOne(id); } /** * http://www.mincoder.com/article/2096.shtml: * 修改数据. * * 在支持Spring Cache的环境下,对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。 * * 注:@CachePut 也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的。 */ @CachePut(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#updated.getId()") //@CacheEvict(value = DEMO_CACHE_NAME,key = "'demoInfo_'+#updated.getId()")//这是清除缓存. @Override public DemoInfo update(DemoInfo updated) throws NotFoundException { DemoInfo demoInfo = demoInfoRepository.findOne(updated.getId()); if (demoInfo == null) { throw new NotFoundException("No find"); } demoInfo.setName(updated.getName()); demoInfo.setPwd(updated.getPwd()); return demoInfo; } /** * 删除数据. */ @CacheEvict(value = DEMO_CACHE_NAME, key = "'demoInfo_'+#id")//这是清除缓存. @Override public void delete(Long id) { demoInfoRepository.delete(id); } }
31.935065
250
0.702318
52d4a6fc796f272fc242e9beb0efcc59ea5e997b
2,331
package com.tinet.clink.openapi.model; import java.util.Date; import java.util.List; /** * 工单模板实体对象 * * @author liuhy * @date: 2020/11/22 **/ public class WorkflowResultModel { /** * 工单模板主键id */ private Integer id; /** * 工单模板名称 */ private String name; /** * 工单模板类型 1: 预制工作流模板,2: 人工分配模板 */ private Integer type; /** * 工单模板状态。 0: 停用,1: 启用。 */ private Integer status; /** * 工单自定义状态集合 */ private List<String> state; /** * 工单模板类别 Id */ private Integer categoryId; /** * 工单模板类别名称 */ private String categoryName; /** * 工单模板创建时间 */ private Date createTime; /** * 工单模板更新时间 */ private Date updateTime; /** * 工单模板表单实体对象 */ private TicketFormModel form; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public List<String> getState() { return state; } public void setState(List<String> state) { this.state = state; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public TicketFormModel getForm() { return form; } public void setForm(TicketFormModel form) { this.form = form; } }
16.415493
54
0.559846
7012acc1260e72049495c0fb8d44ffccaccb6037
464
package IntroductionToJava.EqualOperator; public class Test { public static void main(String[] args) { A obj1 = new A(); obj1.x = 10; A obj2 = new A(); obj2.x = 10; System.out.println(obj1 == obj2); // false, because addr(obj1) != addr(obj2) System.out.println(obj1.x == obj2.x); // true 10 == 10 A obj3 = obj1; System.out.println(obj3 == obj1); // true } } class A { public int x; }
22.095238
84
0.547414
be1340beb5f9a6e3e220980277708087e9346d5e
547
package com.cgfy.pattern.proxy.dynamicproxy; /** * 测试类 */ public class App { public static void main(String[] args) { // 目标对象 UserDao target = new UserDaoImpl(); // 【原始的类型 class cn.itcast.b_dynamic.UserDao】 System.out.println("目标对象:"+target.getClass()); // 给目标对象,创建代理对象 UserDao proxy = (UserDao) new ProxyFactory(target).getProxyInstance(); // class $Proxy0 内存中动态生成的代理对象 System.out.println("代理对象:"+proxy.getClass()); // 执行方法 【代理对象】 proxy.save(); } }
24.863636
78
0.592322
81f32c7419b7ef5e9478a258b01bfa4ad5bcecf8
5,589
package com.example.controller; import com.example.dto.PatientDTO; import com.example.entities.Patient; import com.example.exceptions.*; import com.example.service.BedService; import com.example.service.ClientService; import com.example.service.DeviceService; import com.example.service.PatientService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.UUID; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/pms") public class OccupancyController { final Logger logger = LogManager.getLogger(OccupancyController.class); @Autowired private PatientService patientService; @Autowired private BedService bedService; @Autowired private ClientService clientService; @Autowired private DeviceService deviceService; @PostMapping("/client/{client_id}/patient") public ResponseEntity<Patient> createPatient(@PathVariable(value = "client_id") UUID client_id, @Valid @RequestBody PatientDTO patientDTO) throws PatientAlreadyExistsException, InvalidDateFormatException, BedDoesNotExistException, BedHasAlreadyBeenOccupiedException, PatientCreatedWithIncorrectStatusWhenAdmittedException, BedDoesNotBelongToSpecifiedClientException { //First we are validating patient for DOB and status as ADMITTED. Then we are checking if bed is VACANT. ONLY THEN we are inserting patient. Once inserting patient we are associating random NOTINUSE Device With bed that patient is associated with patientService.validatePatientDetails(patientDTO); bedService.updateBedStatusWhenPatientAdmitted(patientDTO.getBed_id(), client_id.toString()); logger.info("Bed Status has been updated"); Patient savedPatient = patientService.savePatient(patientDTO, client_id.toString()); logger.info("saving patient"); deviceService.associateDeviceToBed(patientDTO.getBed_id()); return new ResponseEntity<Patient>(savedPatient, HttpStatus.CREATED); } @GetMapping("/client/{client_id}/bed") public ResponseEntity<Map<String,String>> getAllBedStatusForSpecifiedClient(@PathVariable(value = "client_id") UUID client_id) throws ClientDoesNotExistException, BedDoesNotExistException { //FIRST WE ARE CHECKING IF CLIENT WITH ID=client_id EXISTS.Only then we are getting bed status if(clientService.checkIfClientExists(client_id.toString())) { Map<String, String> allBedStatus = bedService.getAllBedStatusByClientId(client_id.toString()); return new ResponseEntity<Map<String, String>>(allBedStatus, HttpStatus.OK); } else{ throw new ClientDoesNotExistException("Client with id = "+client_id.toString()+ "does not exist"); } } @PutMapping("/client/{client_id}/patient/{patient_id}/discharge") public ResponseEntity<Patient> dischargePatient(@PathVariable(value = "client_id") UUID client_id, @PathVariable(value = "patient_id") UUID patient_id) throws PatientDoesNotExistException, PatientHasAlreadyBeenDischargedException, PatientDoesNotBelongToSpecifiedClientException, DeviceDoesNotExistException, BedDoesNotExistException { //NO REQUEST BODY PASSED HERE. Patient dischargedPatient = patientService.dischargePatient(patient_id.toString(), client_id.toString()); bedService.updateBedStatusAfterPatientDischarged(dischargedPatient.getBedId()); deviceService.updateDeviceAfterPatientDischarge(dischargedPatient.getBedId()); return new ResponseEntity<Patient>(dischargedPatient, HttpStatus.OK); } //controller for getting all the empty bed of particular client @GetMapping("/client/{client_id}/emptybeds") public ResponseEntity<List<String>> getEmptyBedsForSpecifiedClient(@PathVariable(value = "client_id") UUID client_id) throws ClientDoesNotExistException, BedDoesNotExistException { //FIRST WE ARE CHECKING IF CLIENT WITH ID=client_id EXISTS.Only then we are getting bed status if(clientService.checkIfClientExists(client_id.toString())) { List<String> emptyBeds = bedService.getEmptyBedsByClientId(client_id.toString()); return new ResponseEntity<List<String>>(emptyBeds, HttpStatus.OK); } else{ throw new ClientDoesNotExistException("Client with id = "+client_id.toString()+ "does not exist"); } } //controller for getting all the patients admitted @GetMapping("/client/{client_id}/admittedpatients") public ResponseEntity<List<Patient>> getPatientsAdmittedToSpecifiedClient(@PathVariable(value = "client_id") UUID client_id) throws ClientDoesNotExistException, BedDoesNotExistException { //FIRST WE ARE CHECKING IF CLIENT WITH ID=client_id EXISTS.Only then we are getting bed status if(clientService.checkIfClientExists(client_id.toString())) { List<Patient> admittedPatients = patientService.getAdmittedPatients(client_id.toString()); return new ResponseEntity<List<Patient>>(admittedPatients, HttpStatus.OK); } else{ throw new ClientDoesNotExistException("Client with id = "+client_id.toString()+ "does not exist"); } } }
54.794118
372
0.749687
a3e269d3c881f5d30e723ac2c047f7bf3b814cda
846
package models.base; import models.Persistent; import javax.persistence.CascadeType; import javax.persistence.OneToMany; import java.util.ArrayList; import java.util.List; @javax.persistence.Entity public class Entity extends Persistent { private String name; private String type; @OneToMany(mappedBy="bearer", cascade= CascadeType.ALL) private List<Sensor> sensors = new ArrayList<>(); public Entity(String type, String name) { this.type = type; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<Sensor> getSensors() { return sensors; } }
18.8
59
0.644208
5e20d84342ead57165462a38134b08950031c814
949
package com.atlassian.plugin.connect.modules.beans.builder; import com.atlassian.plugin.connect.modules.beans.AuthenticationBean; import com.atlassian.plugin.connect.modules.beans.AuthenticationType; public class AuthenticationBeanBuilder { private AuthenticationType type; private String publicKey; public AuthenticationBeanBuilder() { this.type = AuthenticationType.JWT; this.publicKey = ""; } public AuthenticationBeanBuilder(AuthenticationBean defaultBean) { this.publicKey = defaultBean.getPublicKey(); this.type = defaultBean.getType(); } public AuthenticationBeanBuilder withType(AuthenticationType type) { this.type = type; return this; } public AuthenticationBeanBuilder withPublicKey(String key) { this.publicKey = key; return this; } public AuthenticationBean build() { return new AuthenticationBean(this); } }
27.911765
72
0.713383
dbc23c0f9866bacb2f1b984a83e9142efb41beee
207
package com.github.dolphineor.demo01; import org.junit.Test; public class HelloLuceneTest { @Test public void testIndex() { HelloLucene hl = new HelloLucene(); hl.index(); } }
15.923077
43
0.642512
020a05ebd278315010f6e91fd65eee795651edcf
2,421
/* * Copyright (c) 2013-2015. Urban Airship and Contributors */ package com.urbanairship.api.segments.model; import com.google.common.base.Preconditions; import org.apache.commons.lang.StringUtils; public final class LocationAlias { private final String aliasType; private final String aliasValue; public LocationAlias(String aliasType, String aliasValue) { this.aliasType = aliasType; this.aliasValue = aliasValue; } public static Builder newBuilder() { return new Builder(); } public String getAliasValue() { return aliasValue; } public String getAliasType() { return aliasType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocationAlias alias = (LocationAlias) o; if (aliasType != null ? !aliasType.equals(alias.aliasType) : alias.aliasType != null) { return false; } if (aliasValue != null ? !aliasValue.equals(alias.aliasValue) : alias.aliasValue != null) { return false; } return true; } @Override public int hashCode() { int result = aliasType != null ? aliasType.hashCode() : 0; result = 31 * result + (aliasValue != null ? aliasValue.hashCode() : 0); return result; } @Override public String toString() { return "LocationAlias{" + "aliasType='" + aliasType + '\'' + ", aliasValue='" + aliasValue + '\'' + '}'; } public static class Builder { private String aliasType; private String aliasValue; private Builder() { } public Builder setAliasValue(String aliasValue) { this.aliasValue = aliasValue; return this; } public Builder setAliasType(String aliasType) { this.aliasType = aliasType; return this; } public LocationAlias build() { Preconditions.checkArgument(StringUtils.isNotBlank(aliasType), "Alias type must be non empty string"); Preconditions.checkArgument(StringUtils.isNotBlank(aliasValue), "Alias name must be non empty string"); return new LocationAlias(aliasType, aliasValue); } } }
25.755319
115
0.585295
bbce27a5a264f332b51b5b5f6288730829b5c547
2,011
package com.robertovecchio.model.veichle; /** * Questo enum serve a specificare il brand del Taxi, utile ai fini della memorizzazione * @author robertovecchio * @version 1.0 * @since 07/01/2021 * */ public enum BrandType { /** * Caso taxi con brand ABARTH * */ ABARTH, /** * Caso taxi con brand ALFA ROMEO * */ ALFA_ROMEO, /** * Caso taxi con brand AUDI * */ AUDI, /** * Caso taxi con brand BMW * */ BMW, /** * Caso taxi con brand CITROEN * */ CITROEN, /** * Caso taxi con brand DACIA * */ DACIA, /** * Caso taxi con brand FIAT * */ FIAT, /** * Caso taxi con brand FORD * */ FORD, /** * Caso taxi con brand HONDA * */ HONDA, /** * Caso taxi con brand HYUNDAI * */ HYUNDAI, /** * Caso taxi con brand KIA * */ KIA, /** * Caso taxi con brand LANCIA * */ LANCIA, /** * Caso taxi con brand LAND ROVER * */ LAND_ROVER, /** * Caso taxi con brand MAZDA * */ MAZDA, /** * Caso taxi con brand MINI * */ MINI, /** * Caso taxi con brand MITSUBISHI * */ MITSUBISHI, /** * Caso taxi con brand NISSAN * */ NISSAN, /** * Caso taxi con brand OPEL * */ OPEL, /** * Caso taxi con brand PEUGEOT * */ PEUGEOT, /** * Caso taxi con brand RENAULT * */ RENAULT, /** * Caso taxi con brand SEAT * */ SEAT, /** * Caso taxi con brand SKODA * */ SKODA, /** * Caso taxi con brand SUBARU * */ SUBARU, /** * Caso taxi con brand SUZUKI * */ SUZUKI, /** * Caso taxi con brand TATA * */ TATA, /** * Caso taxi con brand TOYOTA * */ TOYOTA, /** * Caso taxi con brand VOLKSWAGEN * */ VOLKSWAGEN, /** * Caso taxi con brand VOLVO * */ VOLVO }
16.483607
88
0.467429
f8570b3a7ac7f1d478ed30cfcf7db2e2332ef929
1,336
package com.js.interpreter.plugins.standard; import com.js.interpreter.ast.expressioncontext.ExpressionContext; import com.js.interpreter.ast.returnsvalue.FunctionCall; import com.js.interpreter.ast.returnsvalue.RValue; import com.js.interpreter.exceptions.ParsingException; import com.js.interpreter.linenumber.LineInfo; import com.js.interpreter.pascaltypes.ArgumentType; import com.js.interpreter.pascaltypes.DeclaredType; import com.js.interpreter.plugins.templated.TemplatedPascalPlugin; public class SetArrayLength implements TemplatedPascalPlugin { SetLength a = new SetLength(); @Override public String name() { return a.name(); } @Override public FunctionCall generateCall(LineInfo line, RValue[] values, ExpressionContext f) throws ParsingException { return a.generateCall(line, values, f); } @Override public FunctionCall generatePerfectFitCall(LineInfo line, RValue[] values, ExpressionContext f) throws ParsingException { return a.generatePerfectFitCall(line, values, f); } @Override public ArgumentType[] argumentTypes() { return a.argumentTypes(); } @Override public DeclaredType return_type() { return a.return_type(); } }
30.363636
110
0.701347
04397e31caf92edce1d636193457266e5deb0175
1,904
package com.mypurecloud.sdk.v2.connector.apache; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import java.security.Principal; import java.util.HashMap; public class ApacheHttpCredentialsProvider implements CredentialsProvider { private HashMap<String, Credentials> map = new HashMap<>(); public ApacheHttpCredentialsProvider(String hostname, int port, String user, String pass) { PrincipalWrapper principalWrapper = new PrincipalWrapper(user); setCredentials(new AuthScope(hostname, port), new CredentialsWrapper(principalWrapper, pass)); } @Override public void setCredentials(AuthScope authScope, Credentials credentials) { map.put(authDescription(authScope), credentials); } @Override public Credentials getCredentials(AuthScope authScope) { return map.get(authDescription(authScope)); } @Override public void clear() { map.clear(); } private String authDescription(AuthScope authScope) { return authScope.getHost() + ":" + authScope.getPort(); } private class CredentialsWrapper implements Credentials { private Principal principal; private String pass; public CredentialsWrapper(Principal principal, String pass) { this.principal = principal; this.pass = pass; } @Override public Principal getUserPrincipal() { return principal; } @Override public String getPassword() { return pass; } } private class PrincipalWrapper implements Principal { private String name; public PrincipalWrapper(String name) { this.name = name; } @Override public String getName() { return name; } } }
26.816901
102
0.662815
fd07abcf7b857d157981310a792ed6201ce7e650
1,382
/* * Copyright © 2020 Cask Data, 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 io.cdap.plugin.sendgrid.common.objects.mail; import com.google.gson.annotations.SerializedName; /** * Mail Settings. */ public class SendGridMailSettings { @SerializedName("footer") private SendGridMailFooter footer; @SerializedName("sandbox_mode") private SendGridSwitch sandboxMode; public SendGridMailSettings(SendGridMailFooter footer, SendGridSwitch sandboxMode) { this.footer = footer; this.sandboxMode = sandboxMode; } public SendGridMailFooter getFooter() { return footer; } public SendGridSwitch getSandboxMode() { return sandboxMode; } public void setFooter(SendGridMailFooter footer) { this.footer = footer; } public void setSandboxMode(SendGridSwitch sandboxMode) { this.sandboxMode = sandboxMode; } }
27.098039
87
0.743126
6dc4f047bf5af7f532b1a3b1b48c52f87cfc04fe
926
package me.javaee.meetup.listeners.scenarios; import me.javaee.meetup.Meetup; import me.javaee.meetup.handlers.Scenario; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import java.util.concurrent.TimeUnit; /* * Copyright (c) 2017, Álvaro Mariano. All rights reserved. * * Do not redistribute without permission from the author. */ public class NoCleanListener implements Listener { @EventHandler public void onDeath(PlayerDeathEvent event) { if (Scenario.getByName("NoClean").isEnabled()) { if (event.getEntity().getKiller() != null) { Player killer = event.getEntity().getKiller(); Meetup.getPlugin().getTimerManager().getCombatTimer().setCooldown(killer, killer.getUniqueId(), TimeUnit.SECONDS.toMillis(20L), true); } } } }
30.866667
150
0.706263
6dc417f3cfaff9dd2c246e8f098293c08537684f
1,745
package com.pengrad.telegrambot.passport.decrypt; import com.google.gson.Gson; import com.pengrad.telegrambot.passport.Credentials; import java.util.Arrays; /** * Stas Parshin * 31 July 2018 */ public class Decrypt { public static Credentials decryptCredentials(String privateKey, String data, String hash, String secret) throws Exception { byte[] s = base64(secret); byte[] encryptedSecret = RsaOaep.decrypt(privateKey, s); byte[] h = base64(hash); SecretHash secretHash = new SecretHash(encryptedSecret, h); byte[] d = base64(data); byte[] encryptedData = decryptAes256Cbc(secretHash.key(), secretHash.iv(), d); String credStr = new String(encryptedData); return new Gson().fromJson(credStr, Credentials.class); } public static String decryptData(String data, String dataHash, String secret) throws Exception { byte[] d = base64(data); byte[] encryptedData = decryptFile(d, dataHash, secret); return new String(encryptedData); } public static byte[] decryptFile(byte[] data, String fileHash, String secret) throws Exception { SecretHash secretHash = new SecretHash(base64(secret), base64(fileHash)); return decryptAes256Cbc(secretHash.key(), secretHash.iv(), data); } private static byte[] decryptAes256Cbc(byte[] key, byte[] iv, byte[] data) throws Exception { byte[] encryptedData = new Aes256Cbc(key, iv).decrypt(data); int padding = encryptedData[0] & 0xFF; encryptedData = Arrays.copyOfRange(encryptedData, padding, encryptedData.length); return encryptedData; } private static byte[] base64(String str) { return Base64.decode(str, 0); } }
34.9
127
0.681375
286b3abb42197b02ace998edb359f9eec97bedc7
863
package com.example.invoice.service; import com.example.invoice.domain.User; import com.example.invoice.domain.UserPrincipal; import com.example.invoice.repository.UserRepository; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService { private UserRepository userRepository; public UserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = this.userRepository.findByUsername(s); return new UserPrincipal(user); } }
34.52
109
0.806489
acb353028b5103c2aea46d0ac72bbb0065bef84c
857
package com.gaohui.nano; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.gaohui.utils.ThemeManageUtil; /** * Created by gaohui on 2017/3/12. */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { int theme = ThemeManageUtil.currentTheme; if(theme != 0){ setTheme(theme); } else{ setTheme(ThemeManageUtil.getCurrentThemeFromPreferenceManager()); } super.onCreate(savedInstanceState); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { this.finish(); } return super.onOptionsItemSelected(item); } }
20.404762
77
0.645274
e78738c301161997038e8d40bec74c5af8f07761
1,931
/* * 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 TestBed; /** * * @author Mohammad Fasha */ import java.util.List; import java.io.StringReader; import edu.stanford.nlp.process.TokenizerFactory; import edu.stanford.nlp.process.CoreLabelTokenFactory; import edu.stanford.nlp.process.PTBTokenizer; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.trees.*; import edu.stanford.nlp.parser.lexparser.LexicalizedParser; import edu.stanford.nlp.process.Tokenizer; import java.io.PrintWriter; import java.io.StringWriter; public class Test2 { static LexicalizedParser lp; public static void main(String[] args) { String parserModel = "D:\\PHD Software\\Arabic APIs\\stanford-parser-3.6.0-models\\edu\\stanford\\nlp\\models\\lexparser\\arabicFactored.ser.gz"; lp = LexicalizedParser.loadModel(parserModel); System.out.println(ParseString("سنضربهم يقوة")); } public static String ParseString(String paraString) { TokenizerFactory<CoreLabel> tokenizerFactory = PTBTokenizer.factory(new CoreLabelTokenFactory(), ""); Tokenizer<CoreLabel> tok = tokenizerFactory.getTokenizer(new StringReader(paraString)); List<CoreLabel> rawWords2 = tok.tokenize(); Tree parse = lp.apply(rawWords2); //parse.pennPrint(); //System.out.println(parse.toString()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); // You can also use a TreePrint object to print trees and dependencies TreePrint tp; tp = new TreePrint("penn,typedDependenciesCollapsed"); tp.printTree(parse,pw); return sw.toString(); } }
32.183333
154
0.673226
ee3849257648a181a8a185b90f3f9191f8b1e64b
22,523
/* * 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.netbeans.modules.maven.problems; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.execution.MavenExecutionResult; import org.apache.maven.model.Plugin; import org.apache.maven.model.building.ModelBuildingException; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.model.resolution.UnresolvableModelException; import org.apache.maven.plugin.PluginManagerException; import org.apache.maven.plugin.PluginResolutionException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.netbeans.api.project.Project; import org.netbeans.modules.maven.NbArtifactFixer; import org.netbeans.modules.maven.NbMavenProjectImpl; import org.netbeans.modules.maven.actions.OpenPOMAction; import org.netbeans.modules.maven.api.NbMavenProject; import org.netbeans.modules.maven.embedder.EmbedderFactory; import org.netbeans.modules.maven.embedder.MavenEmbedder; import org.netbeans.modules.maven.modelcache.MavenProjectCache; import static org.netbeans.modules.maven.problems.Bundle.*; import org.netbeans.spi.project.ActionProgress; import org.netbeans.spi.project.ActionProvider; import org.netbeans.spi.project.ProjectServiceProvider; import org.netbeans.spi.project.ui.ProjectProblemsProvider; import org.openide.filesystems.FileUtil; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.openide.util.lookup.Lookups; import org.netbeans.modules.maven.InternalActionDelegate; /** * Suggests to run priming build. Also serves as a provider for Priming Build action, * as it can share cache with the ProblemProvider. * * @author mkleint */ @ProjectServiceProvider(service = { ProjectProblemsProvider.class, InternalActionDelegate.class, }, projectType = "org-netbeans-modules-maven" ) public class MavenModelProblemsProvider implements ProjectProblemsProvider, InternalActionDelegate { static final ScheduledExecutorService RP = new RequestProcessor(MavenModelProblemsProvider.class); private static final Logger LOG = Logger.getLogger(MavenModelProblemsProvider.class.getName()); private final PropertyChangeSupport support = new PropertyChangeSupport(this); private final Project project; private final AtomicBoolean projectListenerSet = new AtomicBoolean(false); private final AtomicReference<Collection<ProjectProblem>> problemsCache = new AtomicReference<Collection<ProjectProblem>>(); private final PrimingActionProvider primingProvider = new PrimingActionProvider(); private ProblemReporterImpl problemReporter; private final PropertyChangeListener projectListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (NbMavenProject.PROP_PROJECT.equals(evt.getPropertyName())) { firePropertyChange(); } } }; public MavenModelProblemsProvider(Project project) { this.project = project; } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } @Override public Collection<? extends ProjectProblem> getProblems() { Collection<? extends ProjectProblem> prbs = doGetProblems(false); return prbs != null ? prbs : Collections.emptyList(); } /** * Compute problems. If 'sync' is true, the computation is done synchronously. Caches results, * returns cache content immediately, if available. * @param sync true = run synchronously. False = fork computation/ * @return project problems. */ Collection<? extends ProjectProblem> doGetProblems(boolean sync) { final MavenProject prj = project.getLookup().lookup(NbMavenProject.class).getMavenProject(); synchronized (this) { LOG.log(Level.FINER, "Called getProblems for {0}", project); //lazy adding listener only when someone asks for the problems the first time if (projectListenerSet.compareAndSet(false, true)) { //TODO do we check only when the project is opened? problemReporter = project.getLookup().lookup(NbMavenProjectImpl.class).getProblemReporter(); assert problemReporter != null; project.getLookup().lookup(NbMavenProject.class).addPropertyChangeListener(projectListener); } //for non changed project models, no need to recalculate, always return the cached value Object wasprocessed = prj.getContextValue(MavenModelProblemsProvider.class.getName()); if (wasprocessed != null) { Collection<ProjectProblem> cached = problemsCache.get(); LOG.log(Level.FINER, "Project was processed, cached is: {0}", cached); if (cached != null) { return cached; } } Callable<Collection<? extends ProjectProblem>> c = new Callable<Collection<? extends ProjectProblem>>() { @Override public Collection<? extends ProjectProblem> call() throws Exception { Object wasprocessed = prj.getContextValue(MavenModelProblemsProvider.class.getName()); if (wasprocessed != null) { Collection<ProjectProblem> cached = problemsCache.get(); LOG.log(Level.FINER, "Project was processed #2, cached is: {0}", cached); if (cached != null) { return cached; } } List<ProjectProblem> toRet = new ArrayList<>(); MavenExecutionResult res = MavenProjectCache.getExecutionResult(prj); if (res != null && res.hasExceptions()) { toRet.addAll(reportExceptions(res)); } //#217286 doArtifactChecks can call FileOwnerQuery and attempt to aquire the project mutex. toRet.addAll(doArtifactChecks(prj)); //mark the project model as checked once and cached prj.setContextValue(MavenModelProblemsProvider.class.getName(), new Object()); synchronized(MavenModelProblemsProvider.this) { LOG.log(Level.FINER, "Project processing finished, result is: {0}", toRet); problemsCache.set(toRet); } firePropertyChange(); return toRet; } }; if(sync || Boolean.getBoolean("test.reload.sync")) { try { return c.call(); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } else { RP.submit(c); } } // indicate that we do not know return null; } private void firePropertyChange() { support.firePropertyChange(ProjectProblemsProvider.PROP_PROBLEMS, null, null); } @NbBundle.Messages({ "ERR_SystemScope=A 'system' scope dependency was not found. Code completion is affected.", "MSG_SystemScope=There is a 'system' scoped dependency in the project but the path to the binary is not valid.\n" + "Please check that the path is absolute and points to an existing binary.", "ERR_NonLocal=Some dependency artifacts are not in the local repository.", "# {0} - list of artifacts", "MSG_NonLocal=Your project has dependencies that are not resolved locally. " + "Code completion in the IDE will not include classes from these dependencies or their transitive dependencies (unless they are among the open projects).\n" + "Please download the dependencies, or install them manually, if not available remotely.\n\n" + "The artifacts are:\n {0}", "ERR_Participant=Custom build participant(s) found", "MSG_Participant=The IDE will not execute any 3rd party extension code during Maven project loading.\nThese can have significant influence on performance of the Maven model (re)loading or interfere with IDE''s own codebase. " + "On the other hand the model loaded can be incomplete without their participation. In this project " + "we have discovered the following external build participants:\n{0}" }) public Collection<ProjectProblem> doArtifactChecks(@NonNull MavenProject project) { List<ProjectProblem> toRet = new ArrayList<ProjectProblem>(); if (MavenProjectCache.unknownBuildParticipantObserved(project)) { StringBuilder sb = new StringBuilder(); for (String s : MavenProjectCache.getUnknownBuildParticipantsClassNames(project)) { sb.append(s).append("\n"); } toRet.add(ProjectProblem.createWarning(ERR_Participant(), MSG_Participant(sb.toString()))); } toRet.addAll(checkParents(project)); boolean missingNonSibling = false; List<Artifact> missingJars = new ArrayList<Artifact>(); for (Artifact art : project.getArtifacts()) { File file = art.getFile(); if (file == null || !file.exists()) { if(Artifact.SCOPE_SYSTEM.equals(art.getScope())){ //TODO create a correction action for this. toRet.add(ProjectProblem.createWarning(ERR_SystemScope(), MSG_SystemScope(), new ProblemReporterImpl.MavenProblemResolver(OpenPOMAction.instance().createContextAwareInstance(Lookups.fixed(project)), "SCOPE_DEPENDENCY"))); } else { problemReporter.addMissingArtifact(art); if (file == null) { missingNonSibling = true; } else { final URL archiveUrl = FileUtil.urlForArchiveOrDir(file); if (archiveUrl != null) { //#236050 null check //a.getFile should be already normalized SourceForBinaryQuery.Result2 result = SourceForBinaryQuery.findSourceRoots2(archiveUrl); if (!result.preferSources() || /* SourceForBinaryQuery.EMPTY_RESULT2.preferSources() so: */ result.getRoots().length == 0) { missingNonSibling = true; } // else #189442: typically a snapshot dep on another project } } missingJars.add(art); } } else if (NbArtifactFixer.isFallbackFile(file)) { problemReporter.addMissingArtifact(art); missingJars.add(art); missingNonSibling = true; } } if (!missingJars.isEmpty()) { StringBuilder mess = new StringBuilder(); for (Artifact art : missingJars) { mess.append(art.getId()).append('\n'); } if (missingNonSibling) { toRet.add(ProjectProblem.createWarning(ERR_NonLocal(), MSG_NonLocal(mess), createSanityBuildAction())); } else { //we used to have a LOW severity ProblemReport here. } } return toRet; } @NbBundle.Messages({ "ERR_NoParent=Parent POM file is not accessible. Project might be improperly setup.", "# {0} - Maven coordinates", "MSG_NoParent=The parent POM with id {0} was not found in sources or local repository. " + "Please check that <relativePath> tag is present and correct, the version of parent POM in sources matches the version defined. \n" + "If parent is only available through a remote repository, please check that the repository hosting it is defined in the current POM." }) private Collection<ProjectProblem> checkParents(@NonNull MavenProject project) { List<MavenEmbedder.ModelDescription> mdls = MavenEmbedder.getModelDescriptors(project); boolean first = true; if (mdls == null) { //null means just about broken project.. return Collections.emptyList(); } List<ProjectProblem> toRet = new ArrayList<ProjectProblem>(); for (MavenEmbedder.ModelDescription m : mdls) { if (first) { first = false; continue; } if (NbArtifactFixer.FALLBACK_NAME.equals(m.getName())) { toRet.add(ProjectProblem.createError(ERR_NoParent(), MSG_NoParent(m.getId()), createSanityBuildAction())); problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(m.getGroupId(), m.getArtifactId(), m.getVersion(), "pom")); } } return toRet; } /** * Will keep a reference to the sanity build, if it was created, as long as * Problems exist. */ private Reference<SanityBuildAction> cachedSanityBuild = new WeakReference<>(null); public SanityBuildAction createSanityBuildAction() { synchronized (this) { SanityBuildAction a = cachedSanityBuild.get(); if (a != null) { Future<ProjectProblemsProvider.Result> r = a.getPendingResult(); if (r != null) { return a; } } a = new SanityBuildAction(project); cachedSanityBuild = new WeakReference<>(a); return a; } } @NbBundle.Messages({ "TXT_Artifact_Resolution_problem=Artifact Resolution problem", "TXT_Artifact_Not_Found=Artifact Not Found", "TXT_Cannot_Load_Project=Unable to properly load project", "TXT_Cannot_read_model=Error reading project model", "TXT_NoMsg=Exception thrown while loading maven project at {0}. See messages.log for more information." }) private Collection<ProjectProblem> reportExceptions(MavenExecutionResult res) { List<ProjectProblem> toRet = new ArrayList<ProjectProblem>(); for (Throwable e : res.getExceptions()) { LOG.log(Level.FINE, "Error on loading project " + project.getProjectDirectory(), e); if (e instanceof ArtifactResolutionException) { // XXX when does this occur? toRet.add(ProjectProblem.createError(TXT_Artifact_Resolution_problem(), getDescriptionText(e))); problemReporter.addMissingArtifact(((ArtifactResolutionException) e).getArtifact()); } else if (e instanceof ArtifactNotFoundException) { // XXX when does this occur? toRet.add(ProjectProblem.createError(TXT_Artifact_Not_Found(), getDescriptionText(e))); problemReporter.addMissingArtifact(((ArtifactNotFoundException) e).getArtifact()); } else if (e instanceof ProjectBuildingException) { toRet.add(ProjectProblem.createError(TXT_Cannot_Load_Project(), getDescriptionText(e), createSanityBuildAction())); if (e.getCause() instanceof ModelBuildingException) { ModelBuildingException mbe = (ModelBuildingException) e.getCause(); for (ModelProblem mp : mbe.getProblems()) { LOG.log(Level.FINE, mp.toString(), mp.getException()); if (mp.getException() instanceof UnresolvableModelException) { // Probably obsoleted by ProblemReporterImpl.checkParent, but just in case: UnresolvableModelException ume = (UnresolvableModelException) mp.getException(); problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createProjectArtifact(ume.getGroupId(), ume.getArtifactId(), ume.getVersion())); } else if (mp.getException() instanceof PluginResolutionException) { Plugin plugin = ((PluginResolutionException) mp.getException()).getPlugin(); // XXX this is not actually accurate; should rather pick out the ArtifactResolutionException & ArtifactNotFoundException inside problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion(), "jar")); } else if (mp.getException() instanceof PluginManagerException) { PluginManagerException ex = (PluginManagerException) mp.getException(); problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(ex.getPluginGroupId(), ex.getPluginArtifactId(), ex.getPluginVersion(), "jar")); } } } } else { String msg = e.getMessage(); if(msg != null) { LOG.log(Level.INFO, "Exception thrown while loading maven project at " + project.getProjectDirectory(), e); //NOI18N toRet.add(ProjectProblem.createError(TXT_Cannot_read_model(), msg)); } else { String path = project.getProjectDirectory().getPath(); toRet.add(ProjectProblem.createError(TXT_Cannot_read_model(), TXT_NoMsg(path))); LOG.log(Level.WARNING, "Exception thrown while loading maven project at " + path, e); //NOI18N } } } return toRet; } private String getDescriptionText(Throwable e) { String msg = e.getMessage(); if(msg != null) { return msg; } else { String path = project.getProjectDirectory().getPath(); return TXT_NoMsg(path); } } //------------------------------------------------------------------------- // ActionProvider implementation private static final String[] PROBLEM_ACTIONS = { ActionProvider.COMMAND_PRIME }; @Override public ActionProvider getActionProvider() { return primingProvider; } private class PrimingActionProvider implements ActionProvider { @Override public String[] getSupportedActions() { return PROBLEM_ACTIONS; } @Override public void invokeAction(String command, Lookup context) throws IllegalArgumentException { final ActionProgress listener = ActionProgress.start(context); if (!PROBLEM_ACTIONS[0].equals(command)) { throw new IllegalArgumentException(command); } // just keep the reference, so SABA is not collected. Collection<? extends ProjectProblem> probs = doGetProblems(true); // sanity build action has been created SanityBuildAction saba = cachedSanityBuild.get(); if (saba == null) { listener.finished(true); } else { CompletableFuture<ProjectProblemsProvider.Result> r = saba.resolve(); r.whenComplete((a, e) -> { listener.finished(e == null); }); } } @Override public boolean isActionEnabled(String command, Lookup context) throws IllegalArgumentException { if (!PROBLEM_ACTIONS[0].equals(command)) { return false; } Collection<? extends ProjectProblem> probs = doGetProblems(false); if (probs == null) { // no value means that cache was not populated yet, Conservatively enable. return true; } if (probs.isEmpty()) { // problems identified: there are none. No primiing build. return false; } // sanity build action has been created SanityBuildAction saba = cachedSanityBuild.get(); if (saba == null) { // other problems, but no need to prime. return false; } Future<?> res = saba.getPendingResult(); // do not enabel, if the priming build was already started. return res == null || !res.isDone(); } } }
50.387025
241
0.635351
0859b1b8b5d697fe246caad7ec50102774ac24d1
711
package org.clickandcollect.model.entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class SelectedProduct { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) private ProductInCourse productInCourse; @ManyToOne(fetch = FetchType.LAZY) private MenuOrder menuOrder; }
22.935484
55
0.803094
c4e056e93c79e0d583e61ca8f31ee05cba0c68ed
3,137
package com.tiny.demo.firstlinecode.kfysts.chapter04.ui; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.view.View; import com.tiny.demo.firstlinecode.R; /** * Desc: * * @author tiny * @date 2018/4/15 下午7:54 */ public class CircleView extends View { private int mColor = Color.RED; private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public CircleView(Context context) { super(context); init(context, null); } public CircleView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); } private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView); mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED); a.recycle(); mPaint.setColor(mColor); } private int mDefaultWidth = 200; private int mDefaultHeight = 200; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); /** * 使用默认宽高对wrap_content做处理。 */ int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(mDefaultWidth, mDefaultHeight); } else if (widthSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(mDefaultWidth, heightSpecSize); } else if (heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSpecSize, mDefaultHeight); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //需要支持padding int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int width = getWidth() - paddingLeft - paddingRight; int height = getHeight() - paddingTop - paddingBottom; int radius = Math.min(width, height) / 2; canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint); } }
34.097826
105
0.689512
8c990a35e79691e6b7914cba1ec6a603fe60c98e
21,865
package com.innoz.toolbox.scenarioGeneration.network; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Logger; import org.geotools.referencing.CRS; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.core.network.NetworkChangeEvent; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.NetworkChangeEvent.ChangeType; import org.matsim.core.network.NetworkChangeEvent.ChangeValue; import org.matsim.core.network.algorithms.NetworkCleaner; import org.matsim.core.utils.collections.CollectionUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.misc.Time; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import com.innoz.toolbox.config.Configuration; import com.innoz.toolbox.config.groups.ConfigurationGroup; import com.innoz.toolbox.config.groups.NetworkConfigurationGroup; import com.innoz.toolbox.config.groups.NetworkConfigurationGroup.HighwayDefaults; import com.innoz.toolbox.io.database.DatabaseReader; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.io.ParseException; /** * * This class provides functionalities to create and modify a {@link org.matsim.api.core.v01.network.Network} * by using OpenStreetMap data stored in a postgreSQL database. * * @author dhosse * */ public class NetworkCreatorFromPsql { private static final Logger log = Logger.getLogger(NetworkCreatorFromPsql.class); //CONSTANTS////////////////////////////////////////////////////////////////////////////// private final Network network; private final List<NetworkChangeEvent> networkChangeEvents = new ArrayList<>(); private final CoordinateTransformation transformation; private final Configuration configuration; public static final String MOTORWAY = "motorway"; public static final String MOTORWAY_LINK = "motorway_link"; public static final String TRUNK = "trunk"; public static final String TRUNK_LINK = "trunk_link"; public static final String PRIMARY = "primary"; public static final String PRIMARY_LINK = "primary_link"; public static final String SECONDARY = "secondary"; public static final String TERTIARY = "tertiary"; public static final String MINOR = "minor"; public static final String UNCLASSIFIED = "unclassified"; public static final String RESIDENTIAL = "residential"; public static final String LIVING_STREET = "living_street"; ///////////////////////////////////////////////////////////////////////////////////////// //MEMBERS//////////////////////////////////////////////////////////////////////////////// private static AtomicInteger linkCounter = new AtomicInteger(0); private Map<String, OsmNodeEntry> nodes = new HashMap<>(); private Map<String, WayEntry> ways = new HashMap<>(); private boolean scaleMaxSpeed = false; private boolean cleanNetwork = false; private boolean simplifyNetwork = false; private GeometryFactory gf; private Set<String> unknownTags = new HashSet<>(); private Map<String, HighwayDefaults> highwayDefaults = new HashMap<String, HighwayDefaults>(); private Geometry bufferedArea; //TODO what can you modify? static enum modification{}; /*TODO make network generation depend on * 1)sample size * 2)survey area or surrounding */ private int levelOfDetail = 6; ///////////////////////////////////////////////////////////////////////////////////////// /** * * Constructor. * * @param network An empty MATSim network. * @param configuration The scenario generation configuration. * @throws FactoryException * @throws NoSuchAuthorityCodeException */ public NetworkCreatorFromPsql(final Network network, Configuration configuration) throws NoSuchAuthorityCodeException, FactoryException{ this.network = network; CoordinateReferenceSystem from = CRS.decode("EPSG:4326", true); CoordinateReferenceSystem to = CRS.decode(configuration.misc().getCoordinateSystem(), true); this.transformation = TransformationFactory.getCoordinateTransformation( from.toString(), to.toString()); this.configuration = configuration; NetworkConfigurationGroup net = configuration.network(); this.cleanNetwork = net.cleanNetwork(); this.simplifyNetwork = net.isSimplifyNetwork(); this.scaleMaxSpeed = net.scaleMaxSpeed(); }; /** * * The main method of the {@code NetworkCreatorFromPsql}. * Via database connection OpenStreetMap road data is retrieved and converted into a MATSim network. * * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException * @throws SQLException * @throws ParseException */ public void create() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException, ParseException{ for(ConfigurationGroup c : this.configuration.network().getHighwayDefaults().values()) { HighwayDefaults def = (HighwayDefaults) c; this.highwayDefaults.put(def.getHighwayType(), def); } // If highway defaults have been specified, use them. Else fall back to default values. if(this.highwayDefaults.size() < 1){ this.setHighwayDefaultsAccordingToLevelOfDetail(); } // Convert the way entries into a MATSim network DatabaseReader.getInstance().readOsmRoads(this.configuration, ways, nodes); this.bufferedArea = DatabaseReader.getInstance().getBufferedArea(); processEntries(); // Clean the network to avoid dead ends during simulation (clustered network) if(this.cleanNetwork){ new NetworkCleaner().run(network); } } /** * * The main method of the {@code NetworkCreatorFromPsql}. * Via database connection OpenStreetMap road data is retrieved and converted into a MATSim network. * * In addition, you can set the level of detail for the network (default value is "6"). The lower hierarchies contain the higher * hierarchies' highway types) * <ul> * <li>1: motorways * <li>2: trunk roads * <li>3: primary roads * <li>4: secondary roads * <li>5: tertiary roads * <li>6: residential roads (minor, unclassified, residential, living street) * </ul> * * @param dbReader * @param levelOfDetail * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException * @throws SQLException * @throws ParseException */ public void create(int levelOfDetail) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException, ParseException{ this.levelOfDetail = levelOfDetail; this.create(); } /** * * Setter for highway defaults. * * @param highwayType The road type. * @param lanesPerDirection Number of lanes per direction. * @param freespeed Allowed free speed on this road type. * @param freespeedFactor Factor for scaling of free speed. * @param laneCapacity_vehPerHour The capacity of one lane on this road type per hour. * @param oneway Road type is only accessible in one direction or not. */ public void setHighwayDefaults(final int hierarchyLevel, final String highwayType, final double lanesPerDirection, final double freespeed, final double freespeedFactor, final double laneCapacity_vehPerHour, final boolean oneway, String modes){ this.highwayDefaults.put(highwayType, new HighwayDefaults(hierarchyLevel, highwayType, freespeed, freespeedFactor, lanesPerDirection, laneCapacity_vehPerHour, oneway, modes)); } /** * * Setter for highway defaults. The one way attribute is set to false in this method. * * @param highwayType The road type. * @param lanesPerDirection Number of lanes per direction. * @param freespeed Allowed free speed on this road type. * @param freespeedFactor Factor for scaling of free speed. * @param laneCapacity_vehPerHour The capacity of one lane on this road type per hour. */ public void setHighwayDefaults(final int hierarchyLevel, final String highwayType, final double lanesPerDirection, final double freespeed, final double freespeedFactor, final double laneCapacity_vehPerHour, String modes){ this.setHighwayDefaults(hierarchyLevel, highwayType, lanesPerDirection, freespeed, freespeedFactor, laneCapacity_vehPerHour, false, modes); } /** * Default setter for the highway defaults. If no defaults were specified, this * method is called and sets the defaults according to the level of detail specified. */ private void setHighwayDefaultsAccordingToLevelOfDetail(){ this.setHighwayDefaults(1, MOTORWAY, 2.0, 100/3.6, 1.2, 2000.0, true, "car"); this.setHighwayDefaults(1, MOTORWAY_LINK, 1, 60.0/3.6, 1.2, 1500, true, "car"); if(this.levelOfDetail > 1){ this.setHighwayDefaults(2, TRUNK, 1, 80.0/3.6, 0.5, 1000, "car"); this.setHighwayDefaults(2, TRUNK_LINK, 1, 60.0/3.6, 0.5, 1500, "car"); if(this.levelOfDetail > 2){ this.setHighwayDefaults(3, PRIMARY, 1, 50.0/3.6, 0.5, 1000, "car"); this.setHighwayDefaults(3, PRIMARY_LINK, 1, 50.0/3.6, 0.5, 1000, "car"); if(this.levelOfDetail > 3){ this.setHighwayDefaults(4, SECONDARY, 1, 50.0/3.6, 0.5, 1000, "car"); if(this.levelOfDetail > 4){ if(this.configuration.scenario().getScaleFactor() <= 0.1) return; this.setHighwayDefaults(5, TERTIARY, 1, 30.0/3.6, 0.8, 600, "car"); if(this.levelOfDetail > 5){ this.setHighwayDefaults(6, MINOR, 1, 30.0/3.6, 0.8, 600, "car"); this.setHighwayDefaults(6, UNCLASSIFIED, 1, 30.0/3.6, 0.8, 600, "car"); this.setHighwayDefaults(6, RESIDENTIAL, 1, 30.0/3.6, 0.6, 600, "car"); this.setHighwayDefaults(6, LIVING_STREET, 1, 15.0/3.6, 1.0, 600, "car"); } } } } } } /** * * Method to perform changes on an existing network (e.g. additional network modes, additional links). * * @param network */ public void modify(Network network){ } /** * * Transforms OSM ways into MATSim nodes and links and adds them to the network. * * @param wayEntries The collection of entries for each OSM way. */ private void processEntries(){ this.gf = new GeometryFactory(); for(WayEntry entry : this.ways.values()){ String highway = entry.getHighwayTag(); if(highway != null && this.highwayDefaults.containsKey(highway)){ nodes.get(entry.getNodes().get(0)).incrementWays(); nodes.get(entry.getNodes().get(entry.getNodes().size()-1)).incrementWays(); for(String id : entry.getNodes()){ OsmNodeEntry node = nodes.get(id); node.incrementWays(); boolean inSurveyArea = this.bufferedArea.contains(MGC.coord2Point(node.getCoord())); int hierarchyLevel = inSurveyArea ? this.levelOfDetail : this.levelOfDetail - 2; if(this.highwayDefaults.get(entry.getHighwayTag()).getHierarchyLevel() <= hierarchyLevel){ node.setUsed(true); } } } } if(this.simplifyNetwork){ for(OsmNodeEntry entry : this.nodes.values()){ if(entry.getWays() == 1){ entry.setUsed(false); } } } for(WayEntry entry : this.ways.values()){ String highway = entry.getHighwayTag(); if(highway != null && this.highwayDefaults.containsKey(highway)){ int prevRealNodeIndex = 0; OsmNodeEntry prevRealNode = this.nodes.get(entry.getNodes().get(prevRealNodeIndex)); for (int i = 1; i < entry.getNodes().size(); i++) { OsmNodeEntry node = this.nodes.get(entry.getNodes().get(i)); if(node.isUsed()){ if(prevRealNode == node){ double increment = Math.sqrt(i - prevRealNodeIndex); double nextNodeToKeep = prevRealNodeIndex + increment; for (double j = nextNodeToKeep; j < i; j += increment) { int index = (int) Math.floor(j); OsmNodeEntry intermediaryNode = this.nodes.get(entry.getNodes().get(index)); intermediaryNode.setUsed(true); } } prevRealNodeIndex = i; prevRealNode = node; } } } } for(OsmNodeEntry node : this.nodes.values()){ if(node.isUsed()){ Node nn = this.network.getFactory().createNode(Id.createNodeId(node.getId()), this.transformation.transform(node.getCoord())); this.network.addNode(nn); } } for(WayEntry way : this.ways.values()){ String highway = way.getHighwayTag(); if(highway != null){ OsmNodeEntry fromNode = this.nodes.get(way.getNodes().get(0)); double length = 0.0d; OsmNodeEntry lastToNode = fromNode; if(fromNode.isUsed()){ for (int i = 1, n = way.getNodes().size(); i < n; i++) { OsmNodeEntry toNode = this.nodes.get(way.getNodes().get(i)); if(toNode != lastToNode){ length += CoordUtils.calcEuclideanDistance(this.transformation.transform(lastToNode.getCoord()), this.transformation.transform(toNode.getCoord())); if(toNode.isUsed()){ this.createLink(way, length, fromNode, toNode); fromNode = toNode; length = 0.0; } lastToNode = toNode; } } } } } log.info("Conversion statistics:"); log.info("OSM nodes: " + nodes.size()); log.info("OSM ways: " + ways.size()); log.info("MATSim nodes: " + network.getNodes().size()); log.info("MATSim links: " + network.getLinks().size()); } public void createLink(WayEntry entry, double length, OsmNodeEntry fromNode, OsmNodeEntry toNode){ HighwayDefaults defaults = this.highwayDefaults.get(entry.getHighwayTag()); // If there are defaults for the highway type of the current way, we proceed // Else the way is simply skipped if(defaults != null){ //set all values to default double freespeed = defaults.getFreespeed(); double freespeedFactor = defaults.getFreespeedFactor(); double lanesPerDirection = defaults.getLanesPerDirection(); double laneCapacity = defaults.getLaneCapacity(); boolean oneway = defaults.isOneway(); boolean onewayReverse = false; Set<String> modes = CollectionUtils.stringToSet(defaults.getModes()); // Handle the freespeed tag String freespeedTag = entry.getMaxspeedTag(); if(freespeedTag != null){ try{ freespeed = Double.parseDouble(freespeedTag) / 3.6; } catch(NumberFormatException e){ freespeed = resolveUnknownFreespeedTag(freespeedTag); if(!unknownTags.contains(freespeedTag) && freespeed == 0){ unknownTags.add(freespeedTag); log.warn("Could not parse freespeed tag: " + freespeedTag + ". Ignoring it."); } } } if("roundabout".equals(entry.getJunctionTag())){ oneway = true; } // Handle the oneway tag if(entry.getOnewayTag() != null){ if(entry.getOnewayTag().equals("yes") || entry.getOnewayTag().equals("true") || entry.getOnewayTag().equals("1")){ oneway = true; } else if(entry.getOnewayTag().equals("no")){ oneway = false; } else if(entry.getOnewayTag().equals("-1")){ onewayReverse = true; oneway = false; } } if(entry.getHighwayTag().equalsIgnoreCase(TRUNK) || entry.getHighwayTag().equalsIgnoreCase(PRIMARY) || entry.getHighwayTag().equalsIgnoreCase(SECONDARY)){ if((oneway || onewayReverse) && lanesPerDirection == 1.0){ lanesPerDirection = 2.0; } } // Handle the lanes tag. String lanesTag = entry.getLanesTag(); if(lanesTag != null){ try { double totalNofLanes = Double.parseDouble(lanesTag); if (totalNofLanes > 0) { lanesPerDirection = totalNofLanes; if (!oneway && !onewayReverse) { lanesPerDirection /= 2.; } } } catch (Exception e) { if(!unknownTags.contains(lanesTag)){ unknownTags.add(freespeedTag); log.warn("Could not parse lanes tag: " + freespeedTag + ". Ignoring it."); } } } // Set the link's capacity and the resulting freespeed (if it's meant to be scaled) double capacity = lanesPerDirection * laneCapacity; //MATSim seems to have problems with lane numbers smaller than 1 //This can be fixed here since we already took the reduced capacity into account if(lanesPerDirection < 1d){ lanesPerDirection = 1d; } if(this.scaleMaxSpeed){ freespeed *= freespeedFactor; } String origId = entry.getOsmId(); synchronized(linkCounter){ Id<Node> from = Id.createNodeId(fromNode.getId()); Id<Node> to = Id.createNodeId(toNode.getId()); if(this.network.getNodes().get(from) != null && this.network.getNodes().get(to) != null){ String conditionalSpeed = entry.getConditionalMaxspeedTag(); // Create a link in one direction if(!onewayReverse){ double lanes = lanesPerDirection; if(entry.getForwardLanesTag() != null) { lanes = Double.parseDouble(entry.getForwardLanesTag()); } Link link = network.getFactory().createLink(Id.createLinkId(linkCounter.get()), this.network.getNodes().get(from), this.network.getNodes().get(to)); link.setCapacity(capacity); link.setFreespeed(freespeed); link.setLength(length); link.setNumberOfLanes(lanes); link.setAllowedModes(modes); NetworkUtils.setOrigId(link, origId); NetworkUtils.setType(link, entry.getHighwayTag()); network.addLink(link); linkCounter.incrementAndGet(); if(conditionalSpeed != null) { resolveConditionalSpeed(conditionalSpeed, link); } } // If it's not a oneway link, create another link in the opposite direction if(!oneway){ double lanes = lanesPerDirection; if(entry.getBackwardLanesTag() != null) { lanes = Double.parseDouble(entry.getBackwardLanesTag()); } else if(entry.getForwardLanesTag() != null) { lanes -= Double.parseDouble(entry.getForwardLanesTag()); if(lanes <= 0) lanes = 1; } Link link = network.getFactory().createLink(Id.createLinkId(linkCounter.get()), this.network.getNodes().get(to), this.network.getNodes().get(from)); link.setCapacity(capacity); link.setFreespeed(freespeed); link.setLength(length); link.setNumberOfLanes(lanes); link.setAllowedModes(modes); NetworkUtils.setOrigId(link, origId); NetworkUtils.setType(link, entry.getHighwayTag()); network.addLink(link); linkCounter.incrementAndGet(); if(conditionalSpeed != null) { resolveConditionalSpeed(conditionalSpeed, link); } } } } } } private double resolveUnknownFreespeedTag(String s){ double kmh = 0; if("DE:urban".equals(s)){ kmh = 50; } else if("DE:rural".equals(s)){ kmh = 100; } else if("DE:motorway".equals(s) || "none".equals(s)){ kmh = 130; } else if("walk".equals(s) || "DE:living_street".equals(s)){ kmh = 5; } else if("5 mph".equals(s)){ kmh = 5 * 1.609; } else if(s.contains(";")){ kmh = Double.parseDouble(s.split(";")[0]); } return kmh / 3.6; } public void resolveConditionalSpeed(String c, Link l) { // We can't model weather conditions... yet if(c.contains("wet") || !c.contains(":")) return; String[] parts = c.split("@"); String[] timeStringArray = parts[1].split("-"); double speed = Double.parseDouble(parts[0]); String startTimeString = timeStringArray[0].replace("(", ""); if(startTimeString.startsWith("0")) startTimeString.substring(1, startTimeString.length()); double startTime = Time.parseTime(startTimeString); double endTime = Time.parseTime(timeStringArray[1].replace(")", "")); if(endTime < startTime) endTime += Time.MIDNIGHT; // Reduce the free speed at start time { NetworkChangeEvent event = new NetworkChangeEvent(startTime); ChangeValue freespeedChange = new ChangeValue(ChangeType.ABSOLUTE_IN_SI_UNITS, speed / 3.6); event.setFreespeedChange(freespeedChange); event.addLink(l); this.networkChangeEvents.add(event); } // Increase free speed when the event is over { NetworkChangeEvent event = new NetworkChangeEvent(endTime); ChangeValue freespeedChange = new ChangeValue(ChangeType.ABSOLUTE_IN_SI_UNITS, l.getFreespeed()); event.setFreespeedChange(freespeedChange); event.addLink(l); this.networkChangeEvents.add(event); } } public Geometry getBufferedArea(){ return this.bufferedArea; } public GeometryFactory getGeomFactory(){ return this.gf; } public CoordinateTransformation getTransformation(){ return this.transformation; } public List<NetworkChangeEvent> getNetworkChangeEvents() { return this.networkChangeEvents; } }
29.547297
154
0.665859
bb302914fe6c767edf782c846980c0304fe21c37
2,569
package com.igoosd.api; import com.igoosd.domain.User; import com.igoosd.domain.vo.ResultMsg; import com.igoosd.exception.StaticException; import com.igoosd.util.RoadPricingException; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Set; import static com.igoosd.util.Constants.SESSION_USER_KEY; public abstract class BaseController<T> { protected User getUserFromSession(HttpServletRequest request) { return (User) request.getSession().getAttribute(SESSION_USER_KEY); } protected List<Long> getIdList(String ids) { Set<String> strSet = StringUtils.commaDelimitedListToSet(ids); List<Long> idList = new ArrayList<>(strSet.size()); try { for (String idStr : strSet) { idList.add(Long.valueOf(idStr)); } } catch (Exception e) { throw new RoadPricingException("无效的参数"); } return idList; } /** * 0 补齐 如 3位 1-> 001 * * @param value * @param length * @return */ protected String preFixZero(int value, int length) { NumberFormat numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMaximumIntegerDigits(length); numberFormat.setMinimumIntegerDigits(length); return numberFormat.format(value); } protected ResultMsg<?> verifyCodeForList(List<T> list, T t) { return verifyForList(list,t,"编码"); } protected ResultMsg<?> verifyForList(List<T> list, T t,String fieldDescName) { if (!CollectionUtils.isEmpty(list)) { Long id = getId(t); if (id != null) { if (!id.equals(getId(list.get(0)))) { return ResultMsg.resultFail(fieldDescName + "不唯一"); } } else { return ResultMsg.resultFail(fieldDescName +"不唯一"); } } return ResultMsg.resultSuccess(fieldDescName + "校验成功"); } private Long getId(T t) { Long id; try { Class clazz = t.getClass(); Method method = clazz.getMethod("getId"); id = (Long) method.invoke(t); } catch (Exception e) { throw new StaticException("获取ID异常id"); } return id; } }
30.583333
83
0.599844
8c918f6a7af268537acfc513e43f96aef3a95dae
3,160
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.keyguard; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import android.support.test.filters.SmallTest; import android.testing.AndroidTestingRunner; import com.android.systemui.SysuiTestCase; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; @RunWith(AndroidTestingRunner.class) @SmallTest public class ScreenLifecycleTest extends SysuiTestCase { private ScreenLifecycle mScreen; private ScreenLifecycle.Observer mScreenObserverMock; @Before public void setUp() throws Exception { mScreen = new ScreenLifecycle(); mScreenObserverMock = mock(ScreenLifecycle.Observer.class); mScreen.addObserver(mScreenObserverMock); } @Test public void baseState() throws Exception { assertEquals(ScreenLifecycle.SCREEN_OFF, mScreen.getScreenState()); verifyNoMoreInteractions(mScreenObserverMock); } @Test public void screenTurningOn() throws Exception { mScreen.dispatchScreenTurningOn(); assertEquals(ScreenLifecycle.SCREEN_TURNING_ON, mScreen.getScreenState()); verify(mScreenObserverMock).onScreenTurningOn(); } @Test public void screenTurnedOn() throws Exception { mScreen.dispatchScreenTurningOn(); mScreen.dispatchScreenTurnedOn(); assertEquals(ScreenLifecycle.SCREEN_ON, mScreen.getScreenState()); verify(mScreenObserverMock).onScreenTurnedOn(); } @Test public void screenTurningOff() throws Exception { mScreen.dispatchScreenTurningOn(); mScreen.dispatchScreenTurnedOn(); mScreen.dispatchScreenTurningOff(); assertEquals(ScreenLifecycle.SCREEN_TURNING_OFF, mScreen.getScreenState()); verify(mScreenObserverMock).onScreenTurningOff(); } @Test public void screenTurnedOff() throws Exception { mScreen.dispatchScreenTurningOn(); mScreen.dispatchScreenTurnedOn(); mScreen.dispatchScreenTurningOff(); mScreen.dispatchScreenTurnedOff(); assertEquals(ScreenLifecycle.SCREEN_OFF, mScreen.getScreenState()); verify(mScreenObserverMock).onScreenTurnedOff(); } @Test public void dump() throws Exception { mScreen.dump(null, new PrintWriter(new ByteArrayOutputStream()), new String[0]); } }
32.244898
88
0.737025
7869bf18e1b0fa6886d7910a563227156bbcccf8
2,069
package com.smithkatakkar.hauntingmod.testrunner; import net.minecraft.launchwrapper.Launch; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.TestClass; import java.lang.reflect.Method; /** * Created by ben on 01/02/17. * * Inspired by https://github.com/vorburger/SwissKnightMinecraft */ public class MinecraftTestRunner extends BlockJUnit4ClassRunner { public MinecraftTestRunner(Class<?> clazz) throws InitializationError { super(getFromTestClassloader(clazz)); } private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError { try { Launch.main(new String[] {"--tweakClass", "com.smithkatakkar.hauntingmod.testrunner.tweaker.Tweaker"}); // This is *VERY* important, because without this // JUnit will be vey unhappy when in MinecraftTestRunner // we replace the class under test with the one from the // Minecraft ClassLoader instead of the parent one into // which JUnit Framework classes were already loaded Launch.classLoader.addClassLoaderExclusion("junit."); Launch.classLoader.addClassLoaderExclusion("org.junit."); Class<?> startupClass = Class.forName("mockit.internal.startup.Startup", false, Launch.classLoader); final Method initializeMethod = startupClass.getMethod("initializeIfPossible"); initializeMethod.invoke(null); } catch (Throwable e) { throw new InitializationError(e); } return clazz; } @Override protected TestClass createTestClass(Class<?> testClass) { try { ClassLoader classLoader = Launch.classLoader; Class<?> testClassFromMinecraftClassLoader = classLoader.loadClass(testClass.getName()); return super.createTestClass(testClassFromMinecraftClassLoader); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
39.037736
115
0.691155
fdb318ffcf61bdce17cb8831c4b40aade4eabdf7
3,948
package sibbo.bitmessage.network.protocol; import java.io.IOException; import java.math.BigInteger; import java.util.Objects; import org.bouncycastle.jce.interfaces.ECPublicKey; import sibbo.bitmessage.crypt.CryptManager; /** * Represents an encrypted message in the bitmessage encryption format. * * @author Sebastian Schmidt */ public class EncryptedMessage extends Message { /** The initialization vector for AES. */ private byte[] iv; /** The public key to generate the shared secret. */ private ECPublicKey publicKey; /** The encrypted data. */ private byte[] encrypted; /** The HmacSHA256 value. */ private byte[] mac; /** * Creates a new Encrypted Message with the given parameters. * * @param iv * The AES initialization vector. Must have a length of 16. * @param publicKey * The public key used to generate the shared secret. * @param encrypted * The encrypted message. Must have a length of n * 16. * @param mac * The message authentication code. Must have a length of 32. */ public EncryptedMessage(byte[] iv, ECPublicKey publicKey, byte[] encrypted, byte[] mac, MessageFactory factory) { super(factory); Objects.requireNonNull(iv, "'iv' must not be null."); Objects.requireNonNull(publicKey, "'publicKey' must not be null."); Objects.requireNonNull(encrypted, "'encrypted' must not be null."); Objects.requireNonNull(mac, "'mac' must not be null."); if (iv.length != 16) { throw new IllegalArgumentException("'iv' must have a length of 16."); } if (encrypted.length % 16 != 0) { throw new IllegalArgumentException("'encrypted' must have a length of n * 16."); } if (mac.length != 32) { throw new IllegalArgumentException("'mac' must have a length of 32."); } this.iv = iv; this.publicKey = publicKey; this.encrypted = encrypted; this.mac = mac; } /** * {@link Message#Message(InputBuffer, MessageFactory)} */ public EncryptedMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException { super(b, factory); } @Override public byte[] getBytes() { byte[] result = new byte[16 + 70 + encrypted.length + mac.length]; System.arraycopy(iv, 0, result, 0, 16); System.arraycopy(Util.getBytes((short) 714), 0, result, 16, 2); System.arraycopy(Util.getBytes((short) 32), 0, result, 18, 2); System.arraycopy(Util.getUnsignedBytes(publicKey.getQ().getX().toBigInteger(), 32), 0, result, 20, 32); System.arraycopy(Util.getBytes((short) 32), 0, result, 52, 2); System.arraycopy(Util.getUnsignedBytes(publicKey.getQ().getY().toBigInteger(), 32), 0, result, 54, 32); System.arraycopy(encrypted, 0, result, 86, encrypted.length); System.arraycopy(mac, 0, result, result.length - 32, 32); return result; } public byte[] getEncrypted() { return encrypted; } public byte[] getIV() { return iv; } public byte[] getMac() { return mac; } public ECPublicKey getPublicKey() { return publicKey; } @Override protected void read(InputBuffer b) throws IOException, ParsingException { iv = b.get(0, 16); int curve = Util.getShort(b.get(16, 2)); if (curve != 714) { throw new ParsingException("Unknown curve: " + 714); } int xLength = Util.getShort(b.get(18, 2)); if (xLength > 32 || xLength < 0) { throw new ParsingException("xLength must be between 0 and 32: " + xLength); } BigInteger x = Util.getUnsignedBigInteger(b.get(20, xLength), 0, xLength); b = b.getSubBuffer(xLength + 20); int yLength = Util.getShort(b.get(0, 2)); if (yLength > 32 || yLength < 0) { throw new ParsingException("yLength must be between 0 and 32: " + yLength); } BigInteger y = Util.getUnsignedBigInteger(b.get(2, yLength), 0, yLength); b = b.getSubBuffer(2 + yLength); publicKey = CryptManager.getInstance().createPublicEncryptionKey(x, y); encrypted = b.get(0, b.length() - 32); mac = b.get(b.length() - 32, 32); } }
28.402878
114
0.680598
6a8b1e59d5c1a860dc6e8485eaa2979bb3eb02d2
11,187
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2014 Visualink * * 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 org.visualink.displee.gui; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.visualink.displee.ResultEntry; import org.visualink.displee.R; import org.visualink.displee.Util; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class ResultActivity extends Activity { private LinearLayout mNoResultLayout; private LinearLayout mResultLayout; private ImageButton mRebegin; private ImageButton mBackButton; private ImageButton mNoGoodResultsButton; private TextView mErrorTextView; private ListView mResults; private ResultAdapter mResultAdapter; private String mReqId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_results); mNoResultLayout = (LinearLayout)findViewById(R.id.no_result_layout); mResultLayout = (LinearLayout)findViewById(R.id.result_layout); mRebegin = (ImageButton)findViewById(R.id.rebegin); mBackButton = (ImageButton)findViewById(R.id.back); mNoGoodResultsButton = (ImageButton)findViewById(R.id.no_good_results); mErrorTextView = (TextView)findViewById(R.id.error); mResults = (ListView)findViewById(R.id.result); mResultAdapter = new ResultAdapter(this); mResults.setAdapter(mResultAdapter); mResults.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ResultEntry r = (ResultEntry)mResultAdapter.getItem(position); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(r.urlPage)); startActivity(i); } }); mRebegin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mBackButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ResultActivity.this.finish(); } }); mNoGoodResultsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Util.informNoGoodResults(mReqId); ResultActivity.this.finish(); } }); mHandler.sendEmptyMessage(SHOW_WAITING_DIALOG); mSendingThread = new SendingThread(); mSendingThread.start(); } private SendingThread mSendingThread; private ProgressDialog mProgressDialog; private class SendingThread extends Thread { public void run() { byte[] imageBytes = CaptureActivity.imageBytes; Bitmap img = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); int newWidth; int newHeight; if (img.getHeight() > img.getWidth()) { newWidth = 500; newHeight = (int)((float)newWidth / CaptureActivity.mImageRatio); } else { newHeight = 500; newWidth = (int)((float)newHeight * CaptureActivity.mImageRatio); } Bitmap scaledImg = Bitmap.createScaledBitmap(img, newWidth, newHeight, false); ByteArrayOutputStream imgByteStream = new ByteArrayOutputStream(); scaledImg.compress(Bitmap.CompressFormat.JPEG, 75, imgByteStream); Log.d("Pastec", "Image file size: " + imgByteStream.size()); /* Create the JSON. */ JSONObject json = new JSONObject(); try { json.put("api_version", Util.API_VERSION); } catch (JSONException e) { e.printStackTrace(); } /* Prepare the request to the server. */ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Util.SERVER + "results"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ByteArrayBody file = new ByteArrayBody(imgByteStream.toByteArray(), "userfile.jpg"); builder.addPart("userfile", file); builder.addTextBody("json", json.toString()); httppost.setEntity(builder.build()); try { HttpResponse response = httpclient.execute(httppost); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder strBuilder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { strBuilder.append(line); } JSONTokener tokener = new JSONTokener(strBuilder.toString()); try { JSONObject res = new JSONObject(tokener); boolean success = res.getBoolean("success"); mReqId = res.getString("req_id"); if (success == true) { JSONArray results = res.getJSONArray("results"); for (int i = 0; i < results.length(); ++i) { JSONObject result = results.getJSONObject(i); ResultEntry r = new ResultEntry(); r.id = result.getInt("id"); r.name = result.getString("name"); r.urlImage = result.getString("url_image"); r.urlPage = result.getString("url_page"); r.description = result.getString("description"); mResultAdapter.addItem(r); } } if (mResultAdapter.getCount() > 0) mHandler.sendEmptyMessage(RESULT_RECEIVED); else mHandler.sendEmptyMessage(NO_RESULT); } catch (JSONException e) { mHandler.sendEmptyMessage(SERVICE_DOWN); e.printStackTrace(); } } catch (ClientProtocolException e) { mHandler.sendEmptyMessage(SERVICE_DOWN); e.printStackTrace(); } catch (IOException e) { mHandler.sendEmptyMessage(SERVICE_DOWN); e.printStackTrace(); } mHandler.sendEmptyMessage(HIDE_WAITING_DIALOG); } } public byte[] requestResponse; private static final int RESULT_RECEIVED = 1; private static final int NO_RESULT = 11; private static final int SERVICE_DOWN = 12; private static final int SHOW_WAITING_DIALOG = 2; private static final int HIDE_WAITING_DIALOG = 3; private final Handler mHandler = new MyHandler(); private class MyHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESULT_RECEIVED: mResultAdapter.getImages(); mResultAdapter.notifyDataSetChanged(); mNoResultLayout.setVisibility(View.GONE); mResultLayout.setVisibility(View.VISIBLE); break; case NO_RESULT: mNoResultLayout.setVisibility(View.VISIBLE); mResultLayout.setVisibility(View.GONE); mErrorTextView.setText(ResultActivity.this.getText(R.string.no_result)); break; case SERVICE_DOWN: mNoResultLayout.setVisibility(View.VISIBLE); mResultLayout.setVisibility(View.GONE); mErrorTextView.setText(ResultActivity.this.getText(R.string.service_down)); break; case SHOW_WAITING_DIALOG: mProgressDialog = new ProgressDialog(ResultActivity.this, R.style.ProgressDialog); mProgressDialog.setMessage(ResultActivity.this.getText(R.string.retrieving)); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new MyCancelListener()); mProgressDialog.show(); break; case HIDE_WAITING_DIALOG: mProgressDialog.setOnCancelListener(null); mProgressDialog.cancel(); break; } } }; private class MyCancelListener implements ProgressDialog.OnCancelListener { @Override public void onCancel(DialogInterface dialog) { mSendingThread.interrupt(); finish(); } }; }
40.241007
117
0.621436
a7c1f9f0ef814d429d9bef7ae9f9d0d4c38cc64f
1,393
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * 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 net.java.sip.communicator.service.protocol.event; import java.util.*; /** * The <tt>ChatRoomMemberPropertyChangeListener</tt> receives events notifying interested parties * that a property of the corresponding chat room member (e.g. such as its nickname) has been * modified. * * @author Emil Ivov * @author Yana Stamcheva */ public interface ChatRoomMemberPropertyChangeListener extends EventListener { /** * Called to indicate that a chat room member property has been modified. * * @param event * the <tt>ChatRoomMemberPropertyChangeEvent</tt> containing the name of the property * that has just changed, as well as its old and new values. */ public void chatRoomPropertyChanged(ChatRoomMemberPropertyChangeEvent event); }
37.648649
100
0.753051
59ad27e2638b3b693c392284f6a943e4cad89172
762
package jp.ne.naokiur.design.pattern.command; public class Writing extends Command { private Canvas canvas; private int thickness; private String color; private int length; public Writing(int thickness, String color, int length) { this.thickness = thickness; this.color = color; this.length = length; } @Override public void execute(Canvas canvas) { canvas.addArt(thickness + " " + color + " " + length); this.canvas = canvas; } @Override public void undo() { String current = canvas.getField(); canvas.setField(current.replace(thickness + " " + color + " " + length, "")); } @Override public void redo() { execute(this.canvas); } }
23.8125
85
0.603675
525f0406b995adab4889e5e18068c871849c98c2
8,560
/* * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2020 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, * Jean-Yves Tinevez and Michael Zinsmaier. * %% * 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. * * 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 HOLDERS 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. * #L% */ package net.imglib2.type.numeric.integer; import java.math.BigInteger; import net.imglib2.img.NativeImg; import net.imglib2.img.basictypeaccess.LongAccess; import net.imglib2.img.basictypeaccess.array.LongArray; import net.imglib2.type.NativeTypeFactory; import net.imglib2.util.Util; /** * TODO * * @author Stephan Preibisch * @author Stephan Saalfeld * @author Albert Cardona * @author Mark Hiner */ public class UnsignedLongType extends GenericLongType< UnsignedLongType > { private static final double MAX_VALUE_PLUS_ONE = Math.pow( 2, 64 ); // not precise, because double is not sufficient private static final double MAX_LONG_PLUS_ONE = Math.pow( 2, 63 ); // not precise, because double is not sufficient // this is the constructor if you want it to read from an array public UnsignedLongType( final NativeImg< ?, ? extends LongAccess > img ) { super( img ); } // this is the constructor if you want it to be a variable public UnsignedLongType( final long value ) { super( value ); } // this is the constructor if you want it to be a variable public UnsignedLongType( final BigInteger value ) { super( ( NativeImg< ?, ? extends LongAccess > ) null ); dataAccess = new LongArray( 1 ); set( value.longValue() ); } // this is the constructor if you want to specify the dataAccess public UnsignedLongType( final LongAccess access ) { super( access ); } // this is the constructor if you want it to be a variable public UnsignedLongType() { this( 0 ); } @Override public UnsignedLongType duplicateTypeOnSameNativeImg() { return new UnsignedLongType( img ); } private static final NativeTypeFactory< UnsignedLongType, LongAccess > typeFactory = NativeTypeFactory.LONG( UnsignedLongType::new ); @Override public NativeTypeFactory< UnsignedLongType, LongAccess > getNativeTypeFactory() { return typeFactory; } @Override public void mul( final float c ) { set( Util.round( ( double ) ( get() * c ) ) ); } @Override public void mul( final double c ) { set( Util.round( ( get() * c ) ) ); } @Override public void add( final UnsignedLongType c ) { set( get() + c.get() ); } /** * @see #divide(long, long) */ @Override public void div( final UnsignedLongType c ) { set( divide( get(), c.get() ) ); } /** * Unsigned division of {@code d1} by {@code d2}. * * See "Division by Invariant Integers using Multiplication", by Torbjorn * Granlund and Peter L. Montgomery, 1994. <a href= * "http://gmplib.org/~tege/divcnst-pldi94.pdf">http://gmplib.org/~tege/divcnst-pldi94.pdf</a> * * @throws ArithmeticException * when c equals zero. */ static public final long divide( final long d1, final long d2 ) { if ( d2 < 0 ) { // d2 is larger than the maximum signed long value if ( Long.compareUnsigned( d1, d2 ) < 0 ) { // d1 is smaller than d2 return 0; } else { // d1 is larger or equal than d2 return 1; } } if ( d1 < 0 ) { // Approximate division: exact or one less than the actual value final long quotient = ( ( d1 >>> 1 ) / d2 ) << 1; final long reminder = d1 - quotient * d2; return quotient + ( Long.compareUnsigned( d2, reminder ) < 0 ? 0 : 1 ); } // Exact division, given that both d1 and d2 are smaller than // or equal to the maximum signed long value return d1 / d2; } @Override public void mul( final UnsignedLongType c ) { set( get() * c.get() ); } @Override public void sub( final UnsignedLongType c ) { set( get() - c.get() ); } @Override public void setOne() { set( 1 ); } @Override public void setZero() { set( 0 ); } @Override public void inc() { set( get() + 1 ); } @Override public void dec() { set( get() - 1 ); } @Override public String toString() { return getBigInteger().toString(); } /** * This method returns the value of the UnsignedLongType as a signed long. * To get the unsigned value, use {@link #getBigInteger()}. */ public long get() { return dataAccess.getValue( i ); } /** * This method returns the unsigned representation of this UnsignedLongType * as a {@code BigInteger}. */ @Override public BigInteger getBigInteger() { final BigInteger mask = new BigInteger( "FFFFFFFFFFFFFFFF", 16 ); return BigInteger.valueOf( get() ).and( mask ); } public void set( final long value ) { dataAccess.setValue( i, value ); } @Override public int getInteger() { return ( int ) get(); } @Override public long getIntegerLong() { return get(); } @Override public void setInteger( final int f ) { set( f ); } @Override public void setInteger( final long f ) { set( f ); } @Override public void setBigInteger( final BigInteger b ) { set( b.longValue() ); } @Override public void setReal( double real ) { set( doubleToUnsignedLong( real ) ); } static long doubleToUnsignedLong( double real ) { double value = real < MAX_LONG_PLUS_ONE ? Math.max(0, real) : Math.min(-1, real - MAX_VALUE_PLUS_ONE); return Util.round( value ); } @Override public void setReal( float real ) { setReal( (double) real ); } public void set( final BigInteger bi ) { set( bi.longValue() ); } /** * The maximum value that can be stored is {@code Math.pow( 2, 64 ) - 1}, * which can't be represented with exact precision using a double */ @Override public double getMaxValue() { return MAX_VALUE_PLUS_ONE - 1; } // imprecise /** * Returns the true maximum value as a BigInteger, since it cannot be * precisely represented as a {@code double}. */ public BigInteger getMaxBigIntegerValue() { return new BigInteger( "+FFFFFFFFFFFFFFFF", 16 ); } @Override public double getMinValue() { return 0; } /** * @deprecated Use {@link Long#compareUnsigned(long, long)} instead. */ @Deprecated static public final int compare( final long a, final long b ) { if ( a == b ) return 0; else { boolean test = ( a < b ); if ( ( a < 0 ) != ( b < 0 ) ) { test = !test; } return test ? -1 : 1; } } @Override public UnsignedLongType createVariable() { return new UnsignedLongType( 0 ); } @Override public UnsignedLongType copy() { return new UnsignedLongType( get() ); } @Override public float getRealFloat() { long l = get(); return l >= 0 ? l : ((float) MAX_VALUE_PLUS_ONE + l); } @Override public double getRealDouble() { return unsignedLongToDouble( get() ); } static double unsignedLongToDouble( long l ) { return l >= 0 ? l : (MAX_VALUE_PLUS_ONE + l); } @Override public int compareTo( final UnsignedLongType other ) { return Long.compareUnsigned( get(), other.get() ); } }
22.765957
134
0.679673
31c04bf2638f0a09bbfb0eba65bb3e4adbc0aa4b
150
package net.minecraft.client.gui.recipebook; public interface IRecipeShownListener { void recipesUpdated(); RecipeBookGui getRecipeGui(); }
16.666667
44
0.773333
2e7bdc8cc5b9b9ca618830710ca4c655156d55b4
1,333
import java.util.ArrayList; public class Producer implements Runnable{ ArrayList <Integer> buffer; //variable for shared resource private int objectNo; //keep track of order of added objects final int max = 5; //max size of buffer /*Constructor*/ public Producer(ArrayList<Integer> buffer){ this.buffer = buffer; objectNo = 1; } /*Method that adds an object to the shared resource*/ public void addObject(int i) throws InterruptedException{ //synchronize access to shared object synchronized(buffer){ while(buffer.size() >= max){ System.out.println("\nObject #" + i +" cannot be added. Buffer is full."); buffer.wait(); // sleep while waiting for buffer size to be less than 5 //and release control over shared resource } buffer.add(i); System.out.println("\nObject #" + i + " was added to Buffer.\nBuffer currently contains "+ buffer.size() +" objects."); Thread.sleep(200); //delayed shorter than in the consumer class to make it easier to get //cases where buffer is full buffer.notify(); //wake up next sleeping thread and release control over shared resource } } //Override run method @Override public void run(){ while(true){ try{ addObject(objectNo++); } catch(InterruptedException ie){} } } }
31
123
0.671418
203711a99b17db79b6c527f019703657e22ce599
1,065
package com.hblog.mapper; import com.hblog.bean.Message; import com.hblog.bean.MessageExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface MessageMapper { long countByExample(MessageExample example); int deleteByExample(MessageExample example); int deleteByPrimaryKey(Integer messageId); int insert(Message record); int insertSelective(Message record); List<Message> selectByExample(MessageExample example); Message selectByPrimaryKey(Integer messageId); int updateByExampleSelective(@Param("record") Message record, @Param("example") MessageExample example); int updateByExample(@Param("record") Message record, @Param("example") MessageExample example); int updateByPrimaryKeySelective(Message record); int updateByPrimaryKey(Message record); List<Message> querycontactlist(@Param("userid") int userid); Message selectnewchat(@Param("userid") int userid); int countudrtchat(@Param("userid") int userid); }
29.583333
109
0.728638
c36917a9741dd6ddb40a6cadf18f2e31b0b7fcc1
2,688
package org.firstinspires.ftc.teamcode.hardware; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.Gamepad; import com.qualcomm.robotcore.hardware.HardwareMap; import org.checkerframework.checker.index.qual.LTEqLengthOf; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.teamcode.enums.TSEArmPos; import org.firstinspires.ftc.teamcode.teleop.TeamMarkerTracker; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; public class MOEBot { public Chassis chassis; public Slides slides; public Intake intake; public Dispenser dispenser; public Carousel carousel; public TSEArm tseArm; public IMU imu; WebcamName webcamName; OpenCvCamera camera; public TeamMarkerTracker TSETracker; //Teleop Constructor public MOEBot(HardwareMap hardwareMap, Gamepad gpad1, Gamepad gpad2){ chassis = new Chassis(hardwareMap, gpad1); slides = new Slides(hardwareMap, gpad2); dispenser = new Dispenser(hardwareMap, gpad2, this.slides); intake = new Intake(hardwareMap, gpad1, gpad2, this.slides, this.dispenser); carousel = new Carousel(hardwareMap, gpad1); tseArm = new TSEArm(hardwareMap, gpad1); imu = new IMU(hardwareMap); } //Autonomous Constructor public MOEBot(HardwareMap hardwareMap, Gamepad gpad1, Gamepad gpad2, LinearOpMode opMode, int headingOffset){ String status = "INITIALIZING..."; opMode.telemetry.addData("status", status); opMode.telemetry.update(); chassis = new Chassis(hardwareMap, gpad1, opMode, headingOffset); slides = new Slides(hardwareMap, gpad2, opMode); dispenser = new Dispenser(hardwareMap, gpad2, this.slides); intake = new Intake(hardwareMap, gpad1, gpad2, this.slides, this.dispenser); tseArm = new TSEArm(hardwareMap, gpad1); carousel = new Carousel(hardwareMap, gpad1); imu = new IMU(hardwareMap, opMode); TSETracker = new TeamMarkerTracker(); webcamName = hardwareMap.get(WebcamName.class, "TSECam"); camera = OpenCvCameraFactory.getInstance().createWebcam(webcamName); TSETracker = new TeamMarkerTracker(); camera.openCameraDevice(); camera.startStreaming(160, 90 , OpenCvCameraRotation.UPRIGHT); camera.setPipeline(TSETracker); status = "READY!"; opMode.telemetry.addData("status", status); opMode.telemetry.update(); } }
40.119403
113
0.718378
a488c5e24e8278b42da71ca62be8d23c294c4a11
506
package ru.ltst.saturday_data_binding.ui.events; import android.view.View; import android.widget.Button; import android.widget.Toast; public class EventsClicks { public void onFirstClick(View view) { showToast(view); } public void onSecondClick(View view) { showToast(view); } private void showToast(View view){ String buttonText = ((Button) view).getText().toString(); Toast.makeText(view.getContext(),buttonText,Toast.LENGTH_SHORT).show(); } }
23
79
0.689723
3d239dfe9f4894c39879dff202b92b507c4a1bd1
492
package com.surroundrervouscat.astar; import com.surroundrervouscat.PlayGameScene; public class MapInfo { public PlayGameScene.SATTUS[][] maps; // 二维数组的地图 public int width; // 地图的宽 public int hight; // 地图的高 public Node start; // 起始结点 public Node end; // 最终结点 public MapInfo(PlayGameScene.SATTUS[][] maps, int width, int hight, Node start, Node end) { this.maps = maps; this.width = width; this.hight = hight; this.start = start; this.end = end; } }
22.363636
93
0.672764
f9432a41742a133bf224d4fa207a904bf322678d
3,016
import java.util.List; import org.checkerframework.checker.guieffect.qual.*; class ThrowsTest { boolean flag = true; // Type var test <E extends @UI PolyUIException> void throwTypeVarUI1(E ex1, @UI E ex2) throws PolyUIException { if (flag) { //:: error: (throw.type.invalid) throw ex1; } //:: error: (throw.type.invalid) throw ex2; } <@UI E extends @UI PolyUIException> void throwTypeVarUI2(E ex1) throws PolyUIException { //:: error: (throw.type.invalid) throw ex1; } <E extends @AlwaysSafe PolyUIException> void throwTypeVarAlwaysSafe1(E ex1, @AlwaysSafe E ex2) throws PolyUIException { if (flag) { throw ex1; } throw ex2; } <@AlwaysSafe E extends PolyUIException> void throwTypeVarAlwaysSafe2(E ex1, @AlwaysSafe E ex2) throws PolyUIException { if (flag) { throw ex1; } throw ex2; } <@AlwaysSafe E extends @UI PolyUIException> void throwTypeVarMixed(E ex1, @AlwaysSafe E ex2) throws PolyUIException { if (flag) { //:: error: (throw.type.invalid) throw ex1; } throw ex2; } // Wildcards //:: error: (type.argument.type.incompatible) void throwWildcard(List<? extends @UI PolyUIException> ui, // Default type of List's type parameter is below @UI so this is type.argument.incompatible List<? extends @AlwaysSafe PolyUIException> alwaysSafe) throws PolyUIException { if (flag) { //:: error: (throw.type.invalid) throw ui.get(0); } throw alwaysSafe.get(0); } void throwNull() { throw null; } // Declared @UI PolyUIException ui = new PolyUIException(); @AlwaysSafe PolyUIException alwaysSafe = new PolyUIException(); void throwDeclared() { try { //:: error: (throw.type.invalid) throw ui; } catch (@UI PolyUIException UIParam) { } try { throw alwaysSafe; } catch (@AlwaysSafe PolyUIException alwaysSafeParam) { } } // Test Exception parameters void unionTypes() { // GuiEffectChecker throws an exception on this code. When issue 384 is fixed, uncomment these lines. //https://github.com/typetools/checker-framework/issues/384 // try { // } catch (@AlwaysSafe NullPointerPolyUIException | @AlwaysSafe ArrayStorePolyUIException unionParam) { // // } // try { // } catch (@UI NullPointerPolyUIException | @UI ArrayStorePolyUIException unionParam) { // // } } void defaults() { try { throw new PolyUIException(); } catch (PolyUIException e) { } } @PolyUIType class PolyUIException extends Exception { } @PolyUIType class NullPointerPolyUIException extends NullPointerException { } @PolyUIType class ArrayStorePolyUIException extends ArrayStoreException { } }
28.186916
154
0.608422
19d5e63ed926bffef27171465914dd7edba5be33
876
package array; public class selectionsort { public static void main(String[] args) {//max=descending order //for ascending order change max to min and if(m[j]"<"m[min])..... int m[]={4,5,2,6,8,12,34,32,1,7}; int i,j,max,t; for(i=0;i<10;i++) { max=i; for(j=i+1;j<10;j++) { if(m[j]>m[max])//change sign for change in order max=j; } t=m[i]; m[i]=m[max]; m[max]=t; for(int k=0;k<10;k++) System.out.print(m[k]+"|"); System.out.println(); } for(i=0;i<10;i++) System.out.print(m[i]+"|"); /*String ch[]={"hell","To","Umar","hates","bakwas"}; int min; for(int i=0;i<5;i++) { min=i; for(int j=i+1;j<5;j++) { if(ch[j].compareTo(ch[min])>0) min=j; } String t=ch[i]; ch[i]=ch[min]; ch[min]=t; } for(int i=0;i<5;i++) System.out.print(ch[i]+",");//why error :(:(:( */ } }
17.877551
68
0.504566
1976be84fa78a701857028059080257f201557fd
826
package io.planckx.api.client; import org.apache.commons.lang3.builder.ToStringStyle; /** * Constants used throughout PlannckX's API. */ public class PlanckXConstant { /** * HTTP Header to be used for API authentication. */ public static final String API_KEY_HEADER = "access_key"; public static final String TIMESTAMP_HEADER = "timestamp"; public static final String NONCE_HEADER = "nonce"; public static final String TOKEN_HEADER = "sign"; public static final String HMAC_SHA1 = "HmacSHA1"; /** * Default ToStringStyle used by toString methods. * Override this to change the output format of the overridden toString methods. * - Example ToStringStyle.JSON_STYLE */ public static final ToStringStyle TO_STRING_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; }
28.482759
89
0.72276
6757f5accad7ce192db039735f4c19a23c8930dc
3,346
package integration.sockjs; import integration.VertxNubesTestBase; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.WebSocket; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; public abstract class EventBusBridgeTestBase extends VertxNubesTestBase { protected static void registerThroughBridge(WebSocket ws, String address, String msg) { sendTypeToBridge(ws, "register", address, msg); } protected static void publishThroughBridge(WebSocket ws, String address, String msg) { sendTypeToBridge(ws, "publish", address, msg); } protected static void sendThroughBridge(WebSocket ws, String address, String msg) { sendTypeToBridge(ws, "send", address, msg); } protected static void sendTypeToBridge(WebSocket ws, String type, String address, String msg) { JsonObject json = new JsonObject(); json.put("type", type); json.put("address", address); json.put("body", msg); ws.write(Buffer.buffer(json.toString())); } protected void testInboundPermitted(TestContext context, String wsAddress, String address) { Async async = context.async(); String msg = "It was a dark stormy night"; vertx.eventBus().consumer(address, buff -> { context.assertEquals(msg, buff.body()); async.complete(); }); client().websocket(wsAddress, socket -> { publishThroughBridge(socket, address, msg); }); } protected void testOutboundPermitted(TestContext context, String wsAddress, String address) { Async async = context.async(); async.await(10000); String msg = "It was a dark stormy night"; client().websocket(wsAddress, socket -> { socket.handler(buffer -> { System.out.println("message received through socket"); JsonObject json = new JsonObject(buffer.toString("UTF-8")); context.assertEquals(msg, json.getString("body")); async.complete(); }); registerThroughBridge(socket, address, msg); try { Thread.sleep(1000); } catch (Exception e) { } vertx.eventBus().publish(address, msg); }); } protected void testInboundRefused(TestContext context, String wsAddress, String address) { Async async = context.async(); String msg = "It was a dark stormy night"; vertx.eventBus().consumer(address, buff -> { context.fail("The message should not be forwarded to the event bus"); }); client().websocket(wsAddress, socket -> { socket.handler(buffer -> { assertAccessRefused(context, buffer); async.complete(); }); publishThroughBridge(socket, address, msg); }); } protected void testOutboundRefused(TestContext context, String wsAddress, String address) { Async async = context.async(); String msg = "It was a dark stormy night"; client().websocket(wsAddress, socket -> { socket.handler(buffer -> { assertAccessRefused(context, buffer); async.complete(); }); registerThroughBridge(socket, address, msg); }); } protected void assertAccessRefused(TestContext context, Buffer buffer) { JsonObject resp = new JsonObject(buffer.toString("UTF-8")); context.assertEquals("err", resp.getString("type")); context.assertEquals("access_denied", resp.getString("body")); } }
33.79798
97
0.682606
b792d8ee47c19ee9d46aa472f1c9834429353278
10,519
package io.l0neman.utils.stay.uiautomation; import android.os.SystemClock; import android.view.MotionEvent; import android.view.View; import android.widget.Checkable; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by l0neman on 2019/11/23. * <p> */ public class XUiObject implements XSearchable { private static final long WAIT_FOR_SELECTOR_TIMEOUT = 10 * 1000L; private static final long WAIT_FOR_SELECTOR_POLL = 1000L; private static final long WAIT_FOR_NEW_WINDOW_TIMEOUT = 10 * 1000L; private static final long WAIT_FOR_NEW_WINDOW_POLL = 1000L; private View mTarget; private XUiSelector mSelector; private XUiDevice mDevice; XUiObject(XUiDevice mDevice, XUiSelector mSelector) { this.mDevice = mDevice; this.mSelector = mSelector; } XUiObject(XUiDevice mDevice, View mTarget) { this.mDevice = mDevice; this.mTarget = mTarget; } public View getView() { checkView(); return mTarget; } private void checkView() { if (mTarget == null) { throw new XUiObjectNotFoundException(mSelector.toString()); } } public void click() { checkView(); ViewThread.runOnViewThread(new Runnable() { @Override public void run() { getView().performClick(); } }); } public void longClick() { checkView(); ViewThread.runOnViewThread(new Runnable() { @Override public void run() { getView().performLongClick(); } }); } private static void touchClickView(final View target) { final Random random = new Random(); target.post(new Runnable() { @Override public void run() { final int width = target.getWidth(); final int height = target.getHeight(); // 触点分布 x 10%~90% 之间。 final int x = width / 10 + random.nextInt(width / 5 * 4); // 触点分布 y 20%~80% 之间。 final int y = height / 8 + random.nextInt(height / 4 * 3); // 抬起时间 100ms + 0~300ms。 final long downTime = System.currentTimeMillis(); final long upTime = downTime + 100 + random.nextInt(300); final MotionEvent down = MotionEvent.obtain(downTime, downTime + random.nextInt(5), MotionEvent.ACTION_DOWN, x, y, MotionEvent.AXIS_PRESSURE); target.dispatchTouchEvent(down); final MotionEvent up = MotionEvent.obtain(upTime, upTime + random.nextInt(8), MotionEvent.ACTION_UP, x, y, MotionEvent.AXIS_PRESSURE); target.dispatchTouchEvent(up); down.recycle(); up.recycle(); } }); } public void touchClick() { checkView(); ViewThread.runOnViewThread(new Runnable() { @Override public void run() { touchClickView(getView()); } }); } public boolean setText(String text) { checkView(); if (getView() instanceof TextView) { ViewThread.runOnViewThread(new Runnable() { @Override public void run() { ((TextView) getView()).setText(text); } }); return true; } return false; } public XUiObject getParent() { try { return new XUiObject(mDevice, (View) getView().getParent()); } catch (ClassCastException e) { return null; } } public boolean waitForExists() { return waitForExists(WAIT_FOR_SELECTOR_TIMEOUT); } public boolean waitForExists(long timeout) { if (mTarget != null) { return true; } final long beginTime = SystemClock.uptimeMillis(); while (true) { final XUiObject uiObject = mDevice.findObject(mSelector); if (uiObject != null) { mTarget = uiObject.mTarget; return true; } if (SystemClock.uptimeMillis() - beginTime > timeout) { return false; } SystemClock.sleep(WAIT_FOR_SELECTOR_POLL); } } XUiDevice getDevice() { return mDevice; } public XUiObject makeObject(XUiSelector selector) { return new XUiObject(mDevice, selector); } @Override public boolean hasObject(XUiSelector selector) { return checkHashObject(selector); } private boolean checkHashObject(XUiSelector selector) { return ViewFinder.findWithView(XUiObject.this, null, selector); } @Override public XUiObject findObject(XUiSelector selector) { final List<XUiObject> objects = findObjects(selector); return objects.isEmpty() ? null : objects.get(0); } @Override public XUiObject findIndexObject(XUiSelector selector, int index) { final List<XUiObject> objects = findObjects(selector); return objects.size() <= index ? null : objects.get(index); } @Override public XUiObject findLastObject(XUiSelector selector) { final List<XUiObject> objects = findObjects(selector); return objects.isEmpty() ? null : objects.get(objects.size() - 1); } @Override public List<XUiObject> findObjects(XUiSelector selector) { checkView(); List<XUiObject> results = new ArrayList<>(); ViewFinder.findWithView(XUiObject.this, results, selector); return results; } public CharSequence getText() { checkView(); return getView() instanceof TextView ? ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<CharSequence>() { @Override public CharSequence getValue() { return ((TextView) getView()).getText(); } }) : ""; } public CharSequence getContentDesc() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<CharSequence>() { @Override public CharSequence getValue() { return getView().getContentDescription(); } }); } public CharSequence getHint() { checkView(); return getView() instanceof EditText ? ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<CharSequence>() { @Override public CharSequence getValue() { return ((EditText) getView()).getHint(); } }) : ""; } public boolean isCheckable() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView() instanceof Checkable; } }); } public boolean isChecked() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView() instanceof Checkable && ((Checkable) getView()).isChecked(); } }); } public boolean isClickable() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView().isClickable(); } }); } public boolean isEnabled() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView().isEnabled(); } }); } public boolean isFocusable() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView().isFocusable(); } }); } public boolean isFocused() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView().isFocused(); } }); } public boolean isLongClickable() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView().isLongClickable(); } }); } public boolean isSelected() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<Boolean>() { @Override public Boolean getValue() { return getView().isSelected(); } }); } public Class<?> getType() { checkView(); return getView().getClass(); } public String getResourceId() { checkView(); return ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<String>() { @Override public String getValue() { return ViewFinder.getId(getView()); } }); } public <R> R wait(final XSearchCondition<R> searchCondition, long timeout) { final long beginTime = SystemClock.uptimeMillis(); R ret; while (true) { ret = ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<R>() { @Override public R getValue() { return searchCondition.apply(XUiObject.this); } }); if (!(ret == null || ret.equals(false))) { break; } if (SystemClock.uptimeMillis() - beginTime > timeout) { break; } } return ret; } public <R> R wait(final XUiObjectCondition<R> uiObjectCondition, long timeout) { final long beginTime = SystemClock.uptimeMillis(); R ret; while (true) { ret = ViewThread.getValueOnViewThread(new ViewThread.ValueGetter<R>() { @Override public R getValue() { return uiObjectCondition.apply(XUiObject.this); } }); if (!(ret == null || ret.equals(false))) { break; } if (SystemClock.uptimeMillis() - beginTime > timeout) { break; } } return ret; } public boolean clickAndWaitForNewWindow() { checkView(); return clickAndWaitForNewWindow(WAIT_FOR_NEW_WINDOW_TIMEOUT); } public boolean clickAndWaitForNewWindow(long timeout) { final XUiAutomation vUiAutomation = mDevice.getVUiAutomation(); vUiAutomation.resetNewActivityFlag(); click(); final long beginTime = SystemClock.uptimeMillis(); while (!vUiAutomation.isOpenNewActivity()) { SystemClock.sleep(WAIT_FOR_NEW_WINDOW_POLL); if (SystemClock.uptimeMillis() - beginTime > timeout) { return false; } } return true; } public void recycle() { mSelector = null; mTarget = null; } // future support: // from androidx UiObject. // dragTo(...); // exists(); // getBounds(); // getChild(UiSelector selector); // getChildCount(); // isScrollable(); // performMultiPointerGesture(...); // pinchIn(int percent, int steps); // pinchOut(int percent, int steps); // swipe[down, up, left, down] // future support: // from androidx UiObject2; // clickAndWait(Condition); // drag(); // fling(); // scroll(); // getApplicationPackage(); // getChildren(); // wait(Condition); }
26.23192
91
0.648256
ad1020a02c4ddd88f1babe54eac9eb4963e224dc
1,518
package com.booking.app.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Transient; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.annotation.JsonInclude; @Entity public class Image implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JsonInclude() @Transient private MultipartFile images; @Column(nullable = true) @Lob private byte[] imagesDB; @ManyToOne(optional = false) private Facility facility; public Image() { } public Image(MultipartFile images, byte[] imagesDB, Facility facility) { super(); this.images = images; this.imagesDB = imagesDB; this.facility = facility; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public MultipartFile getImages() { return images; } public void setImages(MultipartFile images) { this.images = images; } public byte[] getImagesDB() { return imagesDB; } public void setImagesDB(byte[] imagesDB) { this.imagesDB = imagesDB; } public Facility getFacility() { return facility; } public void setFacility(Facility facility) { this.facility = facility; } }
17.448276
73
0.735837
12d337e0d83d35fa4e355469e617081ee051237a
1,602
// package interface08y09; /** * Clase Triangulo que implementa Figuras Geometricas * @author EDg2 */ public class Triangulo implements FigGeometrica{ // Atributos private double lado1, lado2, lado3; // Lados del triangulo // Constructor public Triangulo(double lado1, double lado2, double lado3) { this.lado1 = lado1; this.lado2 = lado2; this.lado3 = lado3; } // Metodos implementados // Perimetro de un Triangulo public double calculaPerim() { double perim = lado1 + lado2 + lado3; return perim; } // Area de un Triangulo Escaleno public double calculaArea() { double sePe, area; // Semiperimentro y Area sePe = calculaPerim()/2; area = Math.sqrt(sePe*(sePe-lado1)*(sePe-lado2)*(sePe-lado3) ); return area; } // Overriding @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Triangulo other = (Triangulo) obj; if (this.lado1 != other.lado1) { return false; } if (this.lado2 != other.lado2) { return false; } if (this.lado3 != other.lado3) { return false; } return true; } @Override public String toString() { return "Triangulo{" + "lado1=" + lado1 + ", lado2=" + lado2 + ", lado3=" + lado3 + '}'; } }
24.646154
95
0.533708
1fd62ba1a06291f3e3afe65bed7cd3760994513f
352
package tran.nam.flatform.database; import android.arch.persistence.room.Database; import android.arch.persistence.room.RoomDatabase; import tran.nam.flatform.model.AlarmData; @Database(entities = {AlarmData.class}, version = 1 ,exportSchema = false) public abstract class DBProvider extends RoomDatabase{ public abstract AlarmDao alarmDao(); }
29.333333
74
0.801136
e54012b63bd1ebd050555174c99be95d73530b03
5,240
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */ package io.annot8.components.translation.processors; import io.annot8.api.capabilities.Capabilities; import io.annot8.api.components.annotations.ComponentDescription; import io.annot8.api.components.annotations.ComponentName; import io.annot8.api.components.annotations.ComponentTags; import io.annot8.api.components.annotations.SettingsClass; import io.annot8.api.context.Context; import io.annot8.api.data.Content; import io.annot8.api.exceptions.BadConfigurationException; import io.annot8.api.exceptions.ProcessingException; import io.annot8.common.components.AbstractProcessorDescriptor; import io.annot8.common.components.capabilities.SimpleCapabilities; import io.annot8.common.data.content.Text; import io.annot8.components.base.text.processors.AbstractTextProcessor; import io.annot8.conventions.PropertyKeys; import java.util.Collection; import uk.gov.dstl.machinetranslation.connector.api.LanguagePair; import uk.gov.dstl.machinetranslation.connector.api.MTConnectorApi; import uk.gov.dstl.machinetranslation.connector.api.Translation; import uk.gov.dstl.machinetranslation.connector.api.exceptions.ConfigurationException; import uk.gov.dstl.machinetranslation.connector.api.exceptions.ConnectorException; import uk.gov.dstl.machinetranslation.connector.api.utils.ConnectorUtils; /** * Uses the MT API (see https://github.com/dstl/machinetranslation) to perform translation of Text * content objects. The relevant connector must be on the class path */ @ComponentName("Machine Translation") @ComponentDescription("Uses the Machine Translation API to translate text between languages") @SettingsClass(MachineTranslationSettings.class) @ComponentTags({"translation", "text"}) public class MachineTranslation extends AbstractProcessorDescriptor<MachineTranslation.Processor, MachineTranslationSettings> { @Override protected Processor createComponent(Context context, MachineTranslationSettings settings) { return new Processor(settings); } @Override public Capabilities capabilities() { return new SimpleCapabilities.Builder() .withProcessesContent(Text.class) .withCreatesContent(Text.class) .build(); } public static class Processor extends AbstractTextProcessor { private final MTConnectorApi connector; private final String sourceLanguage; private final String targetLanguage; private final boolean copyProperties; protected Processor( String sourceLanguage, String targetLanguage, boolean copyProperties, MTConnectorApi connector) { this.sourceLanguage = sourceLanguage; this.targetLanguage = targetLanguage; this.copyProperties = copyProperties; this.connector = connector; } public Processor(MachineTranslationSettings settings) { this.sourceLanguage = settings.getSourceLanguage(); this.targetLanguage = settings.getTargetLanguage(); this.copyProperties = settings.isCopyProperties(); try { connector = settings.getTranslatorClass().getConstructor().newInstance(); } catch (Exception e) { throw new BadConfigurationException("Could not instantiate MT Connector", e); } try { connector.configure(settings.getTranslatorConfiguration()); } catch (ConfigurationException e) { throw new BadConfigurationException("Could not configure MT Connector", e); } if (!ConnectorUtils.LANGUAGE_AUTO.equals(sourceLanguage) && connector.queryEngine().isSupportedLanguagesSupported()) { try { Collection<LanguagePair> supportedLanguages = connector.supportedLanguages(); if (!supportedLanguages.contains(new LanguagePair(sourceLanguage, targetLanguage))) { throw new BadConfigurationException( "Unsupported language pair (" + sourceLanguage + " -> " + targetLanguage + ")"); } } catch (ConnectorException e) { log().error("Unable to retrieve supported languages", e); } } } @Override protected void process(Text content) { Translation translatedText; try { log() .debug("Translating {} from {} to {}", content.getId(), sourceLanguage, targetLanguage); translatedText = connector.translate(sourceLanguage, targetLanguage, content.getData()); } catch (ConnectorException e) { throw new ProcessingException("Unable to translate text", e); } Content.Builder<Text, String> builder = content .getItem() .createContent(Text.class) .withDescription( "Translated " + content.getId() + " from " + translatedText.getSourceLanguage() + " to " + targetLanguage + " by " + connector.queryEngine().getName()) .withData(translatedText.getContent()); if (copyProperties) builder = builder.withProperties(content.getProperties()); builder.withProperty(PropertyKeys.PROPERTY_KEY_LANGUAGE, targetLanguage).save(); } } }
39.69697
100
0.709542
ecbf8ebf46ff717b4d7a304b1c2acea4cde829ac
915
package com.aqstore.service.event.payload; import java.util.List; import com.aqstore.service.event.payload.component.CreateOrderSagaStep; import com.aqstore.service.event.payload.component.EventOrderItemDTO; import com.aqstore.service.event.payload.component.EventUserAddressDTO; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; @Data @AllArgsConstructor @NoArgsConstructor @SuperBuilder @EqualsAndHashCode(callSuper = true) public class OrderSagaEvent extends AbstractBaseEvent{ private Long orderId; private String errorMessages; private EventUserAddressDTO userAddress; private List<EventOrderItemDTO> orderItems; private Long eventStepId; private Long eventStepDate; private CreateOrderSagaStep stepInfo; @Override public String getPayloadId() { return orderId.toString(); } }
24.72973
71
0.83388
e88aec0831fadc8e98c81381e3aed2ca4701413d
671
package com.semihunaldi.backendbootstrap.entitymodel.exceptions.user; import com.semihunaldi.backendbootstrap.entitymodel.exceptions.BaseException; import lombok.NoArgsConstructor; /** * Created by semihunaldi on 28.11.2018 */ @NoArgsConstructor public class UserNotFoundException extends BaseException { public UserNotFoundException(String message, Throwable cause) { super(message, cause); } public UserNotFoundException(String message) { super(message); } public UserNotFoundException(Throwable cause) { super(cause); } @Override public int errorCode() { return 1; } @Override public String description() { return "User not found"; } }
19.171429
77
0.769001
2c297c82c68ad293d2da87bb7f065c2e1ad38d77
4,970
/* * Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-BASE 蓝鲸基础平台 is licensed under the MIT License. * * License for BK-BASE 蓝鲸基础平台: * -------------------------------------------------------------------- * 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 com.tencent.bk.base.dataflow.jobnavi.api; import com.tencent.bk.base.dataflow.jobnavi.ha.HAProxy; import com.tencent.bk.base.dataflow.jobnavi.util.http.JsonUtils; import java.util.HashMap; import java.util.Map; public class Savepoint { /** * save jobnavi savepoint * * @param scheduleId * @param value * @throws Exception */ public static void save(String scheduleId, Map<String, String> value) throws Exception { Map<String, Object> param = new HashMap<>(); param.put("operate", "save_schedule"); param.put("schedule_id", scheduleId); param.put("savepoint", value); String paramStr = JsonUtils.writeValueAsString(param); HAProxy.sendPostRequest("/sys/savepoint", paramStr, null); } /** * save jobnavi savepoint * * @param scheduleId * @param scheduleTime * @param value * @throws Exception */ public static void save(String scheduleId, Long scheduleTime, Map<String, String> value) throws Exception { Map<String, Object> param = new HashMap<>(); param.put("operate", "save"); param.put("schedule_id", scheduleId); param.put("schedule_time", scheduleTime); param.put("savepoint", value); String paramStr = JsonUtils.writeValueAsString(param); HAProxy.sendPostRequest("/sys/savepoint", paramStr, null); } /** * get jobnavi savepoint * * @param scheduleId * @return save point data * @throws Exception */ public static String get(String scheduleId) throws Exception { Map<String, Object> param = new HashMap<>(); param.put("operate", "get_schedule"); param.put("schedule_id", scheduleId); String paramStr = JsonUtils.writeValueAsString(param); return HAProxy.sendPostRequest("/sys/savepoint", paramStr, null); } /** * get jobnavi savepoint * * @param scheduleId * @param scheduleTime * @return save point data * @throws Exception */ public static String get(String scheduleId, Long scheduleTime) throws Exception { Map<String, Object> param = new HashMap<>(); param.put("operate", "get"); param.put("schedule_id", scheduleId); param.put("schedule_time", scheduleTime); String paramStr = JsonUtils.writeValueAsString(param); return HAProxy.sendPostRequest("/sys/savepoint", paramStr, null); } /** * delete jobnavi savepoint * * @param scheduleId * @param scheduleTime * @return response message * @throws Exception */ public static String delete(String scheduleId, Long scheduleTime) throws Exception { Map<String, Object> param = new HashMap<>(); param.put("operate", "delete"); param.put("schedule_id", scheduleId); param.put("schedule_time", scheduleTime); String paramStr = JsonUtils.writeValueAsString(param); return HAProxy.sendPostRequest("/sys/savepoint", paramStr, null); } /** * delete jobnavi savepoint * * @param scheduleId * @return response message * @throws Exception */ public static String delete(String scheduleId) throws Exception { Map<String, Object> param = new HashMap<>(); param.put("operate", "delete_schedule"); param.put("schedule_id", scheduleId); String paramStr = JsonUtils.writeValueAsString(param); return HAProxy.sendPostRequest("/sys/savepoint", paramStr, null); } }
37.368421
114
0.662978
6caf9086511ac5453320db287dcd8cc841c6ad58
1,221
package com.revolsys.record.query; import com.revolsys.record.Record; import com.revolsys.record.schema.RecordStore; public class ParenthesisCondition extends AbstractUnaryQueryValue implements Condition { public ParenthesisCondition(final Condition condition) { super(condition); } @Override public void appendDefaultSql(final Query query, final RecordStore recordStore, final StringBuilder buffer) { buffer.append("("); super.appendDefaultSql(query, recordStore, buffer); buffer.append(")"); } @Override public ParenthesisCondition clone() { final ParenthesisCondition clone = (ParenthesisCondition)super.clone(); return clone; } @Override public boolean equals(final Object obj) { if (obj instanceof ParenthesisCondition) { final ParenthesisCondition condition = (ParenthesisCondition)obj; return super.equals(condition); } return false; } public Condition getCondition() { return getValue(); } @Override public boolean test(final Record record) { final Condition condition = getCondition(); return condition.test(record); } @Override public String toString() { return "(" + super.toString() + ")"; } }
24.42
88
0.719083
016e2f956f2fe36afd78aabf112fc33da66bb44f
3,928
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage()); } } } private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern); private static String[] parseIP(String ip) { String hex = ""; String port = ""; // IPV4 Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; } // IPV6, double colon Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } } // IPV6 Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; } throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); } private static int numCount(String s) { return s.split(":").length; } private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); } private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); } private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; } }
35.387387
229
0.490326
1ce2779505ad4fe05977c52fd7d14519fb268d0d
167
package com.liteworm.spb.dao; /** * @ClassName TestDao * @Decription @TOTO * @AUthor LiteWorm * @Date 2020/4/17 0:35 * @Version 1.0 **/ public class TestDao { }
15.181818
29
0.652695
d9f6c26cdf80ac8ee00ebfe5292d9f828a49d560
1,190
package com.questionnaire.ssm.module.questionnaireManage.pojo; /** * Created by 郑晓辉 on 2017/6/29. * Description: */ public class PreOrNextQes { //已经超出边界的情况 public final static long OUT_OF_INDEX = 0L; //我的全部问卷id信息 private Long[] ids; //当前查看问卷id private Long curQesId; //上一份问卷ID private Long prevId; //下一份问卷ID private Long nextId; public PreOrNextQes(Long[] ids) { this.ids = ids; } public synchronized long getNextQesPaperId() throws Exception { return nextId; } public synchronized long getPreviousQesPaperId() throws Exception { return prevId; } //设置当前问卷id的同时,设置上、下一份的问卷ID,如果已经在边界,则为 OUT_OF_INDEX public void setCurrentQesPaperId(Long aPaperId) throws Exception { this.curQesId = aPaperId; int len = ids.length; for (int i = 0; i < len; i++) { if (aPaperId.equals(ids[i])) { prevId = i - 1 >= 0 ? ids[i - 1] : OUT_OF_INDEX; nextId = i + 1 < len ? ids[i + 1] : OUT_OF_INDEX; } } } public synchronized long getCurrentQesPaperId() throws Exception { return this.curQesId; } }
23.8
71
0.605882
61a998a6b8ddabe6af8f98b28e886948289cbc30
23,036
package star.lut.com.chatdemo.appModules.chatDetails.adapter; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v4.app.NotificationCompat; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.Target; import com.downloader.Error; import com.downloader.OnDownloadListener; import com.downloader.PRDownloader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; import star.lut.com.chatdemo.constants.ApiConstants; import star.lut.com.chatdemo.constants.ValueConstants; import star.lut.com.chatdemo.appModules.fullScreenPicture.PictureActivty; import star.lut.com.chatdemo.R; import star.lut.com.chatdemo.dataModels.MessageDetail; import star.lut.com.chatdemo.webService.FileDownloadService; import star.lut.com.chatdemo.webService.WebServiceFactory; import timber.log.Timber; /** * Created by kamrulhasan on 3/10/18. */ public class ChatDetailsRVAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private int VIEWTYPE_PICTURE = 11; private int VIEWTYPE_FILE = 12; private int VIEWTYPE_MESSAGE = 13; private Context context; private List<MessageDetail> chatDetailsModels; private NotificationCompat.Builder mBuilder; private NotificationManager notificationManager; private String ownPic; private String otherPic; public ChatDetailsRVAdapter(Context context, List<MessageDetail> chatDetailsModels, String ownPic, String otherPic) { this.context = context; this.chatDetailsModels = chatDetailsModels; this.ownPic = ownPic; this.otherPic = otherPic; } class ViewHolderMessage extends RecyclerView.ViewHolder { @BindView(R.id.tvMessage) public TextView tvMessage; @BindView(R.id.tvTime) public TextView tvTime; @BindView(R.id.ivAvatar) public ImageView ivAvatar; @BindView(R.id.clChatLayout) public ConstraintLayout clChatLayout; private ViewHolderMessage(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } class ViewHolderPicture extends RecyclerView.ViewHolder { @BindView(R.id.tvTime) public TextView tvTime; @BindView(R.id.ivAvatar) public ImageView ivAvatar; @BindView(R.id.ivPicture) public ImageView ivPicture; @BindView(R.id.btnDownload) public ImageButton btnDownload; @BindView(R.id.clChatLayout) public ConstraintLayout clChatLayout; private ViewHolderPicture(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } class ViewHolderFile extends RecyclerView.ViewHolder { @BindView(R.id.tvTime) public TextView tvTime; @BindView(R.id.ivAvatar) public ImageView ivAvatar; @BindView(R.id.tvFileTitle) public TextView tvFileTitle; @BindView(R.id.btnDownload) public ImageButton btnDownload; @BindView(R.id.clChatLayout) public ConstraintLayout clChatLayout; private ViewHolderFile(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { RecyclerView.ViewHolder viewHolder; if (viewType == VIEWTYPE_FILE){ View v = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.rv_chat_file, viewGroup, false ); viewHolder = new ViewHolderFile(v); }else if (viewType == VIEWTYPE_PICTURE){ View v = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.rv_chat_picture, viewGroup, false ); viewHolder = new ViewHolderPicture(v); }else { View view = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.rv_chat_message, viewGroup, false ); viewHolder = new ViewHolderMessage(view); } return viewHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { Timber.d(viewHolder.getClass().toString()); if (viewHolder instanceof ViewHolderMessage){ bindMessageViewHolder((ViewHolderMessage) viewHolder, position); }else if (viewHolder instanceof ViewHolderPicture){ bindPictureViewHolder((ViewHolderPicture) viewHolder, position); }else if (viewHolder instanceof ViewHolderFile){ bindFileViewHolder((ViewHolderFile) viewHolder, position); } } @Override public int getItemCount() { return chatDetailsModels.size(); } @Override public int getItemViewType(int position) { switch (chatDetailsModels.get(position).contentType) { case ValueConstants.CONTENT_TYPE_FILE: return VIEWTYPE_FILE; case ValueConstants.CONTENT_TYPE_PICTURE: return VIEWTYPE_PICTURE; default: return VIEWTYPE_MESSAGE; } } private void setAvatar(ImageView ivAvatar, String pic){ Glide.with(context) .load(ApiConstants.BASE_URL+pic) .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL)) .listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { assert e != null; e.printStackTrace(); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { ivAvatar.setVisibility(View.VISIBLE); return false; } }) .into(ivAvatar); } private void bindMessageViewHolder(final ViewHolderMessage viewHolderMessage, int position){ if (chatDetailsModels.get(position).own){ viewHolderMessage.clChatLayout.setBackgroundColor(context.getResources().getColor(android.R.color.holo_blue_light)); }else { viewHolderMessage.clChatLayout.setBackgroundColor(context.getResources().getColor(android.R.color.holo_blue_dark)); } TextAdapter textAdapter = new TextAdapter(chatDetailsModels.get(position).content); SpannableString spannableString = textAdapter.getModifiedText(); viewHolderMessage.tvMessage.setText(spannableString); viewHolderMessage.tvTime.setText(chatDetailsModels.get(position).time); if (chatDetailsModels.get(position).own){ setAvatar(viewHolderMessage.ivAvatar, ownPic); }else { setAvatar(viewHolderMessage.ivAvatar, otherPic); } } private void bindFileViewHolder(final ViewHolderFile viewHolderFile, final int position){ if (chatDetailsModels.get(position).own){ viewHolderFile.clChatLayout.setBackgroundColor(context.getResources().getColor(android.R.color.holo_blue_light)); }else { viewHolderFile.clChatLayout.setBackgroundColor(context.getResources().getColor(android.R.color.holo_blue_dark)); } viewHolderFile.tvFileTitle.setText(chatDetailsModels.get(position).title); viewHolderFile.tvTime.setText(chatDetailsModels.get(position).time); if (chatDetailsModels.get(position).own){ setAvatar(viewHolderFile.ivAvatar, ownPic); }else { setAvatar(viewHolderFile.ivAvatar, otherPic); } viewHolderFile.btnDownload.setOnClickListener(v -> downloadFile( ApiConstants.BASE_URL+chatDetailsModels.get(position).content, chatDetailsModels.get(position).title, position, viewHolderFile) ); } private void bindPictureViewHolder(final ViewHolderPicture viewHolderPicture, final int position){ if (chatDetailsModels.get(position).own){ viewHolderPicture.clChatLayout.setBackgroundColor(context.getResources().getColor(android.R.color.holo_blue_light)); }else { viewHolderPicture.clChatLayout.setBackgroundColor(context.getResources().getColor(android.R.color.holo_blue_dark)); } viewHolderPicture.tvTime.setText(chatDetailsModels.get(position).time); if (chatDetailsModels.get(position).own){ setAvatar(viewHolderPicture.ivAvatar, ownPic); }else { setAvatar(viewHolderPicture.ivAvatar, otherPic); } viewHolderPicture.btnDownload.setOnClickListener(v -> { Timber.d("download clicked"); downloadFile(ApiConstants.BASE_URL+chatDetailsModels.get(position).content, chatDetailsModels.get(position).title, position, viewHolderPicture); }); viewHolderPicture.ivPicture.setOnClickListener(v -> { Intent intent = new Intent(context, PictureActivty.class); intent.putExtra("path", chatDetailsModels.get(position).content); context.startActivity(intent); }); setAvatar(viewHolderPicture.ivPicture, chatDetailsModels.get(position).content); } private void downloadFile(String url, final String fileName, final int position, RecyclerView.ViewHolder viewHolder){ String dirPath = getDirPath(); PRDownloader.initialize(context.getApplicationContext()); setNotification(chatDetailsModels.get(position).id, fileName); PRDownloader.download(url, dirPath, fileName) .build() .setOnStartOrResumeListener(() -> setNotification(chatDetailsModels.get(position).id, fileName)) .setOnPauseListener(() -> { mBuilder.setSubText("Paused"); notificationManager.notify(chatDetailsModels.get(position).id, mBuilder.build()); }) .setOnCancelListener(() -> { }) .setOnProgressListener(progress -> { mBuilder.setProgress(100, (int) ((double) progress.currentBytes * 100 / progress.totalBytes), false); notificationManager.notify(chatDetailsModels.get(position).id, mBuilder.build()); }) .start(new OnDownloadListener() { @Override public void onDownloadComplete() { Timber.d("download complete"); mBuilder.setProgress(0,0,false); mBuilder.setSubText("Download completed"); mBuilder.setOngoing(false); notificationManager.notify(chatDetailsModels.get(position).id, mBuilder.build()); if (viewHolder instanceof ViewHolderPicture){ ((ViewHolderPicture)viewHolder).btnDownload.setImageResource(R.drawable.ic_open); ((ViewHolderPicture)viewHolder).btnDownload.setOnClickListener(view -> { File file = new File(dirPath+fileName); Uri path = Uri.fromFile(file); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setDataAndType(path, "application/*"); if(Build.VERSION.SDK_INT>=24){ try{ Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); }catch(Exception e){ e.printStackTrace(); } } try { context.startActivity(pdfOpenintent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } }); }else { ((ViewHolderFile)viewHolder).btnDownload.setImageResource(R.drawable.ic_open); ((ViewHolderFile)viewHolder).btnDownload.setOnClickListener(view -> { File file = new File(dirPath+fileName); Uri path = Uri.fromFile(file); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setDataAndType(path, "application/*"); if(Build.VERSION.SDK_INT>=24){ try{ Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); }catch(Exception e){ e.printStackTrace(); } } try { context.startActivity(pdfOpenintent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } }); } } @Override public void onError(Error error) { Timber.d(error.isConnectionError()+" "+error.isServerError()); mBuilder.setProgress(0,0,false); mBuilder.setSubText("Download canceled"); notificationManager.notify(chatDetailsModels.get(position).id, mBuilder.build()); } }); } private void setNotification(int notificationid, String fileName){ Intent intent = new Intent(); final PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, intent, 0); mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_apk_box) .setContentTitle(fileName); mBuilder.setContentIntent(pendingIntent); notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mBuilder.setProgress(100 , 0, false); mBuilder.setOngoing(true); notificationManager.notify(notificationid, mBuilder.build()); } private static String getDirPath() { Timber.d( "called here"); File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "chatDemoDownloads"); if (!file.exists()) { file.mkdirs(); Timber.d( file.getAbsolutePath()); } else { Timber.d( file.getAbsolutePath()); } return file.getAbsolutePath(); } private void downloadFile(MessageDetail messageDetail, ViewHolderFile file){ FileDownloadService downloadService = WebServiceFactory.createRetrofitService(FileDownloadService.class); downloadService.getFileFromServer(ApiConstants.BASE_URL+ messageDetail.content) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<ResponseBody>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(ResponseBody responseBody) { boolean writtenToDisk = writeResponseBodyToDisk(responseBody, messageDetail); if (writtenToDisk){ Toast.makeText(context, "Download complete", Toast.LENGTH_SHORT).show(); file.btnDownload.setImageResource(R.drawable.ic_open); file.btnDownload.setOnClickListener(view -> { File file = new File(getDirPath()+messageDetail.title); Uri path = Uri.fromFile(file); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setDataAndType(path, "application/*"); if(Build.VERSION.SDK_INT>=24){ try{ Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); }catch(Exception e){ e.printStackTrace(); } } try { context.startActivity(pdfOpenintent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } }); } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } private void downloadPicture(MessageDetail messageDetail, ViewHolderPicture file){ FileDownloadService downloadService = WebServiceFactory.createRetrofitService(FileDownloadService.class); downloadService.getFileFromServer(ApiConstants.BASE_URL+ messageDetail.content) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<ResponseBody>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(ResponseBody responseBody) { boolean writtenToDisk = writeResponseBodyToDisk(responseBody, messageDetail); if (writtenToDisk){ Toast.makeText(context, "Download complete", Toast.LENGTH_SHORT).show(); file.btnDownload.setImageResource(R.drawable.ic_open); file.btnDownload.setOnClickListener(view -> { File file = new File(getDirPath()+messageDetail.title); Uri path = Uri.fromFile(file); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setDataAndType(path, "application/*"); if(Build.VERSION.SDK_INT>=24){ try{ Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); }catch(Exception e){ e.printStackTrace(); } } try { context.startActivity(pdfOpenintent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } }); } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } private boolean writeResponseBodyToDisk(ResponseBody body, MessageDetail messageDetail) { try { File futureStudioIconFile = new File(getDirPath() + File.separator + messageDetail.title); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; long fileSize = body.contentLength(); long fileSizeDownloaded = 0; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; } outputStream.flush(); return true; } catch (IOException e) { return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return false; } } }
42.580407
158
0.571019
811da502ecbe1f43e63681a055865841896a1b1b
1,643
package lykrast.universalbestiary; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; import vazkii.patchouli.api.PatchouliAPI; import vazkii.patchouli.api.PatchouliAPI.IPatchouliAPI; @Mod(modid = UniversalBestiary.MODID, name = UniversalBestiary.NAME, version = UniversalBestiary.VERSION, dependencies = "required-after:patchouli", acceptedMinecraftVersions = "[1.12, 1.13)") public class UniversalBestiary { public static final String MODID = "universalbestiary"; public static final String NAME = "Universal Bestiary"; public static final String VERSION = "@VERSION@"; public static Logger logger = LogManager.getLogger(MODID); public static Item identifier; @EventHandler public void preInit(FMLPreInitializationEvent event) { CriteriaTriggers.register(BestiaryTrigger.INSTANCE); } @EventHandler public void init(FMLInitializationEvent event) { //Flags for checking which mobs exist IPatchouliAPI patchouli = PatchouliAPI.instance; for (ResourceLocation rl : ForgeRegistries.ENTITIES.getKeys()) { patchouli.setConfigFlag(MODID + ":entity:" + rl, true); logger.debug("Found entity " + rl); } } }
35.717391
69
0.777845
174f07ec995d0d7cb758104749c3523156038f3d
640
package gov.ca.emsa.pulse.broker.dao; import gov.ca.emsa.pulse.broker.dto.LocationDTO; import gov.ca.emsa.pulse.broker.entity.LocationEntity; import java.util.List; public interface LocationDAO { public LocationDTO create(LocationDTO location); public LocationDTO update(LocationDTO location); public List<LocationEntity> getAllEntities(); public List<LocationDTO> findAll(); public void delete(LocationDTO locationDto); public LocationDTO findById(Long id); public LocationDTO findByExternalId(String externalId); public List<LocationDTO> findByName(String name); public List<LocationDTO> findByEndpoint(Long endpointId) ; }
32
59
0.809375
b5bf3ddacdbe30566a0bfd04d063a326fb0db159
442
package cn.edu.gdupt.genericity; /** * 泛型特性练习 * * @author Liang Xiaobin<1490556728@qq.com> * @version 2019.09.07 * @since JDK1.8 */ public class Generic<T> { private T key; /** * 泛型构造方法形参key类型也为T,T的类型由外部指定 * * @param key */ public Generic(T key) { this.key = key; } /** * get方法返回值也为T,T的类型由外部指定 * * @return key */ public T getKey() { return key; } }
14.258065
43
0.524887
486074c906c52921d73b2e582204a1bbdf2e50a5
1,961
package com.primankaden.stay63.entities; import com.primankaden.stay63.XmlUtils; import org.w3c.dom.Element; public class Stop extends AbsPoint { @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAdjacentStreet() { return adjacentStreet; } public void setAdjacentStreet(String adjacentStreet) { this.adjacentStreet = adjacentStreet; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } public String getTitleEn() { return titleEn; } public void setTitleEn(String titleEn) { this.titleEn = titleEn; } public String getAdjacentStreetEn() { return adjacentStreetEn; } public void setAdjacentStreetEn(String adjacentStreetEn) { this.adjacentStreetEn = adjacentStreetEn; } public String getDirectionEn() { return directionEn; } public void setDirectionEn(String directionEn) { this.directionEn = directionEn; } private String id; private String title; private String adjacentStreet; private String direction; private String titleEn; private String adjacentStreetEn; private String directionEn; public void init(Element e) { setId(XmlUtils.getValue(e, "KS_ID")); setTitle(XmlUtils.getValue(e, "title")); setAdjacentStreet(XmlUtils.getValue(e, "adjacentStreet")); setDirection(XmlUtils.getValue(e, "direction")); setTitleEn(XmlUtils.getValue(e, "titleEn")); setAdjacentStreetEn(XmlUtils.getValue(e, "adjacentStreetEn")); setDirectionEn(XmlUtils.getValue(e, "directionEn")); } }
23.345238
70
0.651198
c39f5ae418552a396327f315af7e7695c929b84c
908
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> comb = new ArrayList<Integer>(); backtrack(res,comb,candidates,target,0); return res; } public void backtrack(List<List<Integer>> res, List<Integer> comb, int[] candidates,int target,int idx) { if(idx>=candidates.length) return; if(target==0) { res.add(new ArrayList<Integer>(comb)); return; } if(target-candidates[idx]>=0) { comb.add(candidates[idx]); backtrack(res,comb,candidates,target-candidates[idx],idx); comb.remove(comb.size()-1); } else return; backtrack(res,comb,candidates,target,idx+1); } }
31.310345
107
0.564978
28834954662b3246f0adbc68f604fbbd0a8c7bf0
4,061
/* * Exercise 6.33 * (Current date and time) Invoking System.currentTimeMillis() returns the * elapsed time in milliseconds since midnight of January 1, 1970. Write a program * that displays the date and time. * * Current date and time is May 16, 2012 10:34:23 */ package chapter06.exercise.exercise06_33; /** * Display current date and time * @author emaph */ public class DisplayCurrentDateAndTime { public static void main(String[] args) { // Ignore timezones System.out.println("Current date and time is " + getDate() + " " + getTime()); } public static String getTime() { // Obtain the total millisoconds since midnight, Jan 1 1960 long totalMilliseconds = System.currentTimeMillis(); // Objtain the total seconds since midnight Jan 1, 1970 long totalSeconds = totalMilliseconds / 1000; // Compute the current second in the minute in the hour long currentSecond = totalSeconds % 60; // Obtain the total minutes long totalMinutes = totalSeconds / 60; // Compute the current minute in the hour long currentMinute = totalMinutes % 60; // Obtain the total hours long totalHours = totalMinutes / 60; // Compute the current hour - Convert to EST long currentHour = (totalHours % 24) - 4; return String.format("%02d:%02d:%02d", currentHour, currentMinute, currentSecond); } public static String getDate() { long totalMilliseconds = System.currentTimeMillis(); long totalDays = totalMilliseconds / (1000 * 60 * 60 * 24); // start from January 1, 1970 when currentTimeMillis starts at 0. int year = 1970; int month = 1; int day = 1; int startDayNo = 4; // Thursday. int monthDays = getNumberOfDaysInMonth(year, month); // loop thru all of the days to find current day for (long i = 0; i < totalDays; i++) { // increment day startDayNo = (startDayNo + 1) % 7; day++; // increment month if (day > monthDays) { month++; day = 1; } // increment year if (month > 12) { year++; month = 1; } monthDays = getNumberOfDaysInMonth(year, month); } return getMonthName(month) + " " + day + ", " + year; } // // See Listing 6.12 for these functions // /** Get the number of days in a month */ public static int getNumberOfDaysInMonth(int year, int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) return 31; if (month == 4 || month == 6 || month == 9 || month == 11) return 30; if (month == 2) return isLeapYear(year)? 29: 28; return 0; // if month is incorrect } /** Return true if year is a leap year */ public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } /** * Convert from month number to month name * * from Listing 6.12 */ public static String getMonthName(int month) { String monthName; switch (month) { case 1: monthName = "January"; break; case 2: monthName = "February"; break; case 3: monthName = "March"; break; case 4: monthName = "April"; break; case 5: monthName = "May"; break; case 6: monthName = "June"; break; case 7: monthName = "July"; break; case 8: monthName = "August"; break; case 9: monthName = "September"; break; case 10: monthName = "October"; break; case 11: monthName = "November"; break; case 12: monthName = "December"; break; default: monthName = "unkown"; } return monthName; } }
30.081481
91
0.551096
75f1dbbb17eb732a2a1e3a1e7cfba2d029cc57a7
6,850
package org.infinispan.persistence.manager; import static org.infinispan.commons.test.Exceptions.expectCompletionException; import static org.infinispan.persistence.manager.PersistenceManager.AccessMode.BOTH; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.getFirstStore; import static org.infinispan.test.TestingUtil.getStore; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.support.DelayStore; import org.infinispan.persistence.support.FailStore; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestException; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.subscribers.TestSubscriber; /** * A {@link PersistenceManager} unit test. * * @author Pedro Ruivo * @since 9.3 */ @Test(groups = "unit", testName = "persistence.PersistenceManagerTest") @CleanupAfterMethod public class PersistenceManagerTest extends SingleCacheManagerTest { /** * Simulates cache receiving a topology update while stopping. */ public void testPublishAfterStop() { PersistenceManager persistenceManager = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); String key = "k"; insertEntry(persistenceManager, keyPartitioner, key, "v"); persistenceManager.stop(); // The stopped PersistenceManager should never pass the request to the store Flowable.fromPublisher(persistenceManager.publishEntries(true, true)) .blockingSubscribe(ignore -> fail("shouldn't run")); } /** * Simulates cache stopping while processing a state request. */ public void testStopDuringPublish() throws ExecutionException, InterruptedException, TimeoutException { PersistenceManager persistenceManager = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); insertEntry(persistenceManager, keyPartitioner, "k1", "v1"); insertEntry(persistenceManager, keyPartitioner, "k2", "v2"); insertEntry(persistenceManager, keyPartitioner, "k3", "v3"); DelayStore store = getFirstStore(cache); store.delayBeforeEmit(1); CountDownLatch before = new CountDownLatch(1); CountDownLatch after = new CountDownLatch(1); Future<Integer> publisherFuture = fork(() -> { TestSubscriber<Object> subscriber = TestSubscriber.create(0); Flowable.fromPublisher(persistenceManager.publishEntries(true, true)) .subscribe(subscriber); before.countDown(); assertTrue(after.await(10, TimeUnit.SECONDS)); // request all the elements after we have initiated stop subscriber.request(Long.MAX_VALUE); subscriber.await(10, TimeUnit.SECONDS); subscriber.assertNoErrors(); subscriber.assertComplete(); return subscriber.values().size(); }); assertTrue(before.await(30, TimeUnit.SECONDS)); Future<Void> stopFuture = fork(persistenceManager::stop); // Stop is unable to proceed while the publisher hasn't completed Thread.sleep(50); assertFalse(stopFuture.isDone()); assertFalse(publisherFuture.isDone()); after.countDown(); // Publisher can't continue because the store emit is delayed Thread.sleep(50); assertFalse(stopFuture.isDone()); assertFalse(publisherFuture.isDone()); // Emit the entries and allow PMI to stop store.endDelay(); Integer count = publisherFuture.get(30, TimeUnit.SECONDS); stopFuture.get(30, TimeUnit.SECONDS); assertEquals(3, count.intValue()); } public void testEarlyTerminatedPublish() { PersistenceManager persistenceManager = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); // This has to be > 128 - as the flowable pulls a chunk of that size for (int i = 0; i < 140; ++i) { String key = "k" + i; insertEntry(persistenceManager, keyPartitioner, key, "v"); } DelayStore store = getFirstStore(cache); store.delayBeforeEmit(1); PersistenceManagerImpl pmImpl = (PersistenceManagerImpl) persistenceManager; assertFalse(pmImpl.anyLocksHeld()); assertFalse(cache.isEmpty()); assertFalse(pmImpl.anyLocksHeld()); store.endDelay(); } public void testStoreExceptionInWrite() { PersistenceManager pm = extractComponent(cache, PersistenceManager.class); KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); DelayStore store1 = getStore(cache, 0, true); FailStore store2 = getStore(cache, 1, true); store2.failModification(2); String key = "k"; int segment = keyPartitioner.getSegment(key); expectCompletionException(TestException.class, pm.writeToAllNonTxStores(MarshalledEntryUtil.create(key, "v", cache), segment, BOTH)); assertTrue(store1.contains(key)); expectCompletionException(TestException.class, pm.deleteFromAllStores(key, segment, BOTH)); assertFalse(store1.contains(key)); } @Override protected EmbeddedCacheManager createCacheManager() { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.persistence().addStore(DelayStore.ConfigurationBuilder.class); cfg.persistence().addStore(FailStore.ConfigurationBuilder.class); cfg.persistence().addStore(FailStore.ConfigurationBuilder.class); return TestCacheManagerFactory.createCacheManager(cfg); } private void insertEntry(PersistenceManager persistenceManager, KeyPartitioner keyPartitioner, String k, String v) { join(persistenceManager.writeToAllNonTxStores(MarshalledEntryUtil.create(k, v, cache), keyPartitioner.getSegment(k), BOTH)); } }
42.283951
119
0.736788
209e62268b752473a256a2e747b04ed5edd93ac8
690
package com.tomersela.lightex.ast; import com.tomersela.lightex.parser.Token; public abstract class UnaryOp implements Operator { private final String symbol; private final Exp expression; private final Token token; public UnaryOp(String symbol, Exp expression, Token token) { this.symbol = symbol; this.expression = expression; this.token = token; } public Exp getExpression() { return expression; } @Override public Token getToken() { return token; } public String getSymbol() { return symbol; } @Override public String toString() { return symbol + expression; } }
20.294118
64
0.63913
d21e563ac646451d88c71fe62cc76c4b335f1303
967
/* * @lc app=leetcode id=158 lang=java * * [158] Read N Characters Given Read4 II - Call multiple times */ // @lc code=start /** * The read4 API is defined in the parent class Reader4. * int read4(char[] buf4); */ public class Solution extends Reader4 { private char[] buf4 = new char[4]; private int count = 0; private int buf4Idx = 0; /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ public int read(char[] buf, int n) { int wrote = 0; while (wrote < n) { if (buf4Idx == count) { count = read4(buf4); buf4Idx = 0; } if (count == 0) { break; } while (wrote < n && buf4Idx < count) { buf[wrote++] = buf4[buf4Idx++]; } } return wrote; } } // @lc code=end
21.488889
63
0.496381
e1747d68c55cd34f560047d6273d9c1b607bde2d
36,905
/** * personium.io * Copyright 2014 FUJITSU LIMITED * * 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 io.personium.test.jersey.box.odatacol; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.MediaType; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.json.simple.JSONObject; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; import io.personium.test.jersey.ODataCommon; import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.PersoniumResponse; import io.personium.test.setup.Setup; import io.personium.test.utils.EntityTypeUtils; import io.personium.test.utils.Http; import io.personium.test.utils.TResponse; import io.personium.test.utils.UserDataUtils; /** * UserData更新のテスト. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) public class UserDataMergeTest extends AbstractUserDataTest { /** * コンストラクタ. */ public UserDataMergeTest() { super(new PersoniumCoreApplication()); colName = "setodata"; } /** * UserDataのMERGEで存在するプロパティを指定してプロパティが更新されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGEで存在するプロパティを指定してプロパティが更新されること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty", "updateDynamicPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty", "updateDynamicPropertyValue"); expectedDynamicFields.put("secondDynamicProperty", "secondDynamicPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(userDataId); } } /** * UserDataのMERGEで存在しないプロパティを指定してプロパティが追加されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGEで存在しないプロパティを指定してプロパティが追加されること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("newProperty", "newPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty", "dynamicPropertyValue"); expectedDynamicFields.put("secondDynamicProperty", "secondDynamicPropertyValue"); expectedDynamicFields.put("newProperty", "newPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(userDataId); } } /** * UserDataのMERGEで存在しないkeyを指定し404が返却されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGEで存在しないkeyを指定し404が返却されること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("newProperty", "newPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // マージリクエスト実行 res = mergeRequest("dummyKey", updateReqBody); res.statusCode(HttpStatus.SC_NOT_FOUND); } finally { deleteUserData(userDataId); } } /** * UserDataのMERGEで__idを指定した場合__idが無視されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGEで__idを指定した場合__idが無視されること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("__id", "newuserdata001"); updateReqBody.put("dynamicProperty", "updateDynamicPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty", "updateDynamicPropertyValue"); expectedDynamicFields.put("secondDynamicProperty", "secondDynamicPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(userDataId); } } /** * UserDataのMERGEで存在しないプロパティを指定してプロパティが追加されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataをIfMatchヘッダの指定なしでMERGEして412エラーとなること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty", "updateDynamicPropertyValue"); try { createUserData(createReqBody, HttpStatus.SC_CREATED); Http.request("box/odatacol/merge.txt") .with("cell", cellName) .with("box", boxName) .with("collection", colName) .with("entityType", entityTypeName) .with("id", userDataId) .with("accept", MediaType.APPLICATION_JSON) .with("contentType", MediaType.APPLICATION_JSON) .with("token", PersoniumUnitConfig.getMasterToken()) .with("body", updateReqBody.toJSONString()) .returns() .statusCode(HttpStatus.SC_PRECONDITION_FAILED) .debug(); } finally { deleteUserData(userDataId); } } /** * UserDataのIfMatchヘッダにEtagのVersionに不正な値を指定して412エラーとなること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのIfMatchヘッダにEtagのVersionに不正な値を指定して412エラーとなること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty", "updateDynamicPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // Etag取得 String etag = res.getHeader(HttpHeaders.ETAG); long version = ODataCommon.getEtagVersion(etag); long updated = ODataCommon.getEtagUpdated(etag); // マージリクエスト実行 res = mergeRequest(userDataId, "W/\"" + String.valueOf(version + 1) + "-" + String.valueOf(updated) + "\"", updateReqBody); res.statusCode(HttpStatus.SC_PRECONDITION_FAILED); } finally { deleteUserData(userDataId); } } /** * UserDataのIfMatchヘッダにEtagのUpdatedに不正な値を指定して412エラーとなること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのIfMatchヘッダにEtagのUpdatedに不正な値を指定して412エラーとなること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty", "updateDynamicPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // Etag取得 String etag = res.getHeader(HttpHeaders.ETAG); long version = ODataCommon.getEtagVersion(etag); long updated = ODataCommon.getEtagUpdated(etag); // マージリクエスト実行 res = mergeRequest(userDataId, "W/\"" + String.valueOf(version) + "-" + String.valueOf(updated + 1) + "\"", updateReqBody); res.statusCode(HttpStatus.SC_PRECONDITION_FAILED); } finally { deleteUserData(userDataId); } } /** * UserDataのIfMatchヘッダに現在登録されているEtagの値を指定して正常にMERGEできること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのIfMatchヘッダに現在登録されているEtagの値を指定して正常にMERGEできること() { String userDataId = "userdata001"; // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("newProperty", "newPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty", "dynamicPropertyValue"); expectedDynamicFields.put("secondDynamicProperty", "secondDynamicPropertyValue"); expectedDynamicFields.put("newProperty", "newPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etag取得 String etag = res.getHeader(HttpHeaders.ETAG); long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(userDataId, etag, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(userDataId); } } /** * UserDataのリクエストボディに最大要素数のプロパティを登録し存在するプロパティを1つ指定してMERGEできること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのリクエストボディに最大要素数のプロパティを登録し存在するプロパティを1つ指定してMERGEできること() { String userDataId = "userdata001"; // 最大要素数 int maxPropNum = PersoniumUnitConfig.getMaxPropertyCountInEntityType(); // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); for (int i = 0; i < maxPropNum; i++) { createReqBody.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty" + 0, "updatePropertyValue" + 0); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty" + 0, "updatePropertyValue" + 0); for (int i = 1; i < maxPropNum; i++) { expectedDynamicFields.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } String entityType = Setup.TEST_ENTITYTYPE_MDP; try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン情報取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, MASTER_TOKEN_NAME, -1); } } /** * UserDataのリクエストボディに最大要素数の存在するプロパティを指定してMERGEできること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのリクエストボディに最大要素数の存在するプロパティを指定してMERGEできること() { String userDataId = "userdata001"; // 最大要素数 int maxPropNum = PersoniumUnitConfig.getMaxPropertyCountInEntityType(); // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); for (int i = 0; i < maxPropNum; i++) { createReqBody.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); for (int i = 0; i < maxPropNum; i++) { updateReqBody.put("dynamicProperty" + i, "updatePropertyValue" + i); } // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); for (int i = 0; i < maxPropNum; i++) { expectedDynamicFields.put("dynamicProperty" + i, "updatePropertyValue" + i); } String entityType = Setup.TEST_ENTITYTYPE_MDP; try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン情報取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, MASTER_TOKEN_NAME, -1); } } /** * UserDataのリクエストボディに最大要素数プラス1の存在するプロパティを指定して400エラーとなること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのリクエストボディに最大要素数プラス1の存在するプロパティを指定して400エラーとなること() { String userDataId = "userdata001"; // 最大要素数 int maxPropNum = PersoniumUnitConfig.getMaxPropertyCountInEntityType(); // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); for (int i = 0; i < maxPropNum; i++) { createReqBody.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); for (int i = 0; i < maxPropNum + 1; i++) { updateReqBody.put("dynamicProperty" + i, "updatePropertyValue" + i); } String entityType = Setup.TEST_ENTITYTYPE_MDP; try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType); // マージリクエスト実行 res = mergeRequest(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, updateReqBody); res.statusCode(HttpStatus.SC_BAD_REQUEST); ODataCommon.checkErrorResponseBody(res, PersoniumCoreException.OData.ENTITYTYPE_STRUCTUAL_LIMITATION_EXCEEDED.getCode(), PersoniumCoreException.OData.ENTITYTYPE_STRUCTUAL_LIMITATION_EXCEEDED.getMessage()); } finally { deleteUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, MASTER_TOKEN_NAME, -1); } } /** * UserDataのMERGE後のプロパティ数が最大要素数の場合にMERGEできること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGE後のプロパティ数が最大要素数の場合にMERGEできること() { String userDataId = "userdata001"; // 最大要素数 int maxPropNum = PersoniumUnitConfig.getMaxPropertyCountInEntityType(); // 初期作成用のリクエストボディ // 最大要素数 - 1のプロパティを指定 JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); for (int i = 0; i < maxPropNum - 1; i++) { createReqBody.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty399", "newPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); for (int i = 0; i < maxPropNum - 1; i++) { expectedDynamicFields.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } expectedDynamicFields.put("dynamicProperty399", "newPropertyValue"); String entityType = Setup.TEST_ENTITYTYPE_MDP; try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン情報取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, expectedDynamicFields, etag, published); } finally { deleteUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, MASTER_TOKEN_NAME, -1); } } /** * UserDataのMERGE後のプロパティ数が最大要素数プラス1の場合に400エラーとなること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGE後のプロパティ数が最大要素数プラス1の場合に400エラーとなること() { String userDataId = "userdata001"; // 最大要素数 int maxPropNum = PersoniumUnitConfig.getMaxPropertyCountInEntityType(); // 初期作成用のリクエストボディ // 最大要素数 - 1のプロパティを指定 JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); for (int i = 0; i < maxPropNum - 1; i++) { createReqBody.put("dynamicProperty" + i, "dynamicPropertyValue" + i); } // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("newProperty1", "newPropertyValue1"); updateReqBody.put("newProperty2", "newPropertyValue2"); String entityType = Setup.TEST_ENTITYTYPE_MDP; try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType); // マージリクエスト実行 res = mergeRequest(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, updateReqBody); res.statusCode(HttpStatus.SC_BAD_REQUEST); ODataCommon.checkErrorResponseBody(res, PersoniumCoreException.OData.ENTITYTYPE_STRUCTUAL_LIMITATION_EXCEEDED.getCode(), PersoniumCoreException.OData.ENTITYTYPE_STRUCTUAL_LIMITATION_EXCEEDED.getMessage()); } finally { deleteUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityType, userDataId, MASTER_TOKEN_NAME, -1); } } /** * UserDataのMERGEでstaticプロパティのみを指定した場合指定したプロパティのみ更新されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGEでstaticプロパティのみを指定した場合指定したプロパティのみ更新されること() { String userDataId = "userdata001"; String propName = "declaredProperty"; String locationUserData = null, locationProperty = null; // Nullable=flaseのPropertyを追加 PersoniumResponse resProperty = UserDataUtils.createProperty(cellName, boxName, Setup.TEST_ODATA, propName, "Category", "Edm.String", false, "", "None", false, null); locationProperty = resProperty.getFirstHeader(HttpHeaders.LOCATION); // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); createReqBody.put(propName, "declaredPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put(propName, "updateDeclaredPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty", "dynamicPropertyValue"); expectedDynamicFields.put("secondDynamicProperty", "secondDynamicPropertyValue"); expectedDynamicFields.put(propName, "updateDeclaredPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); locationUserData = res.getLocationHeader(); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(userDataId, expectedDynamicFields, etag, published); } finally { if (locationUserData != null) { ODataCommon.deleteOdataResource(locationUserData); } if (locationProperty != null) { ODataCommon.deleteOdataResource(locationProperty); } } } /** * UserDataのMERGEでdynamicプロパティのみを指定した場合指定したプロパティのみ更新されること. */ @SuppressWarnings("unchecked") @Test public final void UserDataのMERGEでdynamicプロパティのみを指定した場合指定したプロパティのみ更新されること() { String userDataId = "userdata001"; String propName = "declaredProperty"; String locationUserData = null, locationProperty = null; // Nullable=flaseのPropertyを追加 PersoniumResponse resProperty = UserDataUtils.createProperty(cellName, boxName, Setup.TEST_ODATA, propName, "Category", "Edm.String", false, "", "None", false, null); locationProperty = resProperty.getFirstHeader(HttpHeaders.LOCATION); // 初期作成用のリクエストボディ JSONObject createReqBody = new JSONObject(); createReqBody.put("__id", userDataId); createReqBody.put("dynamicProperty", "dynamicPropertyValue"); createReqBody.put("secondDynamicProperty", "secondDynamicPropertyValue"); createReqBody.put(propName, "declaredPropertyValue"); // MERGE用のリクエストボディ JSONObject updateReqBody = new JSONObject(); updateReqBody.put("dynamicProperty", "updateDynamicPropertyValue"); // チェック項目の作成 Map<String, Object> expectedDynamicFields = new HashMap<String, Object>(); expectedDynamicFields.put("dynamicProperty", "updateDynamicPropertyValue"); expectedDynamicFields.put("secondDynamicProperty", "secondDynamicPropertyValue"); expectedDynamicFields.put(propName, "declaredPropertyValue"); try { TResponse res = createUserData(createReqBody, HttpStatus.SC_CREATED); locationUserData = res.getLocationHeader(); // __publishedの取得 String published = ODataCommon.getPublished(res); // Etagのバージョン取得 long version = ODataCommon.getEtagVersion(res.getHeader(HttpHeaders.ETAG)); // マージリクエスト実行 res = mergeRequest(userDataId, updateReqBody); res.statusCode(HttpStatus.SC_NO_CONTENT); // レスポンスヘッダからETAGを取得する String etag = res.getHeader(HttpHeaders.ETAG); // レスポンスヘッダーのチェック ODataCommon.checkCommonResponseHeader(res, version + 1); // ユーザデータが更新されていることを確認 checkUserData(userDataId, expectedDynamicFields, etag, published); } finally { if (locationUserData != null) { ODataCommon.deleteOdataResource(locationUserData); } if (locationProperty != null) { ODataCommon.deleteOdataResource(locationProperty); } } } /** * 登録済のダイナミックプロパティにnullを指定して正常に部分更新できること. */ @SuppressWarnings("unchecked") @Test public final void 登録済のダイナミックプロパティにnullを指定して正常に部分更新できること() { String entityTypeName = "srcEntity"; // 登録用リクエストボディ String userDataFirstId = "userdata"; JSONObject bodyFirst = new JSONObject(); bodyFirst.put("__id", userDataFirstId); bodyFirst.put("dynamicProperty1", null); bodyFirst.put("dynamicProperty2", null); bodyFirst.put("First", "test1"); // 更新用リクエストボディ:dynamicProperty2は省略 JSONObject bodySecond = new JSONObject(); bodySecond.put("__id", userDataFirstId); bodySecond.put("dynamicProperty1", null); bodySecond.put("dynamicProperty3", null); bodySecond.put("Second", "test2"); // リクエスト実行 try { // EntityType作成 EntityTypeUtils.create(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, Setup.TEST_BOX1, Setup.TEST_ODATA, entityTypeName, HttpStatus.SC_CREATED); // ユーザODataを登録 UserDataUtils.create(AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_CREATED, bodyFirst, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityTypeName); // ユーザデータの取得 TResponse response = getUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityTypeName, userDataFirstId, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK); JSONObject resBody = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); assertTrue(resBody.containsKey("dynamicProperty1")); assertNull(resBody.get("dynamicProperty1")); assertTrue(resBody.containsKey("dynamicProperty2")); assertNull(resBody.get("dynamicProperty2")); assertTrue(resBody.containsKey("First")); assertNotNull(resBody.get("First")); // レスポンスボディーのチェック Map<String, Object> additionalFirst = new HashMap<String, Object>(); additionalFirst.put("__id", userDataFirstId); additionalFirst.put("dynamicProperty", "dynamicPropertyValue"); // ユーザODataを更新 UserDataUtils.merge(AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT, bodySecond, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityTypeName, userDataFirstId, "*"); // ユーザデータの取得 response = getUserData(Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA, entityTypeName, userDataFirstId, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK); resBody = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); // レスポンスボディーのチェック assertTrue(resBody.containsKey("dynamicProperty1")); assertNull(resBody.get("dynamicProperty1")); assertTrue(resBody.containsKey("dynamicProperty2")); assertNull(resBody.get("dynamicProperty2")); assertTrue(resBody.containsKey("dynamicProperty3")); assertNull(resBody.get("dynamicProperty3")); assertTrue(resBody.containsKey("First")); assertNotNull(resBody.get("First")); assertTrue(resBody.containsKey("Second")); assertNotNull(resBody.get("Second")); } finally { UserDataUtils.delete(AbstractCase.MASTER_TOKEN_NAME, -1, entityTypeName, userDataFirstId, Setup.TEST_ODATA); Setup.entityTypeDelete(Setup.TEST_ODATA, entityTypeName, Setup.TEST_CELL1, Setup.TEST_BOX1); } } private TResponse mergeRequest(String userDataId, JSONObject updateReqBody) { return mergeRequest(userDataId, "*", updateReqBody); } private TResponse mergeRequest(String userDataId, String ifMatch, JSONObject updateReqBody) { return Http.request("box/odatacol/merge.txt") .with("cell", cellName) .with("box", boxName) .with("collection", colName) .with("entityType", entityTypeName) .with("id", userDataId) .with("accept", MediaType.APPLICATION_JSON) .with("contentType", MediaType.APPLICATION_JSON) .with("ifMatch", ifMatch) .with("token", PersoniumUnitConfig.getMasterToken()) .with("body", updateReqBody.toJSONString()) .returns() .debug(); } private TResponse mergeRequest(String cell, String box, String col, String entityType, String userDataId, JSONObject updateReqBody) { return Http.request("box/odatacol/merge.txt") .with("cell", cell) .with("box", box) .with("collection", col) .with("entityType", entityType) .with("id", userDataId) .with("accept", MediaType.APPLICATION_JSON) .with("contentType", MediaType.APPLICATION_JSON) .with("ifMatch", "*") .with("token", PersoniumUnitConfig.getMasterToken()) .with("body", updateReqBody.toJSONString()) .returns() .debug(); } /** * ユーザデータが更新されていることを確認する. * @param userDataId userDataId * @param additional additional * @param etag etag * @param published published */ public final void checkUserData(String userDataId, Map<String, Object> additional, String etag, String published) { checkUserData(cellName, boxName, colName, entityTypeName, userDataId, additional, etag, published); } /** * ユーザデータが更新されていることを確認する. * @param cell セル名 * @param box ボックス名 * @param col コレクション名 * @param entityType エンティティタイプ名 * @param userDataId userDataId * @param additional additional * @param etag etag * @param published published */ public final void checkUserData(String cell, String box, String col, String entityType, String userDataId, Map<String, Object> additional, String etag, String published) { // ユーザデータの取得 TResponse getResponse = getUserData(cell, box, col, entityType, userDataId, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK); // レスポンスボディーのチェック String nameSpace = getNameSpace(entityType); ODataCommon.checkResponseBody(getResponse.bodyAsJson(), null, nameSpace, additional, null, etag, published); } }
38.322949
119
0.643571
83995121e071eaebff3578f37d891168f7424769
3,303
package org.eclipse.aether.spi.connector; /* * 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. */ import java.io.File; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.transfer.ArtifactTransferException; /** * A download/upload of an artifact. * * @noextend This class is not intended to be extended by clients. */ public abstract class ArtifactTransfer extends Transfer { private Artifact artifact; private File file; private ArtifactTransferException exception; ArtifactTransfer() { // hide } /** * Gets the artifact being transferred. * * @return The artifact being transferred or {@code null} if not set. */ public Artifact getArtifact() { return artifact; } /** * Sets the artifact to transfer. * * @param artifact The artifact, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ public ArtifactTransfer setArtifact( Artifact artifact ) { this.artifact = artifact; return this; } /** * Gets the local file the artifact is downloaded to or uploaded from. In case of a download, a connector should * first transfer the bytes to a temporary file and only overwrite the target file once the entire download is * completed such that an interrupted/failed download does not corrupt the current file contents. * * @return The local file or {@code null} if not set. */ public File getFile() { return file; } /** * Sets the local file the artifact is downloaded to or uploaded from. * * @param file The local file, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ public ArtifactTransfer setFile( File file ) { this.file = file; return this; } /** * Gets the exception that occurred during the transfer (if any). * * @return The exception or {@code null} if the transfer was successful. */ public ArtifactTransferException getException() { return exception; } /** * Sets the exception that occurred during the transfer. * * @param exception The exception, may be {@code null} to denote a successful transfer. * @return This transfer for chaining, never {@code null}. */ public ArtifactTransfer setException( ArtifactTransferException exception ) { this.exception = exception; return this; } }
28.474138
116
0.66818
27fb0feb5704013d5980d98db96842d1f9a6c573
370
class Solution { public int XXX(String haystack, String needle) { int l1=haystack.length(); int l2=needle.length(); if(l2==0) return 0; if(l1==0) return -1; for(int i = 0;i<l1-l2+1;i++){ if(haystack.substring(i,i+l2).equals(needle)){ return i; } } return -1; } }
21.764706
58
0.472973
f605f16c7c8f6bf99fcb6db8eb8926c2bce153cd
276
package me.cchu.mall.ware.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import me.cchu.mall.ware.entity.WareOrderTaskEntity; import org.apache.ibatis.annotations.Mapper; @Mapper public interface WareOrderTaskDao extends BaseMapper<WareOrderTaskEntity> { }
23
75
0.826087
8b79afbbf1e007f659b5119edf302ff0b016fc27
1,354
package info.scry.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.Signature; import android.content.pm.PackageManager; import java.security.MessageDigest; public class Utils{ public static byte[] getSignature(Context context) { try { String pkgname = context.getPackageName(); PackageManager manager = context.getPackageManager(); PackageInfo packageInfo = manager.getPackageInfo(pkgname, PackageManager.GET_SIGNATURES); Signature[] signatures = packageInfo.signatures; return signatures[0].toByteArray(); } catch (Exception e) { return null; } } public static String md5(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes); byte[] b = md.digest(); int i; StringBuilder sb = new StringBuilder(); for (byte value : b) { i = value; if (i < 0) i += 256; if (i < 16) sb.append("0"); sb.append(Integer.toHexString(i)); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } }
31.488372
101
0.55096
423e5ca2b4a260e63ff2c286c9394414dc6cb286
6,415
package com.rockchip.alexa.jacky.activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.KeyEvent; import com.amazon.identity.auth.device.AuthError; import com.amazon.identity.auth.device.api.authorization.AuthCancellation; import com.amazon.identity.auth.device.api.authorization.AuthorizeListener; import com.amazon.identity.auth.device.api.authorization.AuthorizeResult; import com.amazon.identity.auth.device.api.workflow.RequestContext; import com.rockchip.alexa.jacky.R; import com.rockchip.alexa.jacky.app.AuthConstants; import com.rockchip.alexa.jacky.app.AuthManager; import com.rockchip.alexa.jacky.app.BaseApplication; import com.rockchip.alexa.jacky.fragment.AlexaAuthorSuccessFragment; import com.rockchip.alexa.jacky.fragment.CompatActivity; import com.rockchip.alexa.jacky.fragment.NoFragment; import com.rockchip.alexa.jacky.fragment.SupportsFragment; import com.rockchip.alexa.jacky.info.CompanionProvisioningInfo; import com.rockchip.alexa.jacky.info.DeviceProvisioningInfo; import com.rockchip.alexa.jacky.info.ProvisioningClient; import com.rockchip.alexa.jacky.socket.TcpClient; /** * Created by Administrator on 2017/3/21. */ public class AlexaActivity extends CompatActivity { private static final String TAG = "AlexaActivity"; private RequestContext mRequestContext; private ProvisioningClient mProvisioningClient; private DeviceProvisioningInfo mDeviceProvisioningInfo; private String deviceIp; private NoFragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRequestContext = RequestContext.create(this); mRequestContext.registerListener(new AuthorizeListenerImpl()); try { mProvisioningClient = ProvisioningClient.getProvisioningClient(this); } catch (Exception e) { Log.e(TAG, "Unable to use Provisioning Client. CA Certificate is incorrect or does not exist.", e); } startFragment(SupportsFragment.class); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); mRequestContext.onResume(); } @Override protected int fragmentLayoutId() { return R.id.fragment_root; } public void setFragment(NoFragment fragment) { this.mFragment = fragment; } public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public DeviceProvisioningInfo getDeviceProvisioningInfo() { return mDeviceProvisioningInfo; } public RequestContext getRequestContext() { return mRequestContext; } public void setDeviceProvisioningInfo(DeviceProvisioningInfo mDeviceProvisioningInfo) { this.mDeviceProvisioningInfo = mDeviceProvisioningInfo; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } private CompanionProvisioningInfo companionProvisioningInfo; private boolean mIsAuthorized; public boolean isAuthorized() { return mIsAuthorized; } public void setAuthorized(boolean isAuthorized) { this.mIsAuthorized = isAuthorized; } private class AuthorizeListenerImpl extends AuthorizeListener { @Override public void onSuccess(final AuthorizeResult authorizeResult) { BaseApplication.getApplication().setAuthorizeTime(SystemClock.uptimeMillis()); final String authorizationCode = authorizeResult.getAuthorizationCode(); final String redirectUri = authorizeResult.getRedirectURI(); final String clientId = authorizeResult.getClientId(); final String sessionId = getDeviceProvisioningInfo().getSessionId(); companionProvisioningInfo = new CompanionProvisioningInfo(sessionId, clientId, redirectUri, authorizationCode, getDeviceProvisioningInfo().getCodeVerifier()); AuthManager.getAuthManager().setCompanionProvisioningInfo(companionProvisioningInfo); new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... voids) { try { Log.d(TAG, "result:" + companionProvisioningInfo.toJson().toString()); if (AuthConstants.COMMUNICATE_TYPE.equals(AuthConstants.CommunicateType.SOCKET)) { TcpClient client = new TcpClient(); client.connect(getDeviceIp(), 1221); Thread.sleep(1000); client.send(companionProvisioningInfo.toJson().toString()); if (mFragment != null) { mFragment.startFragment(AlexaAuthorSuccessFragment.class); } } else if (AuthConstants.COMMUNICATE_TYPE.equals(AuthConstants.CommunicateType.HTTPS)) { if (mFragment != null) { mFragment.startFragment(AlexaAuthorSuccessFragment.class); } } } catch (Exception e) { Log.e(TAG, "Post CompanionProvisioningInfo fail", e); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } }.execute(); } @Override public void onError(final AuthError authError) { Log.e(TAG, "AuthError during authorization", authError); } @Override public void onCancel(final AuthCancellation authCancellation) { Log.e(TAG, "User cancelled authorization"); } } }
37.51462
171
0.638504
d7f09fb1976602a9c5a5ff0fe609fa934249765b
41,597
package tfc.smallerunits.utils.world.client; import net.minecraft.block.*; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientChunkProvider; import net.minecraft.client.network.play.ClientPlayNetHandler; import net.minecraft.client.particle.DiggingParticle; import net.minecraft.client.particle.Particle; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.settings.ParticleStatus; import net.minecraft.client.world.ClientWorld; import net.minecraft.client.world.DimensionRenderInfo; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.FluidState; import net.minecraft.item.crafting.RecipeManager; import net.minecraft.particles.IParticleData; import net.minecraft.particles.ParticleTypes; import net.minecraft.profiler.IProfiler; import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.*; import net.minecraft.util.math.*; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.registry.DynamicRegistries; import net.minecraft.util.registry.Registry; import net.minecraft.world.DimensionType; import net.minecraft.world.LightType; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeContainer; import net.minecraft.world.biome.BiomeManager; import net.minecraft.world.biome.BiomeRegistry; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkStatus; import net.minecraft.world.chunk.IChunk; import net.minecraft.world.lighting.WorldLightManager; import tfc.smallerunits.SmallerUnitsTESR; import tfc.smallerunits.api.SmallerUnitsAPI; import tfc.smallerunits.api.placement.UnitPos; import tfc.smallerunits.block.UnitTileEntity; import tfc.smallerunits.registry.Deferred; import tfc.smallerunits.utils.ExternalUnitInteractionContext; import tfc.smallerunits.utils.SmallUnit; import tfc.smallerunits.utils.world.common.FakeChunk; import javax.annotation.Nullable; import java.util.*; import java.util.function.BooleanSupplier; import java.util.function.Predicate; import java.util.function.Supplier; public class FakeClientWorld extends ClientWorld { public Map<Long, SmallUnit> blockMap; public BlockRayTraceResult result; public UnitTileEntity owner; int maxID = 0; int oldLight = 0; public FakeClientLightingManager lightManager = new FakeClientLightingManager(this.getChunkProvider(), true, true, this); @Override public WorldLightManager getLightManager() { return lightManager; } public FakeClientWorld(ClientPlayNetHandler p_i242067_1_, ClientWorldInfo p_i242067_2_, RegistryKey<World> p_i242067_3_, DimensionType p_i242067_4_, int p_i242067_5_, Supplier<IProfiler> p_i242067_6_, WorldRenderer p_i242067_7_, boolean p_i242067_8_, long p_i242067_9_) { super(p_i242067_1_, p_i242067_2_, p_i242067_3_, p_i242067_4_, p_i242067_5_, p_i242067_6_, p_i242067_7_, p_i242067_8_, p_i242067_9_); FakeClientWorld world = this; this.field_239129_E_ = new ClientChunkProvider(this, 1) { @Nullable @Override public Chunk getChunk(int chunkX, int chunkZ, ChunkStatus requiredStatus, boolean load) { return new FakeChunk(world, new ChunkPos(chunkX, chunkZ), new BiomeContainer(new ObjectIntIdentityMap<>()), world); } }; blockMap = new HashMap<>(); // this.addedTileEntityList = new ArrayList<>(); // this.loadedTileEntityList = new ArrayList<>(); // this.tickableTileEntities = new ArrayList<>(); } private static final Biome[] BIOMES = Util.make(new Biome[BiomeContainer.BIOMES_SIZE], (biomes) -> { Arrays.fill(biomes, BiomeRegistry.PLAINS); }); @Override public Chunk getChunk(int chunkX, int chunkZ) { return new FakeChunk(this, new ChunkPos(chunkX, chunkZ), new BiomeContainer( owner.getWorld().func_241828_r().getRegistry(Registry.BIOME_KEY), BIOMES), this ); } @Override public int getLightFor(LightType lightTypeIn, BlockPos blockPosIn) { if (lightTypeIn.equals(LightType.BLOCK)) { ExternalUnitInteractionContext context = new ExternalUnitInteractionContext(this, blockPosIn); if (context.posInRealWorld != null && context.posInFakeWorld != null) { if (context.stateInRealWorld != null) { if (context.stateInRealWorld.equals(Deferred.UNIT.get().getDefaultState())) { if (!context.posInRealWorld.equals(this.owner.getPos())) { if (context.teInRealWorld != null) { if (((UnitTileEntity) context.teInRealWorld).worldClient != null && ((UnitTileEntity) context.teInRealWorld).worldClient.get().lightManager != null) { return ((UnitTileEntity) context.teInRealWorld).getFakeWorld().getLightFor(lightTypeIn, context.posInFakeWorld); } } } } } } } if (lightTypeIn.equals(LightType.BLOCK)) { return Math.max( ((FakeClientLightingManager) lightManager).getBlockLight(blockPosIn.offset(Direction.DOWN, 64)), owner.getWorld().getLightFor(lightTypeIn, owner.getPos()) ); } else { return Math.max( // lightManager.getLightEngine(lightTypeIn).getLightFor(blockPosIn), 0, owner.getWorld().getLightFor(lightTypeIn, owner.getPos()) ); } } @Override public int getLightSubtracted(BlockPos blockPosIn, int amount) { return Math.max( lightManager.getLightSubtracted(blockPosIn, amount), owner.getWorld().getLightSubtracted(owner.getPos(), amount) ); } @Override public int getLightValue(BlockPos pos) { return Math.max( getLightFor(LightType.BLOCK, pos), getLightFor(LightType.SKY, pos) ); } @Override public BlockRayTraceResult rayTraceBlocks(RayTraceContext context) { return result == null ? super.rayTraceBlocks(context) : result; } public DimensionRenderInfo func_239132_a_() { if (owner.getWorld() == null) { return new DimensionRenderInfo.Overworld(); } DimensionRenderInfo info = ((ClientWorld) this.owner.getWorld()).func_239132_a_(); return info == null ? new DimensionRenderInfo.Overworld() : info; } @Nullable @Override public BlockRayTraceResult rayTraceBlocks(Vector3d startVec, Vector3d endVec, BlockPos pos, VoxelShape shape, BlockState state) { return result == null ? super.rayTraceBlocks(startVec, endVec, pos, shape, state) : result; } @Override public boolean addEntity(Entity entityIn) { entityIn.world = this; addEntity(maxID, entityIn); return true; } @Override public void addEntity(int entityIdIn, Entity entityToSpawn) { boolean setId = false; for (int i = 0; i < entitiesById.size(); i++) { if (!entitiesById.containsKey(i)) { entityToSpawn.setEntityId(i); setId = true; break; } } if (!setId) { entityToSpawn.setEntityId(maxID); } entitiesById.put(entityToSpawn.getEntityId(), entityToSpawn); if (!setId) { maxID = Math.max(maxID, entityIdIn + 1); } } @Override public void addParticle(IParticleData particleData, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed) { if (Minecraft.getInstance().gameSettings.particles.equals(ParticleStatus.ALL) || Minecraft.getInstance().gameSettings.particles.equals(ParticleStatus.DECREASED)) { Particle particle = Minecraft.getInstance().particles.makeParticle(particleData, owner.getPos().getX() + (x / owner.unitsPerBlock), owner.getPos().getY() + ((y - 64) / owner.unitsPerBlock), owner.getPos().getZ() + (z / owner.unitsPerBlock), xSpeed / owner.unitsPerBlock, ySpeed / owner.unitsPerBlock, zSpeed / owner.unitsPerBlock ); if (particle == null) return; particle = particle.multiplyParticleScaleBy(1f / owner.unitsPerBlock); Minecraft.getInstance().particles.addEffect(particle); } // owner.getWorld().addParticle(particleData, // owner.getPos().getX() + (x / owner.unitsPerBlock), // owner.getPos().getY() + ((y - 64) / owner.unitsPerBlock), // owner.getPos().getZ() + (z / owner.unitsPerBlock), // xSpeed / owner.unitsPerBlock, ySpeed / owner.unitsPerBlock, zSpeed / owner.unitsPerBlock // ); } @Override public boolean checkNoEntityCollision(@Nullable Entity entityIn, VoxelShape shape) { for (AxisAlignedBB axisAlignedBB : shape.toBoundingBoxList()) { for (Entity entity : this.getEntitiesWithinAABBExcludingEntity(entityIn, axisAlignedBB)) { if (!entity.removed && entity.preventEntitySpawning) { return false; } } } return true; } @Override public List<Entity> getEntitiesWithinAABBExcludingEntity(@Nullable Entity entityIn, AxisAlignedBB aabb) { List<Entity> entities = super.getEntitiesWithinAABBExcludingEntity(entityIn, aabb); AxisAlignedBB aabb1 = new AxisAlignedBB(0, 0, 0, aabb.getXSize() / owner.unitsPerBlock, aabb.getYSize() / owner.unitsPerBlock, aabb.getZSize() / owner.unitsPerBlock); AxisAlignedBB bb = aabb1.offset( aabb.minX / owner.unitsPerBlock, (aabb.minY - 64) / owner.unitsPerBlock, aabb.minZ / owner.unitsPerBlock ).offset(owner.getPos().getX(), owner.getPos().getY(), owner.getPos().getZ()); entities.addAll(owner.getWorld().getEntitiesWithinAABBExcludingEntity(entityIn, bb)); return entities; } @Override public boolean hasNoCollisions(AxisAlignedBB aabb) { return true; } @Override public boolean hasNoCollisions(Entity entity) { return true; } @Override public boolean hasNoCollisions(Entity entity, AxisAlignedBB aabb) { return true; } @Override public boolean hasNoCollisions(@Nullable Entity entity, AxisAlignedBB aabb, Predicate<Entity> entityPredicate) { return true; } @Override public void addParticle(IParticleData particleData, boolean forceAlwaysRender, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed) { addParticle(particleData, x, y, z, xSpeed, ySpeed, zSpeed); // owner.getWorld().addParticle(particleData, forceAlwaysRender, // owner.getPos().getX() + (x / owner.unitsPerBlock), // owner.getPos().getY() + ((y - 64) / owner.unitsPerBlock), // owner.getPos().getZ() + (z / owner.unitsPerBlock), // xSpeed / owner.unitsPerBlock, ySpeed / owner.unitsPerBlock, zSpeed / owner.unitsPerBlock // ); } @Override public void addOptionalParticle(IParticleData particleData, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed) { if (Minecraft.getInstance().gameSettings.particles.equals(ParticleStatus.ALL)) { Particle particle = Minecraft.getInstance().particles.makeParticle(particleData, owner.getPos().getX() + (x / owner.unitsPerBlock), owner.getPos().getY() + ((y - 64) / owner.unitsPerBlock), owner.getPos().getZ() + (z / owner.unitsPerBlock), xSpeed / owner.unitsPerBlock, ySpeed / owner.unitsPerBlock, zSpeed / owner.unitsPerBlock ); if (particle == null) return; particle = particle.multiplyParticleScaleBy(1f / owner.unitsPerBlock); Minecraft.getInstance().particles.addEffect(particle); } // owner.getWorld().addOptionalParticle(particleData, // owner.getPos().getX() + (x / owner.unitsPerBlock), // owner.getPos().getY() + ((y - 64) / owner.unitsPerBlock), // owner.getPos().getZ() + (z / owner.unitsPerBlock), // xSpeed / owner.unitsPerBlock, ySpeed / owner.unitsPerBlock, zSpeed / owner.unitsPerBlock // ); } @Override public void addOptionalParticle(IParticleData particleData, boolean ignoreRange, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed) { addOptionalParticle(particleData, x, y, z, xSpeed, ySpeed, zSpeed); // owner.getWorld().addOptionalParticle(particleData, ignoreRange, // owner.getPos().getX() + (x / owner.unitsPerBlock), // owner.getPos().getY() + ((y - 64) / owner.unitsPerBlock), // owner.getPos().getZ() + (z / owner.unitsPerBlock), // xSpeed / owner.unitsPerBlock, ySpeed / owner.unitsPerBlock, zSpeed / owner.unitsPerBlock // ); } private final ArrayList<BlockPos> removedTileEntities = new ArrayList<>(); @Override public boolean addTileEntity(TileEntity tile) { if (!(tile.getPos() instanceof UnitPos)) tile.setPos(SmallerUnitsAPI.createPos(tile.getPos(), owner)); setTileEntity(tile.getPos(), tile); return true; } @Override public void addTileEntities(Collection<TileEntity> tileEntityCollection) { for (TileEntity tileEntity : tileEntityCollection) addTileEntity(tileEntity); } @Override public BiomeManager getBiomeManager() { World world = this; return new BiomeManager(this, 0, (seed, x, y, z, biomeReader) -> world.getBiome(new BlockPos(x, y, z))) { @Override public Biome getBiomeAtPosition(double x, double y, double z) { return getBiomeAtPosition(new BlockPos(x, y, z)); } @Override public Biome getBiomeAtPosition(BlockPos pos) { pos = new UnitPos(pos, owner.getPos(), owner.unitsPerBlock).adjustRealPosition(); return owner.getWorld().getBiome(((UnitPos) pos).realPos); } @Override public Biome getBiomeAtPosition(int x, int y, int z) { return getBiomeAtPosition(new BlockPos(x, y, z)); } }; } @Override public Biome getBiome(BlockPos pos) { pos = new UnitPos(pos, owner.getPos(), owner.unitsPerBlock).adjustRealPosition(); return owner.getWorld().getBiome(((UnitPos) pos).realPos); } public BlockPos getPos() { return owner.getPos(); } @Override public void markBlockRangeForRenderUpdate(BlockPos blockPosIn, BlockState oldState, BlockState newState) { notifyBlockUpdate(null, null, null, 0); } @Override public void markSurroundingsForRerender(int sectionX, int sectionY, int sectionZ) { notifyBlockUpdate(null, null, null, 0); } @Override public void notifyBlockUpdate(BlockPos pos, BlockState oldState, BlockState newState, int flags) { // for (Direction dir : Direction.values()) { // if (SmallerUnitsTESR.bufferCache.containsKey(this.getPos().offset(dir))) { // SmallerUnitsTESR.bufferCache.get(this.getPos().offset(dir)).getSecond().dispose(); // } // // SmallerUnitsTESR.bufferCache.remove(this.getPos().offset(dir)); // } // // if (SmallerUnitsTESR.bufferCache.containsKey(this.getPos())) { // SmallerUnitsTESR.bufferCache.get(this.getPos()).getSecond().dispose(); // } // // SmallerUnitsTESR.bufferCache.remove(this.getPos()); if (SmallerUnitsTESR.bufferCache.containsKey(this.getPos())) { SmallerUnitsTESR.bufferCache.get(this.getPos()).getSecond().isDirty = true; } owner.needsRefresh(true); } @Override public void setTileEntity(BlockPos pos, @Nullable TileEntity tileEntityIn) { if (removedTileEntities.contains(pos)) removedTileEntities.remove(pos); ExternalUnitInteractionContext context = new ExternalUnitInteractionContext(this, pos); if (context.posInRealWorld != null) { if (context.stateInRealWorld != null) { if (context.stateInRealWorld.equals(Deferred.UNIT.get().getDefaultState())) { if (!context.posInRealWorld.equals(this.owner.getPos())) { if (context.teInRealWorld != null) { ((UnitTileEntity) context.teInRealWorld).getFakeWorld().setTileEntity(context.posInFakeWorld, tileEntityIn); return; } } } } } SmallUnit unit = blockMap.getOrDefault(pos.toLong(), new SmallUnit(SmallerUnitsAPI.createPos(pos, owner), Blocks.AIR.getDefaultState())); if (unit.tileEntity != null && unit.tileEntity != tileEntityIn) { try { unit.tileEntity.remove(); } catch (Throwable ignored) { } loadedTileEntityList.remove(tileEntityIn); } if (tileEntityIn != null && tileEntityIn.getType().isValidBlock(unit.state.getBlock())) { unit.tileEntity = tileEntityIn; tileEntityIn.setWorldAndPos(this, pos); if (tileEntityIn != null) tileEntityIn.validate(); loadedTileEntityList.add(unit.tileEntity); if (!blockMap.containsKey(pos.toLong())) blockMap.put(pos.toLong(), unit); } else { if (unit.tileEntity != null) unit.tileEntity.remove(); unit.tileEntity = null; } // tileEntityChanges.add(unit); } @Override public void playEvent(int type, BlockPos pos, int data) { playEvent(null, type, pos, data); } @Override public RecipeManager getRecipeManager() { return owner.getWorld().getRecipeManager(); } public BlockState getBlockState(BlockPos pos) { ExternalUnitInteractionContext context = new ExternalUnitInteractionContext(this, pos); if (context.posInRealWorld != null && context.posInFakeWorld != null) { if (context.stateInRealWorld != null) { if (context.stateInRealWorld.equals(Deferred.UNIT.get().getDefaultState())) { if (!context.posInRealWorld.equals(this.owner.getPos())) { if (context.teInRealWorld != null) { if (((UnitTileEntity) context.teInRealWorld).getFakeWorld() != null) { return ((UnitTileEntity) context.teInRealWorld).getFakeWorld().getBlockState(context.posInFakeWorld); } } } } else if (true) { for (Direction value : Direction.values()) { if (context.posInRealWorld.equals(owner.getPos().offset(value))) { if (!(context.teInRealWorld instanceof UnitTileEntity)) { BlockState state = owner.getWorld().getBlockState(context.posInRealWorld); return state; } } } } if (!context.stateInRealWorld.equals(Deferred.UNIT.get().getDefaultState())) { if (context.stateInRealWorld.equals(Blocks.BEDROCK.getDefaultState())) { return Blocks.BEDROCK.getDefaultState(); } else if (context.stateInRealWorld.equals(Blocks.BARRIER.getDefaultState())) { return Blocks.BARRIER.getDefaultState(); } } } } return blockMap.getOrDefault(pos.toLong(), new SmallUnit(SmallerUnitsAPI.createPos(pos, owner), Blocks.AIR.getDefaultState())).state; } public void init(UnitTileEntity owner) { this.owner = owner; IProfiler profiler = new Profiler(() -> 0, () -> 0, false); this.profiler = () -> profiler; } @Override public boolean isBlockPresent(BlockPos pos) { return blockMap.containsKey(pos.offset(Direction.DOWN, 64).toLong()); } @Override public void tick(BooleanSupplier hasTimeLeft) { int newLight = LightTexture.packLight(owner.getWorld().getLightFor(LightType.BLOCK, owner.getPos()), owner.getWorld().getLightFor(LightType.SKY, owner.getPos())); if (newLight != oldLight) owner.needsRefresh(true); oldLight = newLight; this.worldRenderer = Minecraft.getInstance().worldRenderer; this.getProfiler().startTick(); super.tick(hasTimeLeft); this.getProfiler().endTick(); ArrayList<Integer> toRemove = new ArrayList<>(); for (Integer integer : entitiesById.keySet()) if (entitiesById.get(integer).removed) toRemove.add(integer); toRemove.forEach(entitiesById::remove); } @Override public IProfiler getProfiler() { if (this == Minecraft.getInstance().world) return Minecraft.getInstance().getProfiler(); else return profiler.get(); } @Override public Supplier<IProfiler> getWorldProfiler() { if (this == Minecraft.getInstance().world) return () -> Minecraft.getInstance().getProfiler(); else return profiler; } @Override public DynamicRegistries func_241828_r() { return owner == null ? Minecraft.getInstance().world.func_241828_r() : owner.getWorld().func_241828_r(); } public Map<Integer, Entity> getEntitiesById() { return entitiesById; } public boolean containsEntityWithUUID(UUID uuid) { for (Entity value : entitiesById.values()) { if (value.getUniqueID().equals(uuid)) return true; } return false; } @Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } @Override public void playMovingSound(@Nullable PlayerEntity playerIn, Entity entityIn, SoundEvent eventIn, SoundCategory categoryIn, float volume, float pitch) { playSound(playerIn, entityIn.getPositionVec().x, entityIn.getPositionVec().y, entityIn.getPositionVec().z, eventIn, categoryIn, volume, pitch); } @Override public void playSound(double x, double y, double z, SoundEvent soundIn, SoundCategory category, float volume, float pitch, boolean distanceDelay) { this.playSound(null, x, y, z, soundIn, category, volume, pitch); } @Override public void playSound(@Nullable PlayerEntity player, BlockPos pos, SoundEvent soundIn, SoundCategory category, float volume, float pitch) { playSound(player, pos.getX(), pos.getY(), pos.getZ(), soundIn, category, volume, pitch); } @Override public void playSound(@Nullable PlayerEntity player, double x, double y, double z, SoundEvent soundIn, SoundCategory category, float volume, float pitch) { owner.getWorld().playSound(player, owner.getPos().getX() + (x / (float) owner.unitsPerBlock), owner.getPos().getY() + ((y - 64) / (float) owner.unitsPerBlock), owner.getPos().getZ() + (z / (float) owner.unitsPerBlock), soundIn, category, (volume / owner.unitsPerBlock), pitch); } /** * {@link net.minecraft.client.renderer.WorldRenderer#playEvent} */ @Override public void playEvent(@Nullable PlayerEntity player, int type, BlockPos pos, int data) { getBlockState(pos).receiveBlockEvent(this, pos, type, data); this.isRemote = owner.getWorld().isRemote; Random random = rand; // TODO: move this to client world switch (type) { case 1000: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_DISPENSER_DISPENSE, SoundCategory.BLOCKS, 1.0F, 1.2F); break; case 1001: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_DISPENSER_FAIL, SoundCategory.BLOCKS, 1.0F, 1.2F); break; case 1002: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_DISPENSER_LAUNCH, SoundCategory.BLOCKS, 1.0F, 1.2F); break; case 1003: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ENDER_EYE_LAUNCH, SoundCategory.NEUTRAL, 1.0F, 1.2F); break; case 1004: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_FIREWORK_ROCKET_SHOOT, SoundCategory.NEUTRAL, 1.0F, 1.2F); break; case 1005: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_IRON_DOOR_OPEN, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1006: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_WOODEN_DOOR_OPEN, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1007: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_WOODEN_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1008: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_FENCE_GATE_OPEN, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1009: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.BLOCKS, 0.5F, 2.6F + (random.nextFloat() - random.nextFloat()) * 0.8F); break; //TODO:1010 case 1011: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_IRON_DOOR_CLOSE, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1012: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_WOODEN_DOOR_CLOSE, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1013: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_WOODEN_TRAPDOOR_CLOSE, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1014: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_FENCE_GATE_CLOSE, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1015: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_GHAST_WARN, SoundCategory.HOSTILE, 10.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1016: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_GHAST_SHOOT, SoundCategory.HOSTILE, 10.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1017: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ENDER_DRAGON_SHOOT, SoundCategory.HOSTILE, 10.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1018: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_BLAZE_SHOOT, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1019: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1020: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ZOMBIE_ATTACK_IRON_DOOR, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1021: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ZOMBIE_BREAK_WOODEN_DOOR, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1022: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_WITHER_BREAK_BLOCK, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1024: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_WITHER_SHOOT, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1025: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_BAT_TAKEOFF, SoundCategory.NEUTRAL, 0.05F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1026: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ZOMBIE_INFECT, SoundCategory.HOSTILE, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1027: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ZOMBIE_VILLAGER_CONVERTED, SoundCategory.NEUTRAL, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1029: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_ANVIL_DESTROY, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1030: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_ANVIL_USE, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1031: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_ANVIL_LAND, SoundCategory.BLOCKS, 0.3F, this.rand.nextFloat() * 0.1F + 0.9F); break; case 1032: // TODO // this.mc.getSoundHandler().play(SimpleSound.ambientWithoutAttenuation(SoundEvents.BLOCK_PORTAL_TRAVEL, random.nextFloat() * 0.4F + 0.8F, 0.25F)); break; case 1033: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_CHORUS_FLOWER_GROW, SoundCategory.BLOCKS, 1.0F, 1.0F); break; case 1034: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_CHORUS_FLOWER_DEATH, SoundCategory.BLOCKS, 1.0F, 1.0F); break; case 1035: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_BREWING_STAND_BREW, SoundCategory.BLOCKS, 1.0F, 1.0F); break; case 1036: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_IRON_TRAPDOOR_CLOSE, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1037: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 1.0F, random.nextFloat() * 0.1F + 0.9F); break; case 1039: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_PHANTOM_BITE, SoundCategory.HOSTILE, 0.3F, this.rand.nextFloat() * 0.1F + 0.9F); break; case 1040: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_ZOMBIE_CONVERTED_TO_DROWNED, SoundCategory.NEUTRAL, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1041: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ENTITY_HUSK_CONVERTED_TO_ZOMBIE, SoundCategory.NEUTRAL, 2.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); break; case 1042: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_GRINDSTONE_USE, SoundCategory.BLOCKS, 1.0F, this.rand.nextFloat() * 0.1F + 0.9F); break; case 1043: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.ITEM_BOOK_PAGE_TURN, SoundCategory.BLOCKS, 1.0F, this.rand.nextFloat() * 0.1F + 0.9F); break; case 1044: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_SMITHING_TABLE_USE, SoundCategory.BLOCKS, 1.0F, this.rand.nextFloat() * 0.1F + 0.9F); break; case 1500: ComposterBlock.playEvent(this, pos, data > 0); break; case 1502: this.playSound(Minecraft.getInstance().player, pos, SoundEvents.BLOCK_REDSTONE_TORCH_BURNOUT, SoundCategory.BLOCKS, 0.5F, 2.6F + (random.nextFloat() - random.nextFloat()) * 0.8F); for (int l1 = 0; l1 < 5; ++l1) { double d15 = (double) pos.getX() + random.nextDouble() * 0.6D + 0.2D; double d20 = (double) pos.getY() + random.nextDouble() * 0.6D + 0.2D; double d26 = (double) pos.getZ() + random.nextDouble() * 0.6D + 0.2D; this.addParticle(ParticleTypes.SMOKE, d15, d20, d26, 0.0D, 0.0D, 0.0D); } break; case 2001: BlockState state = Block.getStateById(data); if (!state.isAir(this, pos)) { SoundType soundtype = state.getSoundType(this, pos, null); this.playSound(pos, soundtype.getBreakSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F, false); } if (!state.isAir(this, pos) && !state.addDestroyEffects(this, pos, Minecraft.getInstance().particles)) { VoxelShape voxelshape = state.getShape(this, pos); voxelshape.forEachBox((x1, y1, z1, x2, y2, z2) -> { double d1 = Math.min(1.0D, x2 - x1); double d2 = Math.min(1.0D, y2 - y1); double d3 = Math.min(1.0D, z2 - z1); int i = Math.max(2, MathHelper.ceil(d1 / 0.25D)); int j = Math.max(2, MathHelper.ceil(d2 / 0.25D)); int k = Math.max(2, MathHelper.ceil(d3 / 0.25D)); for (int l = 0; l < i; ++l) { for (int i1 = 0; i1 < j; ++i1) { for (int j1 = 0; j1 < k; ++j1) { double d4 = ((double) l + 0.5D) / (double) i; double d5 = ((double) i1 + 0.5D) / (double) j; double d6 = ((double) j1 + 0.5D) / (double) k; double d7 = d4 * d1 + x1; double d8 = d5 * d2 + y1; double d9 = d6 * d3 + z1; Minecraft.getInstance().particles.addEffect( (new DiggingParticle((ClientWorld) owner.getWorld(), (((double) pos.getX() + d7) / owner.unitsPerBlock) + owner.getPos().getX(), (((double) pos.getY() + d8 - 64) / owner.unitsPerBlock) + owner.getPos().getY(), (((double) pos.getZ() + d9) / owner.unitsPerBlock) + owner.getPos().getZ(), (d4 - 0.5D), (d5 - 0.5D), (d6 - 0.5D), state )).setBlockPos(pos) .multiplyVelocity((1f / owner.unitsPerBlock) * 1.5f) .multiplyParticleScaleBy(1f / owner.unitsPerBlock) ); } } } }); } break; //TODO: everything else // case 2000: // Direction direction = Direction.byIndex(data); // int j1 = direction.getXOffset(); // int j2 = direction.getYOffset(); // int k2 = direction.getZOffset(); // double d18 = (double) pos.getX() + (double) j1 * 0.6D + 0.5D; // double d24 = (double) pos.getY() + (double) j2 * 0.6D + 0.5D; // double d28 = (double) pos.getZ() + (double) k2 * 0.6D + 0.5D; // // for (int i3 = 0; i3 < 10; ++i3) { // double d4 = random.nextDouble() * 0.2D + 0.01D; // double d6 = d18 + (double) j1 * 0.01D + (random.nextDouble() - 0.5D) * (double) k2 * 0.5D; // double d8 = d24 + (double) j2 * 0.01D + (random.nextDouble() - 0.5D) * (double) j2 * 0.5D; // double d30 = d28 + (double) k2 * 0.01D + (random.nextDouble() - 0.5D) * (double) j1 * 0.5D; // double d9 = (double) j1 * d4 + random.nextGaussian() * 0.01D; // double d10 = (double) j2 * d4 + random.nextGaussian() * 0.01D; // double d11 = (double) k2 * d4 + random.nextGaussian() * 0.01D; // if (!isRemote) { // spawnParticle(ParticleTypes.SMOKE, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 2, 0, 0, 0, 0); // } else { // this.addOptionalParticle(ParticleTypes.SMOKE, d6, d8, d30, d9, d10, d11); // } // } // break; //TODO: everything else else default: // if (!isRemote) { // owner.getWorld().getServer().getPlayerList() // .sendToAllNearExcept( // player, // (double) owner.getPos().getX() + (pos.getX() / (float) owner.unitsPerBlock), // (double) owner.getPos().getY() + (((pos.getY() - 64)) / (float) owner.unitsPerBlock), // (double) owner.getPos().getZ() + (pos.getZ() / (float) owner.unitsPerBlock), // (64.0D), owner.getWorld().getDimensionKey(), // new SPlaySoundEventPacket(type, owner.getPos(), data, false) // ); // } else { // owner.getWorld().playEvent(player, type, owner.getPos(), data); // } } } @Nullable @Override public TileEntity getTileEntity(BlockPos pos) { ExternalUnitInteractionContext context = new ExternalUnitInteractionContext(this, pos); if (context.posInRealWorld != null) { if (context.stateInRealWorld != null) { if (context.stateInRealWorld.equals(Deferred.UNIT.get().getDefaultState())) { if (!context.posInRealWorld.equals(this.owner.getPos())) { if (context.teInRealWorld != null) { if (context.teInRealWorld instanceof UnitTileEntity) { if (((UnitTileEntity) context.teInRealWorld).getFakeWorld() != null) { return ((UnitTileEntity) context.teInRealWorld).getFakeWorld().getTileEntity(context.posInFakeWorld); } } } } } else { for (Direction value : Direction.values()) { if (context.posInRealWorld.equals(owner.getPos().offset(value))) { if (!(context.teInRealWorld instanceof UnitTileEntity)) { return owner.getWorld().getTileEntity(context.posInRealWorld); } } } } } } // for (TileEntity tileEntityChange : tileEntitiesToBeRemoved) { // if (tileEntityChange.equals(blockMap.getOrDefault(pos.toLong(), new SmallUnit(pos, Blocks.AIR.getDefaultState())).tileEntity)) { // return null; // } // } // boolean containsTE = false; if (removedTileEntities.contains(pos)) return null; for (TileEntity tileEntity : loadedTileEntityList) { if (tileEntity.getPos().equals(pos)) { TileEntity te = blockMap.getOrDefault(pos.toLong(), new SmallUnit(SmallerUnitsAPI.createPos(pos, owner), Blocks.AIR.getDefaultState())).tileEntity; return te; // containsTE = true; } } return null; } @Override public void removeTileEntity(BlockPos pos) { removedTileEntities.add(pos); super.removeTileEntity(pos); } @Override public boolean setBlockState(BlockPos pos, BlockState state, int flags, int recursionLeft) { ExternalUnitInteractionContext context = new ExternalUnitInteractionContext(this, pos); if (recursionLeft < 0) return false; if (context.posInRealWorld != null) { if (context.stateInRealWorld != null) { if (!context.posInRealWorld.equals(owner.getPos())) { if (context.stateInRealWorld.equals(Deferred.UNIT.get().getDefaultState())) { if (!context.posInRealWorld.equals(this.owner.getPos())) { if (((UnitTileEntity) context.teInRealWorld).getFakeWorld() != null) { ((UnitTileEntity) context.teInRealWorld).needsRefresh(true); return ((UnitTileEntity) context.teInRealWorld).getFakeWorld().setBlockState(context.posInFakeWorld, state, flags, recursionLeft - 1); } } return false; } else if (context.stateInRealWorld.isAir(owner.getWorld(), context.posInRealWorld)) { // owner.getWorld().setBlockState(context.posInRealWorld, Deferred.UNIT.get().getDefaultState()); // UnitTileEntity tileEntity = new UnitTileEntity(); // owner.getWorld().setTileEntity(context.posInRealWorld, tileEntity); // tileEntity.unitsPerBlock = this.owner.unitsPerBlock; } else { return false; } } } } if (World.isOutsideBuildHeight(context.posInRealWorld)) { return false; } owner.markDirty(); owner.needsRefresh(true); owner.getWorld().notifyBlockUpdate(owner.getPos(), owner.getBlockState(), owner.getBlockState(), 3); { IChunk chunk = getChunk(0, 0); pos = pos.toImmutable(); // Forge - prevent mutable BlockPos leaks net.minecraftforge.common.util.BlockSnapshot blockSnapshot = null; if (this.captureBlockSnapshots && !this.isRemote) { blockSnapshot = net.minecraftforge.common.util.BlockSnapshot.create(this.dimension, this, pos, flags); this.capturedBlockSnapshots.add(blockSnapshot); } BlockState old = getBlockState(pos); int oldLight = old.getLightValue(this, pos); int oldOpacity = old.getOpacity(this, pos); BlockState blockstate = chunk.setBlockState(pos, state, (flags & 64) != 0); if (blockstate == null) { if (blockSnapshot != null) this.capturedBlockSnapshots.remove(blockSnapshot); return false; } else { BlockState blockstate1 = this.getBlockState(pos); if ((flags & 128) == 0 && blockstate1 != blockstate && (blockstate1.getOpacity(this, pos) != oldOpacity || blockstate1.getLightValue(this, pos) != oldLight || blockstate1.isTransparent() || blockstate.isTransparent())) { this.getProfiler().startSection("queueCheckLight"); // lightManager.checkBlock(pos); this.getProfiler().endSection(); } if (!state.getFluidState().isEmpty()) { if (state.getFluidState().getBlockState().equals(state.getBlockState())) { Fluid fluid = state.getFluidState().getFluid(); // for (Direction dir : Direction.values()) { // this.getBlockState(pos.offset(dir)).neighborChanged(this, pos.offset(dir), state.getBlock(), pos, false); // } getPendingFluidTicks().scheduleTick(pos, fluid, fluid.getTickRate(this)); } } // if (state.getBlockState().equals(state.getFluidState().getBlockState())) { if (old.getBlock() != state.getBlock()) { try { // state.onBlockAdded(this, pos, old, false); // super.setBlockState(pos, state, flags); //TODO: figure out why LootContext$Builder throws null pointers } catch (NullPointerException ignored) { } { BlockState statePlace = state; UnitTileEntity tileEntity = owner; if (statePlace.getBlock() instanceof ITileEntityProvider) { TileEntity te = ((ITileEntityProvider) statePlace.getBlock()).createNewTileEntity(tileEntity.getFakeWorld()); tileEntity.getFakeWorld().setTileEntity(pos, te); } else if (statePlace.getBlock().hasTileEntity(statePlace)) { TileEntity te = statePlace.getBlock().createTileEntity(statePlace, tileEntity.getFakeWorld()); tileEntity.getFakeWorld().setTileEntity(pos, te); } } } // } if (this.getTileEntity(pos) != null) this.getTileEntity(pos).markDirty(); this.markAndNotifyBlock(pos, chunk, blockstate, state, flags, recursionLeft); if (state.equals(Blocks.AIR.getDefaultState())) { try { if (this.getTileEntity(pos) != null) this.getTileEntity(pos).remove(); } catch (Throwable ignored) { } // this.blockMap.remove(pos.toLong()); } try { int newLight = state.getLightValue(this, pos); lightManager.blockLight.storage.updateSourceLevel(pos.toLong(), newLight, oldLight > newLight); } catch (Throwable ignored) { } return true; } } } public void markAndNotifyBlock(BlockPos pos, @Nullable IChunk chunk, BlockState blockstate, BlockState state, int flags, int recursionLeft) { Block block = state.getBlock(); BlockState blockstate1 = getBlockState(pos); { { if (blockstate1 == state) { if (blockstate != blockstate1) { this.markBlockRangeForRenderUpdate(pos, blockstate, blockstate1); } if ((flags & 2) != 0 && (!this.isRemote || (flags & 4) == 0) && (this.isRemote)) { this.notifyBlockUpdate(pos, blockstate, state, flags); } if ((flags & 1) != 0) { this.func_230547_a_(pos, blockstate.getBlock()); if (!this.isRemote && state.hasComparatorInputOverride()) { this.updateComparatorOutputLevel(pos, block); } } if ((flags & 16) == 0 && recursionLeft > 0) { int i = flags & -34; blockstate.updateDiagonalNeighbors(this, pos, i, recursionLeft - 1); state.updateNeighbours(this, pos, i, recursionLeft - 1); state.updateDiagonalNeighbors(this, pos, i, recursionLeft - 1); this.notifyNeighborsOfStateChange(pos, blockstate.getBlock()); for (Direction value : Direction.values()) { BlockPos pos1 = pos.offset(value); BlockState state1 = this.getBlockState(pos1); ExternalUnitInteractionContext context = new ExternalUnitInteractionContext(this, pos1); if (context.teInRealWorld instanceof UnitTileEntity) { state1.updatePostPlacement(value.getOpposite(), state, ((UnitTileEntity) context.teInRealWorld).getFakeWorld(), pos1, pos); } } } this.onBlockStateChange(pos, blockstate, blockstate1); } } } } }
41.974773
279
0.701397
2ba9c8085569160ce40625f01f015339c0e5c0d5
194,612
package eu.isas.peptideshaker.gui.tabpanels; import com.compomics.util.gui.file_handling.FileAndFileFilter; import com.compomics.util.Util; import com.compomics.util.examples.BareBonesBrowserLaunch; import com.compomics.util.experiment.biology.proteins.Peptide; import com.compomics.util.experiment.identification.Identification; import static com.compomics.util.experiment.personalization.ExperimentObject.NO_KEY; import com.compomics.util.experiment.identification.matches.PeptideMatch; import com.compomics.util.experiment.identification.matches.ProteinMatch; import com.compomics.util.experiment.identification.matches.SpectrumMatch; import com.compomics.util.experiment.io.biology.protein.SequenceProvider; import com.compomics.util.experiment.quantification.spectrumcounting.SpectrumCountingMethod; import com.compomics.util.gui.genes.GeneDetailsDialog; import com.compomics.util.gui.GuiUtilities; import com.compomics.util.gui.TableProperties; import com.compomics.util.gui.XYPlottingDialog; import com.compomics.util.gui.error_handlers.HelpDialog; import com.compomics.util.gui.waiting.waitinghandlers.ProgressDialogX; import com.compomics.util.pdbfinder.FindPdbForUniprotAccessions; import com.compomics.util.pdbfinder.pdb.PdbBlock; import com.compomics.util.pdbfinder.pdb.PdbParameter; import com.compomics.util.gui.export.graphics.ExportGraphicsDialog; import com.compomics.util.gui.tablemodels.SelfUpdatingTableModel; import com.compomics.util.parameters.identification.IdentificationParameters; import com.compomics.util.parameters.identification.advanced.SequenceMatchingParameters; import com.compomics.util.parameters.identification.search.ModificationParameters; import eu.isas.peptideshaker.gui.PeptideShakerGUI; import eu.isas.peptideshaker.gui.protein_inference.ProteinInferenceDialog; import eu.isas.peptideshaker.gui.protein_inference.ProteinInferencePeptideLevelDialog; import eu.isas.peptideshaker.gui.tablemodels.ProteinTableModel; import com.compomics.util.experiment.identification.peptide_shaker.PSParameter; import eu.isas.peptideshaker.preferences.DisplayParameters; import com.compomics.util.experiment.identification.validation.MatchValidationLevel; import com.compomics.util.experiment.identification.features.IdentificationFeaturesGenerator; import com.compomics.util.gui.file_handling.FileChooserUtil; import com.compomics.util.io.export.ExportFeature; import com.compomics.util.io.export.ExportFormat; import com.compomics.util.io.export.ExportScheme; import com.compomics.util.io.flat.SimpleFileWriter; import eu.isas.peptideshaker.export.PSExportFactory; import com.compomics.util.io.export.features.peptideshaker.PsPeptideFeature; import com.compomics.util.io.export.features.peptideshaker.PsProteinFeature; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import no.uib.jsparklines.data.StartIndexes; import no.uib.jsparklines.data.XYDataPoint; import no.uib.jsparklines.extra.HtmlLinksRenderer; import no.uib.jsparklines.extra.TrueFalseIconRenderer; import no.uib.jsparklines.renderers.JSparklinesArrayListBarChartTableCellRenderer; import no.uib.jsparklines.renderers.JSparklinesBarChartTableCellRenderer; import no.uib.jsparklines.renderers.JSparklinesIntegerColorTableCellRenderer; import no.uib.jsparklines.renderers.JSparklinesIntegerIconTableCellRenderer; import no.uib.jsparklines.renderers.JSparklinesIntervalChartTableCellRenderer; import no.uib.jsparklines.renderers.JSparklinesMultiIntervalChartTableCellRenderer; import org.jfree.chart.plot.PlotOrientation; import org.jmol.adapter.smarter.SmarterJmolAdapter; import org.jmol.api.JmolAdapter; import org.jmol.api.JmolViewer; /** * The Protein Structure tab. * * @author Harald Barsnes * @author Yehia Farag */ public class ProteinStructurePanel extends javax.swing.JPanel { /** * Peptide keys that can be mapped to the current PDB file. */ private ArrayList<Long> peptidePdbArray; /** * Indexes for the three main data tables. */ private enum TableIndex { PROTEIN_TABLE, PEPTIDE_TABLE, PDB_MATCHES, PDB_CHAINS }; /** * If true, labels are shown for the modifications in the 3D structure. */ private boolean showModificationLabels = true; /** * If true, the 3D model will be spinning. */ private boolean spinModel = true; /** * If true, the ribbon model is used. */ private boolean ribbonModel = true; /** * If true, the backbone model is used. */ private boolean backboneModel = false; /** * The currently displayed PDB file. */ private String currentlyDisplayedPdbFile; /** * A simple progress dialog. */ private ProgressDialogX progressDialog; /** * The UniProt to PDB finder. */ private FindPdbForUniprotAccessions uniProtPdb; /** * The PeptideShaker main frame. */ private final PeptideShakerGUI peptideShakerGUI; /** * The Jmol panel. */ private JmolPanel jmolPanel; /** * The protein table column header tooltips. */ private ArrayList<String> proteinTableToolTips; /** * The peptide table column header tooltips. */ private ArrayList<String> peptideTableToolTips; /** * The PDB files table column header tooltips. */ private ArrayList<String> pdbTableToolTips; /** * The PDB chains table column header tooltips. */ private ArrayList<String> pdbChainsTableToolTips; /** * A mapping of the peptide table entries. */ private HashMap<Integer, Long> peptideTableMap = new HashMap<>(); /** * If true, Jmol is currently displaying a structure. */ private boolean jmolStructureShown = false; /** * The current PDB chains. */ private PdbBlock[] chains; /** * The amino acid sequence of the current chain. */ private String chainSequence; /** * A list of proteins in the protein table. */ private long[] proteinKeys = new long[0]; /** * Creates a new ProteinPanel. * * @param peptideShakerGUI the PeptideShaker main frame */ public ProteinStructurePanel(PeptideShakerGUI peptideShakerGUI) { initComponents(); this.peptideShakerGUI = peptideShakerGUI; jmolPanel = new JmolPanel(); pdbPanel.add(jmolPanel); setUpTableHeaderToolTips(); setUpGUI(); } /** * Set up the GUI. */ private void setUpGUI() { proteinScrollPane.getViewport().setOpaque(false); peptideScrollPane.getViewport().setOpaque(false); pdbJScrollPane.getViewport().setOpaque(false); pdbChainsJScrollPane.getViewport().setOpaque(false); SelfUpdatingTableModel.addSortListener( proteinTable, new ProgressDialogX(peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true) ); proteinTable.getTableHeader().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { proteinTableMouseClicked(e); } }); // add scrolling listeners SelfUpdatingTableModel.addScrollListeners( proteinTable, proteinScrollPane, proteinScrollPane.getVerticalScrollBar() ); peptideTable.setAutoCreateRowSorter(true); setTableProperties(); } /** * Set up the table header tooltips. */ private void setUpTableHeaderToolTips() { proteinTableToolTips = new ArrayList<>(13); proteinTableToolTips.add(null); proteinTableToolTips.add("Starred"); proteinTableToolTips.add("Protein Inference Class"); proteinTableToolTips.add("Protein Accession Number"); proteinTableToolTips.add("Protein Description"); proteinTableToolTips.add("Chromosome Number"); proteinTableToolTips.add("Protein Sequence Coverage (%) (Confident / Doubtful / Not Validated / Possible)"); proteinTableToolTips.add("Number of Peptides (Validated / Doubtful / Not Validated)"); proteinTableToolTips.add("Number of Spectra (Validated / Doubtful / Not Validated)"); proteinTableToolTips.add("MS2 Quantification"); proteinTableToolTips.add("Protein Molecular Weight (kDa)"); if (peptideShakerGUI.getDisplayParameters().showScores()) { proteinTableToolTips.add("Protein Score"); } else { proteinTableToolTips.add("Protein Confidence"); } proteinTableToolTips.add("Validated"); peptideTableToolTips = new ArrayList<>(7); peptideTableToolTips.add(null); peptideTableToolTips.add("Starred"); peptideTableToolTips.add("Protein Inference"); peptideTableToolTips.add("Peptide Sequence"); peptideTableToolTips.add("Peptide Start Index"); peptideTableToolTips.add("In PDB Sequence"); peptideTableToolTips.add("Validated"); pdbTableToolTips = new ArrayList<>(5); pdbTableToolTips.add(null); pdbTableToolTips.add("PDB Accession Number"); pdbTableToolTips.add("PDB Title"); pdbTableToolTips.add("Type of Structure"); pdbTableToolTips.add("Number of Chains"); pdbChainsTableToolTips = new ArrayList<>(4); pdbChainsTableToolTips.add(null); pdbChainsTableToolTips.add("Chain Label"); pdbChainsTableToolTips.add("Protein-PDB Alignment"); pdbChainsTableToolTips.add("Protein Coverage for PDB Sequence"); // correct the color for the upper right corner JPanel proteinCorner = new JPanel(); proteinCorner.setBackground(proteinTable.getTableHeader().getBackground()); proteinScrollPane.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, proteinCorner); JPanel peptideCorner = new JPanel(); peptideCorner.setBackground(peptideTable.getTableHeader().getBackground()); peptideScrollPane.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, peptideCorner); JPanel pdbMatchesCorner = new JPanel(); pdbMatchesCorner.setBackground(pdbMatchesJTable.getTableHeader().getBackground()); pdbJScrollPane.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, pdbMatchesCorner); JPanel pdbChainsCorner = new JPanel(); pdbChainsCorner.setBackground(pdbChainsJTable.getTableHeader().getBackground()); pdbChainsJScrollPane.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, pdbChainsCorner); } /** * Set up the properties of the tables. */ private void setTableProperties() { setProteinTableProperties(); setPeptideTableProperties(); setPdbTablesProperties(); } /** * Set up the properties of the protein table. */ private void setProteinTableProperties() { Integer maxProteinKeyLength = null; if (peptideShakerGUI.getMetrics() != null) { maxProteinKeyLength = peptideShakerGUI.getMetrics().getMaxProteinAccessionLength(); } ProteinTableModel.setProteinTableProperties( proteinTable, peptideShakerGUI.getSparklineColor(), peptideShakerGUI.getSparklineColorNonValidated(), peptideShakerGUI.getSparklineColorNotFound(), peptideShakerGUI.getUtilitiesUserParameters().getSparklineColorDoubtful(), peptideShakerGUI.getScoreAndConfidenceDecimalFormat(), this.getClass(), maxProteinKeyLength ); proteinTable.getModel().addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { reselect(); } }); } }); } /** * Set up the properties of the peptide table. */ private void setPeptideTableProperties() { peptideTable.getColumn(" ").setMaxWidth(50); peptideTable.getColumn(" ").setMinWidth(50); peptideTable.getColumn("PDB").setMinWidth(50); peptideTable.getColumn("PDB").setMaxWidth(50); peptideTable.getColumn("Start").setMinWidth(50); // the validated column peptideTable.getColumn("").setMaxWidth(30); peptideTable.getColumn("").setMinWidth(30); // the selected columns peptideTable.getColumn(" ").setMaxWidth(30); peptideTable.getColumn(" ").setMinWidth(30); // the protein inference column peptideTable.getColumn("PI").setMaxWidth(37); peptideTable.getColumn("PI").setMinWidth(37); peptideTable.getTableHeader().setReorderingAllowed(false); // set up the peptide inference color map HashMap<Integer, Color> peptideInferenceColorMap = new HashMap<>(); peptideInferenceColorMap.put(PSParameter.NOT_GROUP, peptideShakerGUI.getSparklineColor()); peptideInferenceColorMap.put(PSParameter.RELATED, Color.YELLOW); peptideInferenceColorMap.put(PSParameter.RELATED_AND_UNRELATED, Color.ORANGE); peptideInferenceColorMap.put(PSParameter.UNRELATED, Color.RED); // set up the peptide inference tooltip map HashMap<Integer, String> peptideInferenceTooltipMap = new HashMap<>(); peptideInferenceTooltipMap.put(PSParameter.NOT_GROUP, "Unique to a single protein"); peptideInferenceTooltipMap.put(PSParameter.RELATED, "Belongs to a group of related proteins"); peptideInferenceTooltipMap.put(PSParameter.RELATED_AND_UNRELATED, "Belongs to a group of related and unrelated proteins"); peptideInferenceTooltipMap.put(PSParameter.UNRELATED, "Belongs to unrelated proteins"); peptideTable.getColumn("PI").setCellRenderer( new JSparklinesIntegerColorTableCellRenderer( peptideShakerGUI.getSparklineColor(), peptideInferenceColorMap, peptideInferenceTooltipMap ) ); peptideTable.getColumn("Start").setCellRenderer( new JSparklinesMultiIntervalChartTableCellRenderer( PlotOrientation.HORIZONTAL, 100d, 100d, peptideShakerGUI.getSparklineColor() ) ); peptideTable.getColumn("PDB").setCellRenderer( new TrueFalseIconRenderer( new ImageIcon(this.getClass().getResource("/icons/pdb.png")), null, "Mapped to PDB Structure", null ) ); peptideTable.getColumn("").setCellRenderer( new JSparklinesIntegerIconTableCellRenderer( MatchValidationLevel.getIconMap( this.getClass()), MatchValidationLevel.getTooltipMap() ) ); peptideTable.getColumn(" ").setCellRenderer( new TrueFalseIconRenderer( new ImageIcon(this.getClass().getResource("/icons/star_yellow.png")), new ImageIcon(this.getClass().getResource("/icons/star_grey.png")), new ImageIcon(this.getClass().getResource("/icons/star_grey.png")), "Starred", null, null ) ); } /** * Set up the properties of the PDB and PDB chains tables. */ private void setPdbTablesProperties() { pdbMatchesJTable.getColumn(" ").setMaxWidth(50); pdbChainsJTable.getColumn(" ").setMaxWidth(50); pdbMatchesJTable.getColumn("PDB").setMaxWidth(50); pdbChainsJTable.getColumn("Chain").setMaxWidth(50); pdbMatchesJTable.getColumn(" ").setMinWidth(50); pdbChainsJTable.getColumn(" ").setMinWidth(50); pdbMatchesJTable.getColumn("PDB").setMinWidth(50); pdbChainsJTable.getColumn("Chain").setMinWidth(50); pdbMatchesJTable.getColumn("Chains").setMinWidth(100); pdbMatchesJTable.getColumn("Chains").setMaxWidth(100); pdbMatchesJTable.getTableHeader().setReorderingAllowed(false); pdbChainsJTable.getTableHeader().setReorderingAllowed(false); pdbChainsJTable.setAutoCreateRowSorter(true); pdbMatchesJTable.setAutoCreateRowSorter(true); pdbMatchesJTable.getColumn("PDB").setCellRenderer( new HtmlLinksRenderer( TableProperties.getSelectedRowHtmlTagFontColor(), TableProperties.getNotSelectedRowHtmlTagFontColor() ) ); pdbMatchesJTable.getColumn("Chains").setCellRenderer( new JSparklinesBarChartTableCellRenderer( PlotOrientation.HORIZONTAL, 10.0, peptideShakerGUI.getSparklineColor() ) ); ((JSparklinesBarChartTableCellRenderer) pdbMatchesJTable.getColumn("Chains").getCellRenderer()).showNumberAndChart(true, TableProperties.getLabelWidth()); pdbChainsJTable.getColumn("Coverage").setCellRenderer( new JSparklinesBarChartTableCellRenderer( PlotOrientation.HORIZONTAL, 100.0, peptideShakerGUI.getSparklineColor() ) ); ((JSparklinesBarChartTableCellRenderer) pdbChainsJTable.getColumn("Coverage").getCellRenderer()).showNumberAndChart(true, TableProperties.getLabelWidth()); pdbChainsJTable.getColumn("PDB-Protein").setCellRenderer( new JSparklinesIntervalChartTableCellRenderer( PlotOrientation.HORIZONTAL, 100.0, 10.0, peptideShakerGUI.getSparklineColor() ) ); ((JSparklinesIntervalChartTableCellRenderer) pdbChainsJTable.getColumn("PDB-Protein").getCellRenderer()).showReferenceLine(true, 0.02, Color.BLACK); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pdbStructureJPanel = new javax.swing.JPanel(); pdbStructureLayeredPane = new javax.swing.JLayeredPane(); pdbOuterPanel = new javax.swing.JPanel(); pdbLayeredPane = new javax.swing.JLayeredPane(); pdbPanel = new javax.swing.JPanel(); labelsJButton = new javax.swing.JButton(); ribbonJButton = new javax.swing.JButton(); backboneJButton = new javax.swing.JButton(); playJButton = new javax.swing.JButton(); pdbStructureHelpJButton = new javax.swing.JButton(); exportPdbStructureJButton = new javax.swing.JButton(); contextMenuPdbStructureBackgroundPanel = new javax.swing.JPanel(); proteinsJPanel = new javax.swing.JPanel(); proteinsLayeredPane = new javax.swing.JLayeredPane(); proteinsPanel = new javax.swing.JPanel(); proteinScrollPane = new javax.swing.JScrollPane(); proteinTable = new JTable() { protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); String tip = (String) proteinTableToolTips.get(realIndex); return tip; } }; } }; proteinsHelpJButton = new javax.swing.JButton(); exportProteinsJButton = new javax.swing.JButton(); contextMenuProteinsBackgroundPanel = new javax.swing.JPanel(); peptidesJPanel = new javax.swing.JPanel(); peptidesLayeredPane = new javax.swing.JLayeredPane(); peptidesPanel = new javax.swing.JPanel(); peptideScrollPane = new javax.swing.JScrollPane(); peptideTable = new JTable() { protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); String tip = (String) peptideTableToolTips.get(realIndex); return tip; } }; } }; peptidesHelpJButton = new javax.swing.JButton(); exportPeptidesJButton = new javax.swing.JButton(); contextMenuPeptidesBackgroundPanel = new javax.swing.JPanel(); pdbMatchesJPanel = new javax.swing.JPanel(); pdbMatchesLayeredPane = new javax.swing.JLayeredPane(); pdbMatchesPanel = new javax.swing.JPanel(); pdbJScrollPane = new javax.swing.JScrollPane(); pdbMatchesJTable = new JTable() { protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); String tip = (String) pdbTableToolTips.get(realIndex); return tip; } }; } }; pdbMatchesHelpJButton = new javax.swing.JButton(); exportPdbMatchesJButton = new javax.swing.JButton(); contextMenuPdbMatchesBackgroundPanel = new javax.swing.JPanel(); pdbChainsJPanel = new javax.swing.JPanel(); pdbChainsLayeredPane = new javax.swing.JLayeredPane(); pdbChainsPanel = new javax.swing.JPanel(); pdbChainsJScrollPane = new javax.swing.JScrollPane(); pdbChainsJTable = new JTable() { protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); String tip = (String) pdbChainsTableToolTips.get(realIndex); return tip; } }; } }; pdbChainHelpJButton = new javax.swing.JButton(); exportPdbChainsJButton = new javax.swing.JButton(); contextMenuPdbChainsBackgroundPanel = new javax.swing.JPanel(); setBackground(new java.awt.Color(255, 255, 255)); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); pdbStructureJPanel.setOpaque(false); pdbOuterPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("PDB Structure")); pdbOuterPanel.setOpaque(false); pdbLayeredPane.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { pdbLayeredPaneComponentResized(evt); } }); pdbPanel.setLayout(new javax.swing.BoxLayout(pdbPanel, javax.swing.BoxLayout.LINE_AXIS)); pdbPanel.setBounds(0, 0, 435, 440); pdbLayeredPane.add(pdbPanel, javax.swing.JLayeredPane.DEFAULT_LAYER); labelsJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/labels_selected.png"))); // NOI18N labelsJButton.setToolTipText("Hide Modification Labels"); labelsJButton.setBorder(null); labelsJButton.setBorderPainted(false); labelsJButton.setContentAreaFilled(false); labelsJButton.setFocusable(false); labelsJButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); labelsJButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); labelsJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { labelsJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { labelsJButtonMouseExited(evt); } }); labelsJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { labelsJButtonActionPerformed(evt); } }); labelsJButton.setBounds(0, 0, 25, 25); pdbLayeredPane.add(labelsJButton, javax.swing.JLayeredPane.POPUP_LAYER); ribbonJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ribbon_selected.png"))); // NOI18N ribbonJButton.setToolTipText("Ribbon Model"); ribbonJButton.setBorder(null); ribbonJButton.setBorderPainted(false); ribbonJButton.setContentAreaFilled(false); ribbonJButton.setFocusable(false); ribbonJButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); ribbonJButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); ribbonJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { ribbonJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { ribbonJButtonMouseExited(evt); } }); ribbonJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ribbonJButtonActionPerformed(evt); } }); ribbonJButton.setBounds(0, 0, 25, 25); pdbLayeredPane.add(ribbonJButton, javax.swing.JLayeredPane.POPUP_LAYER); backboneJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/backbone.png"))); // NOI18N backboneJButton.setToolTipText("Backbone Model"); backboneJButton.setBorder(null); backboneJButton.setBorderPainted(false); backboneJButton.setContentAreaFilled(false); backboneJButton.setFocusable(false); backboneJButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); backboneJButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); backboneJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { backboneJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { backboneJButtonMouseExited(evt); } }); backboneJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backboneJButtonActionPerformed(evt); } }); backboneJButton.setBounds(0, 0, 25, 25); pdbLayeredPane.add(backboneJButton, javax.swing.JLayeredPane.POPUP_LAYER); playJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/pause.png"))); // NOI18N playJButton.setToolTipText("Stop Rotation"); playJButton.setBorder(null); playJButton.setBorderPainted(false); playJButton.setContentAreaFilled(false); playJButton.setFocusable(false); playJButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); playJButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); playJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { playJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { playJButtonMouseExited(evt); } }); playJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { playJButtonActionPerformed(evt); } }); playJButton.setBounds(0, 0, 21, 21); pdbLayeredPane.add(playJButton, javax.swing.JLayeredPane.POPUP_LAYER); javax.swing.GroupLayout pdbOuterPanelLayout = new javax.swing.GroupLayout(pdbOuterPanel); pdbOuterPanel.setLayout(pdbOuterPanelLayout); pdbOuterPanelLayout.setHorizontalGroup( pdbOuterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 448, Short.MAX_VALUE) .addGroup(pdbOuterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pdbOuterPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(pdbLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE) .addContainerGap())) ); pdbOuterPanelLayout.setVerticalGroup( pdbOuterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 463, Short.MAX_VALUE) .addGroup(pdbOuterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pdbOuterPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(pdbLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE) .addContainerGap())) ); pdbOuterPanel.setBounds(0, 0, 460, 490); pdbStructureLayeredPane.add(pdbOuterPanel, javax.swing.JLayeredPane.DEFAULT_LAYER); pdbStructureHelpJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame_grey.png"))); // NOI18N pdbStructureHelpJButton.setToolTipText("Help"); pdbStructureHelpJButton.setBorder(null); pdbStructureHelpJButton.setBorderPainted(false); pdbStructureHelpJButton.setContentAreaFilled(false); pdbStructureHelpJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame.png"))); // NOI18N pdbStructureHelpJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { pdbStructureHelpJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { pdbStructureHelpJButtonMouseExited(evt); } }); pdbStructureHelpJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pdbStructureHelpJButtonActionPerformed(evt); } }); pdbStructureHelpJButton.setBounds(440, 0, 10, 19); pdbStructureLayeredPane.add(pdbStructureHelpJButton, javax.swing.JLayeredPane.POPUP_LAYER); exportPdbStructureJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPdbStructureJButton.setToolTipText("Export"); exportPdbStructureJButton.setBorder(null); exportPdbStructureJButton.setBorderPainted(false); exportPdbStructureJButton.setContentAreaFilled(false); exportPdbStructureJButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPdbStructureJButton.setEnabled(false); exportPdbStructureJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame.png"))); // NOI18N exportPdbStructureJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { exportPdbStructureJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { exportPdbStructureJButtonMouseExited(evt); } }); exportPdbStructureJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportPdbStructureJButtonActionPerformed(evt); } }); exportPdbStructureJButton.setBounds(430, 0, 10, 19); pdbStructureLayeredPane.add(exportPdbStructureJButton, javax.swing.JLayeredPane.POPUP_LAYER); contextMenuPdbStructureBackgroundPanel.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout contextMenuPdbStructureBackgroundPanelLayout = new javax.swing.GroupLayout(contextMenuPdbStructureBackgroundPanel); contextMenuPdbStructureBackgroundPanel.setLayout(contextMenuPdbStructureBackgroundPanelLayout); contextMenuPdbStructureBackgroundPanelLayout.setHorizontalGroup( contextMenuPdbStructureBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); contextMenuPdbStructureBackgroundPanelLayout.setVerticalGroup( contextMenuPdbStructureBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 19, Short.MAX_VALUE) ); contextMenuPdbStructureBackgroundPanel.setBounds(420, 0, 30, 19); pdbStructureLayeredPane.add(contextMenuPdbStructureBackgroundPanel, javax.swing.JLayeredPane.POPUP_LAYER); javax.swing.GroupLayout pdbStructureJPanelLayout = new javax.swing.GroupLayout(pdbStructureJPanel); pdbStructureJPanel.setLayout(pdbStructureJPanelLayout); pdbStructureJPanelLayout.setHorizontalGroup( pdbStructureJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbStructureLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE) ); pdbStructureJPanelLayout.setVerticalGroup( pdbStructureJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbStructureLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE) ); proteinsJPanel.setOpaque(false); proteinsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Proteins")); proteinsPanel.setOpaque(false); proteinScrollPane.setOpaque(false); proteinTable.setModel(new ProteinTableModel()); proteinTable.setOpaque(false); proteinTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); proteinTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { proteinTableMouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { proteinTableMouseExited(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { proteinTableMouseReleased(evt); } }); proteinTable.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { proteinTableMouseMoved(evt); } }); proteinTable.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { proteinTableKeyReleased(evt); } }); proteinScrollPane.setViewportView(proteinTable); javax.swing.GroupLayout proteinsPanelLayout = new javax.swing.GroupLayout(proteinsPanel); proteinsPanel.setLayout(proteinsPanelLayout); proteinsPanelLayout.setHorizontalGroup( proteinsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 938, Short.MAX_VALUE) .addGroup(proteinsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(proteinsPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(proteinScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 918, Short.MAX_VALUE) .addContainerGap())) ); proteinsPanelLayout.setVerticalGroup( proteinsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 243, Short.MAX_VALUE) .addGroup(proteinsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(proteinsPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(proteinScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) .addContainerGap())) ); proteinsPanel.setBounds(0, 0, 950, 270); proteinsLayeredPane.add(proteinsPanel, javax.swing.JLayeredPane.DEFAULT_LAYER); proteinsHelpJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame_grey.png"))); // NOI18N proteinsHelpJButton.setToolTipText("Help"); proteinsHelpJButton.setBorder(null); proteinsHelpJButton.setBorderPainted(false); proteinsHelpJButton.setContentAreaFilled(false); proteinsHelpJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame.png"))); // NOI18N proteinsHelpJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { proteinsHelpJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { proteinsHelpJButtonMouseExited(evt); } }); proteinsHelpJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { proteinsHelpJButtonActionPerformed(evt); } }); proteinsHelpJButton.setBounds(930, 0, 10, 19); proteinsLayeredPane.add(proteinsHelpJButton, javax.swing.JLayeredPane.POPUP_LAYER); exportProteinsJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportProteinsJButton.setToolTipText("Copy to File"); exportProteinsJButton.setBorder(null); exportProteinsJButton.setBorderPainted(false); exportProteinsJButton.setContentAreaFilled(false); exportProteinsJButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportProteinsJButton.setEnabled(false); exportProteinsJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame.png"))); // NOI18N exportProteinsJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { exportProteinsJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { exportProteinsJButtonMouseExited(evt); } }); exportProteinsJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportProteinsJButtonActionPerformed(evt); } }); exportProteinsJButton.setBounds(920, 0, 10, 19); proteinsLayeredPane.add(exportProteinsJButton, javax.swing.JLayeredPane.POPUP_LAYER); contextMenuProteinsBackgroundPanel.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout contextMenuProteinsBackgroundPanelLayout = new javax.swing.GroupLayout(contextMenuProteinsBackgroundPanel); contextMenuProteinsBackgroundPanel.setLayout(contextMenuProteinsBackgroundPanelLayout); contextMenuProteinsBackgroundPanelLayout.setHorizontalGroup( contextMenuProteinsBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); contextMenuProteinsBackgroundPanelLayout.setVerticalGroup( contextMenuProteinsBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 19, Short.MAX_VALUE) ); contextMenuProteinsBackgroundPanel.setBounds(920, 0, 30, 19); proteinsLayeredPane.add(contextMenuProteinsBackgroundPanel, javax.swing.JLayeredPane.POPUP_LAYER); javax.swing.GroupLayout proteinsJPanelLayout = new javax.swing.GroupLayout(proteinsJPanel); proteinsJPanel.setLayout(proteinsJPanelLayout); proteinsJPanelLayout.setHorizontalGroup( proteinsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(proteinsLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 957, Short.MAX_VALUE) ); proteinsJPanelLayout.setVerticalGroup( proteinsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(proteinsLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE) ); peptidesJPanel.setOpaque(false); peptidesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Peptides")); peptidesPanel.setOpaque(false); peptideScrollPane.setOpaque(false); peptideTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { " ", " ", "PI", "Sequence", "Start", "PDB", "" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Boolean.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Boolean.class, java.lang.Boolean.class }; boolean[] canEdit = new boolean [] { false, true, false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); peptideTable.setOpaque(false); peptideTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); peptideTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { peptideTableMouseExited(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { peptideTableMouseReleased(evt); } }); peptideTable.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { peptideTableMouseMoved(evt); } }); peptideTable.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { peptideTableKeyReleased(evt); } }); peptideScrollPane.setViewportView(peptideTable); javax.swing.GroupLayout peptidesPanelLayout = new javax.swing.GroupLayout(peptidesPanel); peptidesPanel.setLayout(peptidesPanelLayout); peptidesPanelLayout.setHorizontalGroup( peptidesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 468, Short.MAX_VALUE) .addGroup(peptidesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(peptidesPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(peptideScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE) .addContainerGap())) ); peptidesPanelLayout.setVerticalGroup( peptidesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 133, Short.MAX_VALUE) .addGroup(peptidesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(peptidesPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(peptideScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE) .addContainerGap())) ); peptidesPanel.setBounds(0, 0, 480, 160); peptidesLayeredPane.add(peptidesPanel, javax.swing.JLayeredPane.DEFAULT_LAYER); peptidesHelpJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame_grey.png"))); // NOI18N peptidesHelpJButton.setToolTipText("Help"); peptidesHelpJButton.setBorder(null); peptidesHelpJButton.setBorderPainted(false); peptidesHelpJButton.setContentAreaFilled(false); peptidesHelpJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame.png"))); // NOI18N peptidesHelpJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { peptidesHelpJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { peptidesHelpJButtonMouseExited(evt); } }); peptidesHelpJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { peptidesHelpJButtonActionPerformed(evt); } }); peptidesHelpJButton.setBounds(460, 0, 10, 19); peptidesLayeredPane.add(peptidesHelpJButton, javax.swing.JLayeredPane.POPUP_LAYER); exportPeptidesJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPeptidesJButton.setToolTipText("Copy to File"); exportPeptidesJButton.setBorder(null); exportPeptidesJButton.setBorderPainted(false); exportPeptidesJButton.setContentAreaFilled(false); exportPeptidesJButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPeptidesJButton.setEnabled(false); exportPeptidesJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame.png"))); // NOI18N exportPeptidesJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { exportPeptidesJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { exportPeptidesJButtonMouseExited(evt); } }); exportPeptidesJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportPeptidesJButtonActionPerformed(evt); } }); exportPeptidesJButton.setBounds(450, 0, 10, 19); peptidesLayeredPane.add(exportPeptidesJButton, javax.swing.JLayeredPane.POPUP_LAYER); contextMenuPeptidesBackgroundPanel.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout contextMenuPeptidesBackgroundPanelLayout = new javax.swing.GroupLayout(contextMenuPeptidesBackgroundPanel); contextMenuPeptidesBackgroundPanel.setLayout(contextMenuPeptidesBackgroundPanelLayout); contextMenuPeptidesBackgroundPanelLayout.setHorizontalGroup( contextMenuPeptidesBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); contextMenuPeptidesBackgroundPanelLayout.setVerticalGroup( contextMenuPeptidesBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 19, Short.MAX_VALUE) ); contextMenuPeptidesBackgroundPanel.setBounds(440, 0, 30, 19); peptidesLayeredPane.add(contextMenuPeptidesBackgroundPanel, javax.swing.JLayeredPane.POPUP_LAYER); javax.swing.GroupLayout peptidesJPanelLayout = new javax.swing.GroupLayout(peptidesJPanel); peptidesJPanel.setLayout(peptidesJPanelLayout); peptidesJPanelLayout.setHorizontalGroup( peptidesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(peptidesLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE) ); peptidesJPanelLayout.setVerticalGroup( peptidesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(peptidesLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE) ); pdbMatchesJPanel.setOpaque(false); pdbMatchesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("PDB Matches")); pdbMatchesPanel.setOpaque(false); pdbJScrollPane.setOpaque(false); pdbMatchesJTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { " ", "PDB", "Title", "Type", "Chains" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); pdbMatchesJTable.setOpaque(false); pdbMatchesJTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); pdbMatchesJTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { pdbMatchesJTableMouseExited(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { pdbMatchesJTableMouseReleased(evt); } }); pdbMatchesJTable.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { pdbMatchesJTableMouseMoved(evt); } }); pdbMatchesJTable.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { pdbMatchesJTableKeyReleased(evt); } }); pdbJScrollPane.setViewportView(pdbMatchesJTable); javax.swing.GroupLayout pdbMatchesPanelLayout = new javax.swing.GroupLayout(pdbMatchesPanel); pdbMatchesPanel.setLayout(pdbMatchesPanelLayout); pdbMatchesPanelLayout.setHorizontalGroup( pdbMatchesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 468, Short.MAX_VALUE) .addGroup(pdbMatchesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pdbMatchesPanelLayout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(pdbJScrollPane) .addGap(8, 8, 8))) ); pdbMatchesPanelLayout.setVerticalGroup( pdbMatchesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 123, Short.MAX_VALUE) .addGroup(pdbMatchesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pdbMatchesPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(pdbJScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE) .addContainerGap())) ); pdbMatchesPanel.setBounds(0, 0, 480, 150); pdbMatchesLayeredPane.add(pdbMatchesPanel, javax.swing.JLayeredPane.DEFAULT_LAYER); pdbMatchesHelpJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame_grey.png"))); // NOI18N pdbMatchesHelpJButton.setToolTipText("Help"); pdbMatchesHelpJButton.setBorder(null); pdbMatchesHelpJButton.setBorderPainted(false); pdbMatchesHelpJButton.setContentAreaFilled(false); pdbMatchesHelpJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame.png"))); // NOI18N pdbMatchesHelpJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { pdbMatchesHelpJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { pdbMatchesHelpJButtonMouseExited(evt); } }); pdbMatchesHelpJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pdbMatchesHelpJButtonActionPerformed(evt); } }); pdbMatchesHelpJButton.setBounds(460, 0, 10, 19); pdbMatchesLayeredPane.add(pdbMatchesHelpJButton, javax.swing.JLayeredPane.POPUP_LAYER); exportPdbMatchesJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPdbMatchesJButton.setToolTipText("Copy to File"); exportPdbMatchesJButton.setBorder(null); exportPdbMatchesJButton.setBorderPainted(false); exportPdbMatchesJButton.setContentAreaFilled(false); exportPdbMatchesJButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPdbMatchesJButton.setEnabled(false); exportPdbMatchesJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame.png"))); // NOI18N exportPdbMatchesJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { exportPdbMatchesJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { exportPdbMatchesJButtonMouseExited(evt); } }); exportPdbMatchesJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportPdbMatchesJButtonActionPerformed(evt); } }); exportPdbMatchesJButton.setBounds(450, 0, 10, 19); pdbMatchesLayeredPane.add(exportPdbMatchesJButton, javax.swing.JLayeredPane.POPUP_LAYER); contextMenuPdbMatchesBackgroundPanel.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout contextMenuPdbMatchesBackgroundPanelLayout = new javax.swing.GroupLayout(contextMenuPdbMatchesBackgroundPanel); contextMenuPdbMatchesBackgroundPanel.setLayout(contextMenuPdbMatchesBackgroundPanelLayout); contextMenuPdbMatchesBackgroundPanelLayout.setHorizontalGroup( contextMenuPdbMatchesBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); contextMenuPdbMatchesBackgroundPanelLayout.setVerticalGroup( contextMenuPdbMatchesBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 19, Short.MAX_VALUE) ); contextMenuPdbMatchesBackgroundPanel.setBounds(440, 0, 30, 19); pdbMatchesLayeredPane.add(contextMenuPdbMatchesBackgroundPanel, javax.swing.JLayeredPane.POPUP_LAYER); javax.swing.GroupLayout pdbMatchesJPanelLayout = new javax.swing.GroupLayout(pdbMatchesJPanel); pdbMatchesJPanel.setLayout(pdbMatchesJPanelLayout); pdbMatchesJPanelLayout.setHorizontalGroup( pdbMatchesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbMatchesLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE) ); pdbMatchesJPanelLayout.setVerticalGroup( pdbMatchesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbMatchesLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE) ); pdbChainsJPanel.setOpaque(false); pdbChainsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("PDB Chains")); pdbChainsPanel.setOpaque(false); pdbChainsJScrollPane.setOpaque(false); pdbChainsJTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { " ", "Chain", "PDB-Protein", "Coverage" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.Double.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); pdbChainsJTable.setOpaque(false); pdbChainsJTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); pdbChainsJTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { pdbChainsJTableMouseReleased(evt); } }); pdbChainsJTable.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { pdbChainsJTableKeyReleased(evt); } }); pdbChainsJScrollPane.setViewportView(pdbChainsJTable); javax.swing.GroupLayout pdbChainsPanelLayout = new javax.swing.GroupLayout(pdbChainsPanel); pdbChainsPanel.setLayout(pdbChainsPanelLayout); pdbChainsPanelLayout.setHorizontalGroup( pdbChainsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 468, Short.MAX_VALUE) .addGroup(pdbChainsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pdbChainsPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(pdbChainsJScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE) .addContainerGap())) ); pdbChainsPanelLayout.setVerticalGroup( pdbChainsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 133, Short.MAX_VALUE) .addGroup(pdbChainsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pdbChainsPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(pdbChainsJScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE) .addContainerGap())) ); pdbChainsPanel.setBounds(0, 0, 480, 160); pdbChainsLayeredPane.add(pdbChainsPanel, javax.swing.JLayeredPane.DEFAULT_LAYER); pdbChainHelpJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame_grey.png"))); // NOI18N pdbChainHelpJButton.setToolTipText("Help"); pdbChainHelpJButton.setBorder(null); pdbChainHelpJButton.setBorderPainted(false); pdbChainHelpJButton.setContentAreaFilled(false); pdbChainHelpJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/help_no_frame.png"))); // NOI18N pdbChainHelpJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { pdbChainHelpJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { pdbChainHelpJButtonMouseExited(evt); } }); pdbChainHelpJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pdbChainHelpJButtonActionPerformed(evt); } }); pdbChainHelpJButton.setBounds(460, 0, 10, 19); pdbChainsLayeredPane.add(pdbChainHelpJButton, javax.swing.JLayeredPane.POPUP_LAYER); exportPdbChainsJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPdbChainsJButton.setToolTipText("Copy to File"); exportPdbChainsJButton.setBorder(null); exportPdbChainsJButton.setBorderPainted(false); exportPdbChainsJButton.setContentAreaFilled(false); exportPdbChainsJButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame_grey.png"))); // NOI18N exportPdbChainsJButton.setEnabled(false); exportPdbChainsJButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/export_no_frame.png"))); // NOI18N exportPdbChainsJButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { exportPdbChainsJButtonMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { exportPdbChainsJButtonMouseExited(evt); } }); exportPdbChainsJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportPdbChainsJButtonActionPerformed(evt); } }); exportPdbChainsJButton.setBounds(450, 0, 10, 19); pdbChainsLayeredPane.add(exportPdbChainsJButton, javax.swing.JLayeredPane.POPUP_LAYER); contextMenuPdbChainsBackgroundPanel.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout contextMenuPdbChainsBackgroundPanelLayout = new javax.swing.GroupLayout(contextMenuPdbChainsBackgroundPanel); contextMenuPdbChainsBackgroundPanel.setLayout(contextMenuPdbChainsBackgroundPanelLayout); contextMenuPdbChainsBackgroundPanelLayout.setHorizontalGroup( contextMenuPdbChainsBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); contextMenuPdbChainsBackgroundPanelLayout.setVerticalGroup( contextMenuPdbChainsBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 19, Short.MAX_VALUE) ); contextMenuPdbChainsBackgroundPanel.setBounds(440, 0, 30, 19); pdbChainsLayeredPane.add(contextMenuPdbChainsBackgroundPanel, javax.swing.JLayeredPane.POPUP_LAYER); javax.swing.GroupLayout pdbChainsJPanelLayout = new javax.swing.GroupLayout(pdbChainsJPanel); pdbChainsJPanel.setLayout(pdbChainsJPanelLayout); pdbChainsJPanelLayout.setHorizontalGroup( pdbChainsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbChainsLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE) ); pdbChainsJPanelLayout.setVerticalGroup( pdbChainsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbChainsLayeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pdbMatchesJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(pdbChainsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(peptidesJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pdbStructureJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(proteinsJPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(proteinsJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(pdbMatchesJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pdbChainsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(peptidesJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(pdbStructureJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); pdbStructureJPanel.getAccessibleContext().setAccessibleName("Protein Details"); }// </editor-fold>//GEN-END:initComponents /** * Makes sure the cursor changes back to the default cursor when leaving the * protein accession number column. * * @param evt */ private void proteinTableMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proteinTableMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_proteinTableMouseExited /** * Changes the cursor into a hand cursor if the table cell contains an HTML * link. * * @param evt */ private void proteinTableMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proteinTableMouseMoved int row = proteinTable.rowAtPoint(evt.getPoint()); int column = proteinTable.columnAtPoint(evt.getPoint()); proteinTable.setToolTipText(null); if (column == proteinTable.getColumn("Accession").getModelIndex() && proteinTable.getValueAt(row, column) != null) { String tempValue = (String) proteinTable.getValueAt(row, column); if (tempValue.lastIndexOf("<a href=\"") != -1) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); } else { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } } else if (column == proteinTable.getColumn("PI").getModelIndex() && proteinTable.getValueAt(row, column) != null) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); } else if (column == proteinTable.getColumn("Chr").getModelIndex() && proteinTable.getValueAt(row, column) != null) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); } else if (column == proteinTable.getColumn("Description").getModelIndex() && proteinTable.getValueAt(row, column) != null) { if (GuiUtilities.getPreferredWidthOfCell(proteinTable, row, column) > proteinTable.getColumn("Description").getWidth()) { proteinTable.setToolTipText("" + proteinTable.getValueAt(row, column)); } this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } else { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } }//GEN-LAST:event_proteinTableMouseMoved /** * Update the protein selection and the corresponding tables. * * @param evt */ private void proteinTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_proteinTableKeyReleased proteinTableMouseReleased(null); }//GEN-LAST:event_proteinTableKeyReleased /** * Updates the PDB structure. * * @param evt */ private void peptideTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_peptideTableKeyReleased if (evt == null || evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN || evt.getKeyCode() == KeyEvent.VK_PAGE_UP || evt.getKeyCode() == KeyEvent.VK_PAGE_DOWN) { peptideTableMouseReleased(null); } }//GEN-LAST:event_peptideTableKeyReleased /** * Update the PDB structure shown in the Jmol panel. * * @param evt */ private void pdbMatchesJTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pdbMatchesJTableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN || evt.getKeyCode() == KeyEvent.VK_PAGE_UP || evt.getKeyCode() == KeyEvent.VK_PAGE_DOWN) { pdbMatchesJTableMouseReleased(null); } }//GEN-LAST:event_pdbMatchesJTableKeyReleased /** * Update the protein selection and the corresponding tables. * * @param evt */ private void proteinTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proteinTableMouseReleased int row = proteinTable.getSelectedRow(); int column = proteinTable.getSelectedColumn(); int proteinIndex = -1; if (row != -1) { SelfUpdatingTableModel tableModel = (SelfUpdatingTableModel) proteinTable.getModel(); proteinIndex = tableModel.getViewIndex(row); } if (evt == null || (evt.getButton() == MouseEvent.BUTTON1 && (proteinIndex != -1 && column != -1))) { if (proteinIndex != -1) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); long proteinKey = proteinKeys[proteinIndex]; peptideShakerGUI.setSelectedItems(proteinKey, NO_KEY, null, null); // update the pdb file table updatePdbTable(proteinKey); // empty the jmol panel if (jmolStructureShown) { jmolPanel = new JmolPanel(); pdbPanel.removeAll(); pdbPanel.add(jmolPanel); pdbPanel.revalidate(); pdbPanel.repaint(); jmolStructureShown = false; currentlyDisplayedPdbFile = null; ((TitledBorder) pdbOuterPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Structure" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); pdbOuterPanel.repaint(); } // update the peptide selection updatedPeptideSelection(proteinIndex); // remember the selection newItemSelection(); this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); // open the gene details dialog if (column == proteinTable.getColumn("Chr").getModelIndex() && evt != null && evt.getButton() == MouseEvent.BUTTON1) { ProteinMatch proteinMatch = peptideShakerGUI.getIdentification().getProteinMatch(proteinKey); new GeneDetailsDialog( peptideShakerGUI, proteinMatch, peptideShakerGUI.getGeneMaps(), peptideShakerGUI.getProteinDetailsProvider() ); } // open protein link in web browser if (column == proteinTable.getColumn("Accession").getModelIndex() && evt != null && evt.getButton() == MouseEvent.BUTTON1 && ((String) proteinTable.getValueAt(row, column)).lastIndexOf("<a href=\"") != -1) { String link = (String) proteinTable.getValueAt(row, column); link = link.substring(link.indexOf("\"") + 1); link = link.substring(0, link.indexOf("\"")); this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); BareBonesBrowserLaunch.openURL(link); this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } // open the protein inference dialog if (column == proteinTable.getColumn("PI").getModelIndex() && evt != null && evt.getButton() == MouseEvent.BUTTON1) { new ProteinInferenceDialog( peptideShakerGUI, peptideShakerGUI.getGeneMaps(), proteinKey, peptideShakerGUI.getIdentification() ); } if (column == proteinTable.getColumn(" ").getModelIndex()) { ProteinMatch proteinMatch = peptideShakerGUI.getIdentification().getProteinMatch(proteinKey); PSParameter psParameter = (PSParameter) proteinMatch.getUrParam(PSParameter.dummy); if (!psParameter.getStarred()) { peptideShakerGUI.getStarHider().starProtein(proteinKey); } else { peptideShakerGUI.getStarHider().unStarProtein(proteinKey); } peptideShakerGUI.setDataSaved(false); } } } }//GEN-LAST:event_proteinTableMouseReleased /** * Updates the PDB structure. * * @param evt */ private void peptideTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_peptideTableMouseReleased setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); if (evt != null) { peptideShakerGUI.setSelectedItems(peptideShakerGUI.getSelectedProteinKey(), NO_KEY, null, null); } int row = peptideTable.getSelectedRow(); int column = peptideTable.getSelectedColumn(); if (row != -1) { if (pdbMatchesJTable.getSelectedRow() != -1) { updatePeptideToPdbMapping(); } // remember the selection newItemSelection(); if (column == peptideTable.getColumn(" ").getModelIndex()) { long peptideKey = peptideTableMap.get(getPeptideIndex(row)); PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); PSParameter psParameter = (PSParameter) peptideMatch.getUrParam(PSParameter.dummy); if (!psParameter.getStarred()) { peptideShakerGUI.getStarHider().starPeptide(peptideKey); } else { peptideShakerGUI.getStarHider().unStarPeptide(peptideKey); } peptideShakerGUI.setDataSaved(false); } // open the protein inference at the petide level dialog if (column == peptideTable.getColumn("PI").getModelIndex() && evt != null && evt.getButton() == MouseEvent.BUTTON1) { SelfUpdatingTableModel tableModel = (SelfUpdatingTableModel) proteinTable.getModel(); int proteinIndex = tableModel.getViewIndex(proteinTable.getSelectedRow()); long proteinKey = proteinKeys[proteinIndex]; long peptideKey = peptideTableMap.get(getPeptideIndex(row)); new ProteinInferencePeptideLevelDialog( peptideShakerGUI, true, peptideKey, proteinKey, peptideShakerGUI.getGeneMaps() ); } } setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_peptideTableMouseReleased /** * Update the PDB structure shown in the Jmol panel. * * @param evt */ private void pdbMatchesJTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbMatchesJTableMouseReleased setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); boolean loadStructure = true; if (pdbMatchesJTable.getSelectedRow() != -1 && currentlyDisplayedPdbFile != null) { String tempPdbFile = (String) pdbMatchesJTable.getValueAt( pdbMatchesJTable.getSelectedRow(), pdbMatchesJTable.getColumn("PDB").getModelIndex() ); if (currentlyDisplayedPdbFile.equalsIgnoreCase(tempPdbFile)) { loadStructure = false; } } if (loadStructure) { // just a trick to make sure that the users cannot select // another row until the selection has been updated this.setEnabled(false); DefaultTableModel dm = (DefaultTableModel) pdbChainsJTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); // clear the peptide to pdb mappings in the peptide table for (int i = 0; i < peptideTable.getRowCount(); i++) { peptideTable.setValueAt(false, i, peptideTable.getColumn("PDB").getModelIndex()); } // select the peptide in the table again int peptideRow = 0; long peptideKey = peptideShakerGUI.getSelectedPeptideKey(); if (peptideKey != NO_KEY) { peptideRow = getPeptideRow(peptideKey); } if (peptideTable.getRowCount() > 0) { peptideTable.setRowSelectionInterval(peptideRow, peptideRow); peptideTable.scrollRectToVisible(peptideTable.getCellRect(peptideRow, peptideRow, false)); } // empty the jmol panel if (jmolStructureShown) { jmolPanel = new JmolPanel(); pdbPanel.removeAll(); pdbPanel.add(jmolPanel); pdbPanel.revalidate(); pdbPanel.repaint(); jmolStructureShown = false; currentlyDisplayedPdbFile = null; ((TitledBorder) pdbOuterPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Structure" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); pdbOuterPanel.repaint(); } if (pdbMatchesJTable.getSelectedRow() != -1) { currentlyDisplayedPdbFile = (String) pdbMatchesJTable.getValueAt( pdbMatchesJTable.getSelectedRow(), pdbMatchesJTable.getColumn("PDB").getModelIndex() ); // open protein link in web browser if (pdbMatchesJTable.getSelectedColumn() == pdbMatchesJTable.getColumn("PDB").getModelIndex() && evt.getButton() == MouseEvent.BUTTON1 && ((String) pdbMatchesJTable.getValueAt(pdbMatchesJTable.getSelectedRow(), pdbMatchesJTable.getSelectedColumn())).lastIndexOf("<a href=\"") != -1) { String temp = currentlyDisplayedPdbFile.substring(currentlyDisplayedPdbFile.indexOf("\"") + 1); currentlyDisplayedPdbFile = temp.substring(0, temp.indexOf("\"")); this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); BareBonesBrowserLaunch.openURL(currentlyDisplayedPdbFile); this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } // get the pdb file int selectedPdbTableIndex = (Integer) pdbMatchesJTable.getValueAt(pdbMatchesJTable.getSelectedRow(), 0); PdbParameter lParam = uniProtPdb.getPdbs().get(selectedPdbTableIndex - 1); chains = lParam.getBlocks(); // get the protein sequence SelfUpdatingTableModel proteinTableModel = (SelfUpdatingTableModel) proteinTable.getModel(); int proteinIndex = proteinTableModel.getViewIndex(proteinTable.getSelectedRow()); long proteinKey = proteinKeys[proteinIndex]; ProteinMatch proteinMatch = peptideShakerGUI.getIdentification().getProteinMatch(proteinKey); String proteinSequence = peptideShakerGUI.getSequenceProvider().getSequence(proteinMatch.getLeadingAccession()); // @TODO: the code below does not pick up domain information, but rather shows multiple hits for chain. could perhaps be improved? // add the chain information to the table for (int j = 0; j < chains.length; j++) { XYDataPoint temp = new XYDataPoint(chains[j].getStartProtein(), chains[j].getEndProtein()); if (chains[j].getStartProtein() != chains[j].getEndProtein()) { ((DefaultTableModel) pdbChainsJTable.getModel()).addRow(new Object[]{ (j + 1), chains[j].getBlock(), temp, (((double) chains[j].getEndProtein() - chains[j].getStartProtein()) / proteinSequence.length()) * 100 }); } } ((JSparklinesIntervalChartTableCellRenderer) pdbChainsJTable.getColumn("PDB-Protein").getCellRenderer()).setMaxValue(proteinSequence.length()); if (pdbChainsJTable.getRowCount() > 0) { ((TitledBorder) pdbChainsPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Chains (" + pdbChainsJTable.getRowCount() + ")" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); } else { ((TitledBorder) pdbChainsPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Chains" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); } pdbChainsPanel.repaint(); if (pdbChainsJTable.getRowCount() > 0) { pdbChainsJTable.setRowSelectionInterval(0, 0); pdbChainsJTable.scrollRectToVisible(pdbChainsJTable.getCellRect(0, 0, false)); pdbChainsJTableMouseReleased(null); } } else { ((TitledBorder) pdbChainsPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Chains" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); pdbChainsPanel.repaint(); } // give the power back to the user ;) this.setEnabled(true); } else { // open protein link in web browser if (pdbMatchesJTable.getSelectedColumn() == pdbMatchesJTable.getColumn("PDB").getModelIndex() && evt.getButton() == MouseEvent.BUTTON1 && ((String) pdbMatchesJTable.getValueAt(pdbMatchesJTable.getSelectedRow(), pdbMatchesJTable.getSelectedColumn())).lastIndexOf("<a href=\"") != -1) { String temp = currentlyDisplayedPdbFile.substring(currentlyDisplayedPdbFile.indexOf("\"") + 1); currentlyDisplayedPdbFile = temp.substring(0, temp.indexOf("\"")); this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); BareBonesBrowserLaunch.openURL(currentlyDisplayedPdbFile); this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } } setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbMatchesJTableMouseReleased /** * Update the PDB structure with the current chain selection. * * @param evt */ private void pdbChainsJTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbChainsJTableMouseReleased setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); if (jmolStructureShown) { updatePeptideToPdbMapping(); } else { progressDialog = new ProgressDialogX(peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true); progressDialog.setPrimaryProgressCounterIndeterminate(true); progressDialog.setTitle("Loading PDB Structure. Please Wait..."); new Thread(new Runnable() { public void run() { try { progressDialog.setVisible(true); } catch (IndexOutOfBoundsException e) { // ignore } } }, "PdbChaingThread").start(); new Thread("StructureThread") { @Override public void run() { progressDialog.setPrimaryProgressCounterIndeterminate(true); int selectedPdbIndex = (Integer) pdbMatchesJTable.getValueAt(pdbMatchesJTable.getSelectedRow(), 0); PdbParameter lParam = uniProtPdb.getPdbs().get(selectedPdbIndex - 1); String link = "https://files.rcsb.org/download/" + lParam.getPdbaccession() + ".pdb"; jmolPanel.getViewer().openFile(link); if (ribbonModel) { jmolPanel.getViewer().evalString("select all; ribbon only;"); } else if (backboneModel) { jmolPanel.getViewer().evalString("select all; backbone only; backbone 100;"); } if (!progressDialog.isRunCanceled()) { spinModel(spinModel); jmolStructureShown = true; ((TitledBorder) pdbOuterPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Structure (" + lParam.getPdbaccession() + ")" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); pdbOuterPanel.repaint(); } if (!progressDialog.isRunCanceled()) { progressDialog.setTitle("Mapping Peptides. Please Wait..."); // get the chains chains = lParam.getBlocks(); int selectedChainIndex = (Integer) pdbChainsJTable.getValueAt(pdbChainsJTable.getSelectedRow(), 0); chainSequence = chains[selectedChainIndex - 1].getBlockSequence(lParam.getPdbaccession()); // update the peptide to pdb mappings updatePeptideToPdbMapping(); } progressDialog.setRunFinished(); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } }.start(); } setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbChainsJTableMouseReleased /** * Update the PDB structure with the currently selected chain. * * @param evt */ private void pdbChainsJTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pdbChainsJTableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN || evt.getKeyCode() == KeyEvent.VK_PAGE_UP || evt.getKeyCode() == KeyEvent.VK_PAGE_DOWN) { updatePeptideToPdbMapping(); } }//GEN-LAST:event_pdbChainsJTableKeyReleased /** * Changes the cursor into a hand cursor if the table cell contains an HTML * link. * * @param evt */ private void pdbMatchesJTableMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbMatchesJTableMouseMoved int row = pdbMatchesJTable.rowAtPoint(evt.getPoint()); int column = pdbMatchesJTable.columnAtPoint(evt.getPoint()); if (column == pdbMatchesJTable.getColumn("PDB").getModelIndex() && pdbMatchesJTable.getValueAt(row, column) != null) { String tempValue = (String) pdbMatchesJTable.getValueAt(row, column); if (tempValue.lastIndexOf("<a href=\"") != -1) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); } else { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } } else { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } }//GEN-LAST:event_pdbMatchesJTableMouseMoved /** * Changes the cursor back to the default cursor a hand. * * @param evt */ private void pdbMatchesJTableMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbMatchesJTableMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbMatchesJTableMouseExited /** * Resizes the components in the PDB Structure layered pane if the layered * pane is resized. * * @param evt */ private void pdbLayeredPaneComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_pdbLayeredPaneComponentResized int componentIndex = 0; // move the icons pdbLayeredPane.getComponent(componentIndex++).setBounds( pdbLayeredPane.getWidth() - pdbLayeredPane.getComponent(0).getWidth() * componentIndex - 10, pdbLayeredPane.getComponent(0).getHeight() / 10 - 2, pdbLayeredPane.getComponent(0).getWidth(), pdbLayeredPane.getComponent(0).getHeight() ); pdbLayeredPane.getComponent(componentIndex++).setBounds( pdbLayeredPane.getWidth() - pdbLayeredPane.getComponent(0).getWidth() * componentIndex - 15, pdbLayeredPane.getComponent(0).getHeight() / 10 - 2, pdbLayeredPane.getComponent(0).getWidth(), pdbLayeredPane.getComponent(0).getHeight() ); pdbLayeredPane.getComponent(componentIndex++).setBounds( pdbLayeredPane.getWidth() - pdbLayeredPane.getComponent(0).getWidth() * componentIndex - 10, pdbLayeredPane.getComponent(0).getHeight() / 10 - 2, pdbLayeredPane.getComponent(0).getWidth(), pdbLayeredPane.getComponent(0).getHeight() ); pdbLayeredPane.getComponent(componentIndex++).setBounds( pdbLayeredPane.getWidth() - pdbLayeredPane.getComponent(0).getWidth() * componentIndex - 15, pdbLayeredPane.getComponent(0).getHeight() / 10, pdbLayeredPane.getComponent(0).getWidth(), pdbLayeredPane.getComponent(0).getHeight() ); // resize the plot area pdbLayeredPane.getComponent(componentIndex++).setBounds( 0, 0, pdbLayeredPane.getWidth(), pdbLayeredPane.getHeight() ); pdbLayeredPane.revalidate(); pdbLayeredPane.repaint(); }//GEN-LAST:event_pdbLayeredPaneComponentResized /** * Changes the cursor back to the default cursor. * * @param evt */ private void peptideTableMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_peptideTableMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_peptideTableMouseExited /** * Changes the cursor into a hand cursor if the table cell contains an HTML * link. Or shows a tooltip with modification details is over the sequence * column. * * @param evt */ private void peptideTableMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_peptideTableMouseMoved int row = peptideTable.rowAtPoint(evt.getPoint()); int column = peptideTable.columnAtPoint(evt.getPoint()); if (peptideTable.getValueAt(row, column) != null) { if (column == peptideTable.getColumn("PI").getModelIndex()) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); peptideTable.setToolTipText(null); } else if (column == peptideTable.getColumn("Sequence").getModelIndex()) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); // check if we ought to show a tooltip with mod details String sequence = (String) peptideTable.getValueAt(row, column); if (sequence.contains("<span")) { long peptideKey = peptideTableMap.get(getPeptideIndex(row)); PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); String tooltip = peptideShakerGUI.getDisplayFeaturesGenerator().getPeptideModificationTooltipAsHtml(peptideMatch); peptideTable.setToolTipText(tooltip); } else { peptideTable.setToolTipText(null); } } else { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); peptideTable.setToolTipText(null); } } else { this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); peptideTable.setToolTipText(null); } }//GEN-LAST:event_peptideTableMouseMoved /** * Change the cursor to a hand cursor. * * @param evt */ private void playJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_playJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_playJButtonMouseEntered /** * Changes the cursor back to the default cursor. * * @param evt */ private void playJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_playJButtonMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_playJButtonMouseExited /** * Start/stop the rotation of the structure. * * @param evt */ private void playJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playJButtonActionPerformed spinModel = !spinModel; spinModel(spinModel); if (spinModel) { playJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/pause.png"))); playJButton.setToolTipText("Stop Rotation"); } else { playJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/play.png"))); playJButton.setToolTipText("Start Rotation"); } }//GEN-LAST:event_playJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void ribbonJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ribbonJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_ribbonJButtonMouseEntered /** * Changes the cursor back to the default cursor. * * @param evt */ private void ribbonJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ribbonJButtonMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_ribbonJButtonMouseExited /** * Change the model type to ribbon. * * @param evt */ private void ribbonJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ribbonJButtonActionPerformed ribbonModel = true; backboneModel = false; updateModelType(); if (backboneModel) { backboneJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/backbone_selected.png"))); ribbonJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ribbon.png"))); } else { backboneJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/backbone.png"))); ribbonJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ribbon_selected.png"))); } }//GEN-LAST:event_ribbonJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void backboneJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backboneJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_backboneJButtonMouseEntered /** * Changes the cursor back to the default cursor. * * @param evt */ private void backboneJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backboneJButtonMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_backboneJButtonMouseExited /** * Change the model type to backbone. * * @param evt */ private void backboneJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backboneJButtonActionPerformed ribbonModel = false; backboneModel = true; updateModelType(); if (backboneModel) { backboneJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/backbone_selected.png"))); ribbonJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ribbon.png"))); } else { backboneJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/backbone.png"))); ribbonJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ribbon_selected.png"))); } }//GEN-LAST:event_backboneJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void labelsJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelsJButtonMouseEntered this.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_labelsJButtonMouseEntered /** * Changes the cursor back to the default cursor. * * @param evt */ private void labelsJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelsJButtonMouseExited this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_labelsJButtonMouseExited /** * Set if the modification labels are to be shown or not. * * @param evt */ private void labelsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelsJButtonActionPerformed showModificationLabels = !showModificationLabels; if (showModificationLabels) { labelsJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/labels_selected.png"))); labelsJButton.setToolTipText("Hide Modification Labels"); } else { labelsJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/labels.png"))); labelsJButton.setToolTipText("Show Modification Labels"); } if (pdbMatchesJTable.getSelectedRow() != -1 && peptideTable.getSelectedRow() != -1) { updatePeptideToPdbMapping(); } }//GEN-LAST:event_labelsJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void exportProteinsJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportProteinsJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_exportProteinsJButtonMouseEntered /** * Change the cursor to a default cursor. * * @param evt */ private void exportProteinsJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportProteinsJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_exportProteinsJButtonMouseExited /** * Export the table contents. * * @param evt */ private void exportProteinsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportProteinsJButtonActionPerformed try { copyTableContentToClipboardOrFile(TableIndex.PROTEIN_TABLE); } catch (IOException ioe) { peptideShakerGUI.catchException(ioe); } }//GEN-LAST:event_exportProteinsJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void proteinsHelpJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proteinsHelpJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_proteinsHelpJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void proteinsHelpJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proteinsHelpJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_proteinsHelpJButtonMouseExited /** * Open the help dialog. * * @param evt */ private void proteinsHelpJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proteinsHelpJButtonActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); new HelpDialog( peptideShakerGUI, getClass().getResource("/helpFiles/PDB.html"), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/help.GIF")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), "Protein Structure - Help" ); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_proteinsHelpJButtonActionPerformed /** * Update the layered panes. * * @param evt */ private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized // resize the layered panels SwingUtilities.invokeLater(new Runnable() { public void run() { // move the icons proteinsLayeredPane.getComponent(0).setBounds( proteinsLayeredPane.getWidth() - proteinsLayeredPane.getComponent(0).getWidth() - 10, -3, proteinsLayeredPane.getComponent(0).getWidth(), proteinsLayeredPane.getComponent(0).getHeight()); proteinsLayeredPane.getComponent(1).setBounds( proteinsLayeredPane.getWidth() - proteinsLayeredPane.getComponent(1).getWidth() - 20, -3, proteinsLayeredPane.getComponent(1).getWidth(), proteinsLayeredPane.getComponent(1).getHeight()); proteinsLayeredPane.getComponent(2).setBounds( proteinsLayeredPane.getWidth() - proteinsLayeredPane.getComponent(2).getWidth() - 5, -3, proteinsLayeredPane.getComponent(2).getWidth(), proteinsLayeredPane.getComponent(2).getHeight()); // resize the plot area proteinsLayeredPane.getComponent(3).setBounds( 0, 0, proteinsLayeredPane.getWidth(), proteinsLayeredPane.getHeight() ); proteinsLayeredPane.revalidate(); proteinsLayeredPane.repaint(); // move the icons peptidesLayeredPane.getComponent(0).setBounds( peptidesLayeredPane.getWidth() - peptidesLayeredPane.getComponent(0).getWidth() - 10, -3, peptidesLayeredPane.getComponent(0).getWidth(), peptidesLayeredPane.getComponent(0).getHeight() ); peptidesLayeredPane.getComponent(1).setBounds( peptidesLayeredPane.getWidth() - peptidesLayeredPane.getComponent(1).getWidth() - 20, -3, peptidesLayeredPane.getComponent(1).getWidth(), peptidesLayeredPane.getComponent(1).getHeight() ); peptidesLayeredPane.getComponent(2).setBounds( peptidesLayeredPane.getWidth() - peptidesLayeredPane.getComponent(2).getWidth() - 5, -3, peptidesLayeredPane.getComponent(2).getWidth(), peptidesLayeredPane.getComponent(2).getHeight() ); // resize the plot area peptidesLayeredPane.getComponent(3).setBounds( 0, 0, peptidesLayeredPane.getWidth(), peptidesLayeredPane.getHeight() ); peptidesLayeredPane.revalidate(); peptidesLayeredPane.repaint(); // move the icons pdbMatchesLayeredPane.getComponent(0).setBounds( pdbMatchesLayeredPane.getWidth() - pdbMatchesLayeredPane.getComponent(0).getWidth() - 10, -3, pdbMatchesLayeredPane.getComponent(0).getWidth(), pdbMatchesLayeredPane.getComponent(0).getHeight() ); pdbMatchesLayeredPane.getComponent(1).setBounds( pdbMatchesLayeredPane.getWidth() - pdbMatchesLayeredPane.getComponent(1).getWidth() - 20, -3, pdbMatchesLayeredPane.getComponent(1).getWidth(), pdbMatchesLayeredPane.getComponent(1).getHeight() ); pdbMatchesLayeredPane.getComponent(2).setBounds( pdbMatchesLayeredPane.getWidth() - pdbMatchesLayeredPane.getComponent(2).getWidth() - 5, -3, pdbMatchesLayeredPane.getComponent(2).getWidth(), pdbMatchesLayeredPane.getComponent(2).getHeight() ); // resize the plot area pdbMatchesLayeredPane.getComponent(3).setBounds( 0, 0, pdbMatchesLayeredPane.getWidth(), pdbMatchesLayeredPane.getHeight() ); pdbMatchesLayeredPane.revalidate(); pdbMatchesLayeredPane.repaint(); // move the icons pdbChainsLayeredPane.getComponent(0).setBounds( pdbChainsLayeredPane.getWidth() - pdbChainsLayeredPane.getComponent(0).getWidth() - 10, -3, pdbChainsLayeredPane.getComponent(0).getWidth(), pdbChainsLayeredPane.getComponent(0).getHeight() ); pdbChainsLayeredPane.getComponent(1).setBounds( pdbChainsLayeredPane.getWidth() - pdbChainsLayeredPane.getComponent(1).getWidth() - 20, -3, pdbChainsLayeredPane.getComponent(1).getWidth(), pdbChainsLayeredPane.getComponent(1).getHeight() ); pdbChainsLayeredPane.getComponent(2).setBounds( pdbChainsLayeredPane.getWidth() - pdbChainsLayeredPane.getComponent(2).getWidth() - 5, -3, pdbChainsLayeredPane.getComponent(2).getWidth(), pdbChainsLayeredPane.getComponent(2).getHeight() ); // resize the plot area pdbChainsLayeredPane.getComponent(3).setBounds( 0, 0, pdbChainsLayeredPane.getWidth(), pdbChainsLayeredPane.getHeight() ); pdbChainsLayeredPane.revalidate(); pdbChainsLayeredPane.repaint(); // move the icons pdbStructureLayeredPane.getComponent(0).setBounds( pdbStructureLayeredPane.getWidth() - pdbStructureLayeredPane.getComponent(0).getWidth() - 10, -3, pdbStructureLayeredPane.getComponent(0).getWidth(), pdbStructureLayeredPane.getComponent(0).getHeight() ); pdbStructureLayeredPane.getComponent(1).setBounds( pdbStructureLayeredPane.getWidth() - pdbStructureLayeredPane.getComponent(1).getWidth() - 20, -3, pdbStructureLayeredPane.getComponent(1).getWidth(), pdbStructureLayeredPane.getComponent(1).getHeight() ); pdbStructureLayeredPane.getComponent(2).setBounds( pdbStructureLayeredPane.getWidth() - pdbStructureLayeredPane.getComponent(2).getWidth() - 5, -3, pdbStructureLayeredPane.getComponent(2).getWidth(), pdbStructureLayeredPane.getComponent(2).getHeight() ); // resize the plot area pdbStructureLayeredPane.getComponent(3).setBounds( 0, 0, pdbStructureLayeredPane.getWidth(), pdbStructureLayeredPane.getHeight() ); pdbStructureLayeredPane.revalidate(); pdbStructureLayeredPane.repaint(); } }); }//GEN-LAST:event_formComponentResized /** * Change the cursor to a hand cursor. * * @param evt */ private void peptidesHelpJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_peptidesHelpJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_peptidesHelpJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void peptidesHelpJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_peptidesHelpJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_peptidesHelpJButtonMouseExited /** * Open the help dialog. * * @param evt */ private void peptidesHelpJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_peptidesHelpJButtonActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); new HelpDialog( peptideShakerGUI, getClass().getResource("/helpFiles/PDB.html"), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/help.GIF")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), "Protein Structure - Help" ); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_peptidesHelpJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void exportPeptidesJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPeptidesJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_exportPeptidesJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void exportPeptidesJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPeptidesJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_exportPeptidesJButtonMouseExited /** * Export the table contents. * * @param evt */ private void exportPeptidesJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportPeptidesJButtonActionPerformed try { copyTableContentToClipboardOrFile(TableIndex.PEPTIDE_TABLE); } catch (IOException ioe) { peptideShakerGUI.catchException(ioe); } }//GEN-LAST:event_exportPeptidesJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void pdbMatchesHelpJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbMatchesHelpJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_pdbMatchesHelpJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void pdbMatchesHelpJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbMatchesHelpJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbMatchesHelpJButtonMouseExited /** * Open the help dialog. * * @param evt */ private void pdbMatchesHelpJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pdbMatchesHelpJButtonActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); new HelpDialog( peptideShakerGUI, getClass().getResource("/helpFiles/PDB.html"), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/help.GIF")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), "Protein Structure - Help" ); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbMatchesHelpJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void exportPdbMatchesJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPdbMatchesJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_exportPdbMatchesJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void exportPdbMatchesJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPdbMatchesJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_exportPdbMatchesJButtonMouseExited /** * Export the table contents. * * @param evt */ private void exportPdbMatchesJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportPdbMatchesJButtonActionPerformed try { copyTableContentToClipboardOrFile(TableIndex.PDB_MATCHES); } catch (IOException ioe) { peptideShakerGUI.catchException(ioe); } }//GEN-LAST:event_exportPdbMatchesJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void pdbChainHelpJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbChainHelpJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_pdbChainHelpJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void pdbChainHelpJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbChainHelpJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbChainHelpJButtonMouseExited /** * Open the help dialog. * * @param evt */ private void pdbChainHelpJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pdbChainHelpJButtonActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); new HelpDialog( peptideShakerGUI, getClass().getResource("/helpFiles/PDB.html"), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/help.GIF")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), "Protein Structure - Help" ); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbChainHelpJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void exportPdbChainsJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPdbChainsJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_exportPdbChainsJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void exportPdbChainsJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPdbChainsJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_exportPdbChainsJButtonMouseExited /** * Export the table contents. * * @param evt */ private void exportPdbChainsJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportPdbChainsJButtonActionPerformed try { copyTableContentToClipboardOrFile(TableIndex.PDB_CHAINS); } catch (IOException ioe) { peptideShakerGUI.catchException(ioe); } }//GEN-LAST:event_exportPdbChainsJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void pdbStructureHelpJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbStructureHelpJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_pdbStructureHelpJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void pdbStructureHelpJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pdbStructureHelpJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbStructureHelpJButtonMouseExited /** * Open the help dialog. * * @param evt */ private void pdbStructureHelpJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pdbStructureHelpJButtonActionPerformed setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); new HelpDialog( peptideShakerGUI, getClass().getResource("/helpFiles/PDB.html"), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/help.GIF")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), "Protein Structure - Help" ); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_pdbStructureHelpJButtonActionPerformed /** * Change the cursor to a hand cursor. * * @param evt */ private void exportPdbStructureJButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPdbStructureJButtonMouseEntered setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); }//GEN-LAST:event_exportPdbStructureJButtonMouseEntered /** * Change the cursor back to the default cursor. * * @param evt */ private void exportPdbStructureJButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exportPdbStructureJButtonMouseExited setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); }//GEN-LAST:event_exportPdbStructureJButtonMouseExited /** * Export the PDB structure. * * @param evt */ private void exportPdbStructureJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportPdbStructureJButtonActionPerformed new ExportGraphicsDialog( peptideShakerGUI, peptideShakerGUI.getNormalIcon(), peptideShakerGUI.getWaitingIcon(), true, pdbPanel, peptideShakerGUI.getLastSelectedFolder() ); // @TODO: use Jmol's export options... }//GEN-LAST:event_exportPdbStructureJButtonActionPerformed /** * Show the statistics popup menu. * * @param evt */ private void proteinTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_proteinTableMouseClicked if (evt.getButton() == MouseEvent.BUTTON3 && proteinTable.getRowCount() > 0) { final MouseEvent event = evt; JPopupMenu popupMenu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Statistics (beta)"); menuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { new XYPlottingDialog( peptideShakerGUI, proteinTable, proteinTable.getColumnName(proteinTable.columnAtPoint(event.getPoint())), XYPlottingDialog.PlottingDialogPlotType.densityPlot, proteinTableToolTips, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true ); } }); popupMenu.add(menuItem); popupMenu.show(proteinTable, evt.getX(), evt.getY()); } }//GEN-LAST:event_proteinTableMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backboneJButton; private javax.swing.JPanel contextMenuPdbChainsBackgroundPanel; private javax.swing.JPanel contextMenuPdbMatchesBackgroundPanel; private javax.swing.JPanel contextMenuPdbStructureBackgroundPanel; private javax.swing.JPanel contextMenuPeptidesBackgroundPanel; private javax.swing.JPanel contextMenuProteinsBackgroundPanel; private javax.swing.JButton exportPdbChainsJButton; private javax.swing.JButton exportPdbMatchesJButton; private javax.swing.JButton exportPdbStructureJButton; private javax.swing.JButton exportPeptidesJButton; private javax.swing.JButton exportProteinsJButton; private javax.swing.JButton labelsJButton; private javax.swing.JButton pdbChainHelpJButton; private javax.swing.JPanel pdbChainsJPanel; private javax.swing.JScrollPane pdbChainsJScrollPane; private javax.swing.JTable pdbChainsJTable; private javax.swing.JLayeredPane pdbChainsLayeredPane; private javax.swing.JPanel pdbChainsPanel; private javax.swing.JScrollPane pdbJScrollPane; private javax.swing.JLayeredPane pdbLayeredPane; private javax.swing.JButton pdbMatchesHelpJButton; private javax.swing.JPanel pdbMatchesJPanel; private javax.swing.JTable pdbMatchesJTable; private javax.swing.JLayeredPane pdbMatchesLayeredPane; private javax.swing.JPanel pdbMatchesPanel; private javax.swing.JPanel pdbOuterPanel; private javax.swing.JPanel pdbPanel; private javax.swing.JButton pdbStructureHelpJButton; private javax.swing.JPanel pdbStructureJPanel; private javax.swing.JLayeredPane pdbStructureLayeredPane; private javax.swing.JScrollPane peptideScrollPane; private javax.swing.JTable peptideTable; private javax.swing.JButton peptidesHelpJButton; private javax.swing.JPanel peptidesJPanel; private javax.swing.JLayeredPane peptidesLayeredPane; private javax.swing.JPanel peptidesPanel; private javax.swing.JButton playJButton; private javax.swing.JScrollPane proteinScrollPane; private javax.swing.JTable proteinTable; private javax.swing.JButton proteinsHelpJButton; private javax.swing.JPanel proteinsJPanel; private javax.swing.JLayeredPane proteinsLayeredPane; private javax.swing.JPanel proteinsPanel; private javax.swing.JButton ribbonJButton; // End of variables declaration//GEN-END:variables /** * Returns a list of keys of the displayed proteins. * * @return a list of keys of the displayed proteins */ public long[] getDisplayedProteins() { return proteinKeys; } /** * Returns a list of keys of the displayed peptides. * * @return a list of keys of the displayed peptides */ public long[] getDisplayedPeptides() { return peptideTableMap.values().stream().mapToLong(a -> a).toArray(); } /** * Updates the peptide selection according to the currently selected * protein. * * @param proteinIndex the row index of the protein */ private void updatedPeptideSelection(int proteinIndex) { if (proteinIndex != -1) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); DefaultTableModel dm = (DefaultTableModel) peptideTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); long proteinMatchKey = proteinKeys[proteinIndex]; ProteinMatch proteinMatch = peptideShakerGUI.getIdentification().getProteinMatch(proteinMatchKey); String proteinAccession = proteinMatch.getLeadingAccession(); peptideTableMap = new HashMap<>(); int index = 0; long[] peptideKeys = peptideShakerGUI.getIdentificationFeaturesGenerator().getSortedPeptideKeys(proteinMatchKey); for (long peptideKey : peptideKeys) { PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); PSParameter psParameter = (PSParameter) peptideMatch.getUrParam(PSParameter.dummy); if (!psParameter.getHidden()) { // find and add the peptide start and end indexes StartIndexes startIndexes = new StartIndexes( Arrays.stream(peptideMatch.getPeptide().getProteinMapping().get(proteinAccession)) .map(site -> site + 1) .boxed() .collect(Collectors.toCollection(ArrayList::new)) ); int proteinInferenceType = psParameter.getProteinInferenceGroupClass(); // @TODO: should be replaced by a table model!!! ((DefaultTableModel) peptideTable.getModel()).addRow(new Object[]{ index + 1, psParameter.getStarred(), proteinInferenceType, peptideShakerGUI.getDisplayFeaturesGenerator().getTaggedPeptideSequence(peptideMatch, true, true, true), startIndexes, false, psParameter.getMatchValidationLevel().getIndex() }); peptideTableMap.put(index + 1, peptideKey); index++; } } ((DefaultTableModel) peptideTable.getModel()).fireTableDataChanged(); String title = PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Peptides ("; IdentificationFeaturesGenerator identificationFeaturesGenerator = peptideShakerGUI.getIdentificationFeaturesGenerator(); int nValidatedPeptides = identificationFeaturesGenerator.getNValidatedPeptides(proteinMatchKey); int nConfidentPeptides = identificationFeaturesGenerator.getNConfidentPeptides(proteinMatchKey); int nPeptides = proteinMatch.getPeptideCount(); if (nConfidentPeptides > 0) { title += nValidatedPeptides + "/" + nPeptides + " - " + nConfidentPeptides + " confident, " + (nValidatedPeptides - nConfidentPeptides) + " doubtful"; } else { title += nValidatedPeptides + "/" + nPeptides; } title += ")" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING; ((TitledBorder) peptidesPanel.getBorder()).setTitle(title); peptidesPanel.repaint(); String proteinSequence = peptideShakerGUI.getSequenceProvider().getSequence(proteinAccession); peptideTable.getColumn("Start").setCellRenderer(new JSparklinesMultiIntervalChartTableCellRenderer( PlotOrientation.HORIZONTAL, (double) proteinSequence.length(), ((double) proteinSequence.length()) / 50, peptideShakerGUI.getSparklineColor())); ((JSparklinesMultiIntervalChartTableCellRenderer) peptideTable.getColumn("Start").getCellRenderer()).showReferenceLine(true, 0.02, Color.BLACK); ((JSparklinesMultiIntervalChartTableCellRenderer) peptideTable.getColumn("Start").getCellRenderer()).showNumberAndChart(true, TableProperties.getLabelWidth() - 10); // select the peptide in the table if (peptideTable.getRowCount() > 0) { int peptideRow = 0; long peptideKey = peptideShakerGUI.getSelectedPeptideKey(); if (peptideKey != NO_KEY) { peptideRow = getPeptideRow(peptideKey); } if (peptideRow != -1) { peptideTable.setRowSelectionInterval(peptideRow, peptideRow); peptideTable.scrollRectToVisible(peptideTable.getCellRect(peptideRow, 0, false)); peptideTableKeyReleased(null); } } this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } } /** * Displays the results in the result tables. */ public void displayResults() { progressDialog = new ProgressDialogX( peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true ); progressDialog.setPrimaryProgressCounterIndeterminate(true); progressDialog.setTitle("Updating Data. Please Wait..."); new Thread(new Runnable() { public void run() { try { progressDialog.setVisible(true); } catch (IndexOutOfBoundsException e) { // ignore } } }, "ProgressDialog").start(); new Thread("DisplayThread") { @Override public void run() { try { peptideShakerGUI.getIdentificationFeaturesGenerator().setProteinKeys(peptideShakerGUI.getMetrics().getProteinKeys()); proteinKeys = peptideShakerGUI.getIdentificationFeaturesGenerator().getProcessedProteinKeys(progressDialog, peptideShakerGUI.getFilterParameters()); setTableProperties(); // update the table model if (proteinTable.getModel() instanceof ProteinTableModel && ((ProteinTableModel) proteinTable.getModel()).isInstantiated()) { ((ProteinTableModel) proteinTable.getModel()).updateDataModel( peptideShakerGUI.getIdentification(), peptideShakerGUI.getIdentificationFeaturesGenerator(), peptideShakerGUI.getProteinDetailsProvider(), peptideShakerGUI.getSequenceProvider(), peptideShakerGUI.getGeneMaps(), peptideShakerGUI.getDisplayFeaturesGenerator(), proteinKeys ); } else { ProteinTableModel proteinTableModel = new ProteinTableModel( peptideShakerGUI.getIdentification(), peptideShakerGUI.getIdentificationFeaturesGenerator(), peptideShakerGUI.getProteinDetailsProvider(), peptideShakerGUI.getSequenceProvider(), peptideShakerGUI.getGeneMaps(), peptideShakerGUI.getDisplayFeaturesGenerator(), peptideShakerGUI.getExceptionHandler(), proteinKeys ); proteinTable.setModel(proteinTableModel); } setTableProperties(); showSparkLines(peptideShakerGUI.showSparklines()); ((DefaultTableModel) proteinTable.getModel()).fireTableDataChanged(); // update spectrum counting column header tooltip if (peptideShakerGUI.getSpectrumCountingParameters().getSelectedMethod() == SpectrumCountingMethod.EMPAI) { proteinTableToolTips.set(proteinTable.getColumn("MS2 Quant.").getModelIndex(), "Protein MS2 Quantification - emPAI"); } else if (peptideShakerGUI.getSpectrumCountingParameters().getSelectedMethod() == SpectrumCountingMethod.NSAF) { proteinTableToolTips.set(proteinTable.getColumn("MS2 Quant.").getModelIndex(), "Protein MS2 Quantification - NSAF"); } else { proteinTableToolTips.set(proteinTable.getColumn("MS2 Quant.").getModelIndex(), "Protein MS2 Quantification"); } if (peptideShakerGUI.getDisplayParameters().showScores()) { proteinTableToolTips.set(proteinTable.getColumnCount() - 2, "Protein Score"); } else { proteinTableToolTips.set(proteinTable.getColumnCount() - 2, "Protein Confidence"); } String title = PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Proteins ("; int nValidated = peptideShakerGUI.getIdentificationFeaturesGenerator().getNValidatedProteins(); int nConfident = peptideShakerGUI.getIdentificationFeaturesGenerator().getNConfidentProteins(); int nProteins = proteinTable.getRowCount(); if (nConfident > 0) { title += nValidated + "/" + nProteins + " - " + nConfident + " confident, " + (nValidated - nConfident) + " doubtful"; } else { title += nValidated + "/" + nProteins; } title += ")" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING; ((TitledBorder) proteinsPanel.getBorder()).setTitle(title); proteinsPanel.repaint(); updateProteinTableCellRenderers(); // enable the contextual export options exportProteinsJButton.setEnabled(true); exportPdbMatchesJButton.setEnabled(true); exportPdbChainsJButton.setEnabled(true); exportPeptidesJButton.setEnabled(true); exportPdbStructureJButton.setEnabled(true); peptideShakerGUI.setUpdated(PeptideShakerGUI.STRUCTURES_TAB_INDEX, true); progressDialog.setPrimaryProgressCounterIndeterminate(true); progressDialog.setTitle("Preparing 3D Structure Tab. Please Wait..."); peptideShakerGUI.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); progressDialog.setRunFinished(); new Thread(new Runnable() { public void run() { long proteinKey = peptideShakerGUI.getSelectedProteinKey(); long peptideKey = peptideShakerGUI.getSelectedPeptideKey(); String spectrumFile = peptideShakerGUI.getSelectedSpectrumFile(); String spectrumTitle = peptideShakerGUI.getSelectedSpectrumTitle(); proteinTableMouseReleased(null); peptideShakerGUI.setSelectedItems(proteinKey, peptideKey, spectrumFile, spectrumTitle); updateSelection(true); proteinTable.requestFocus(); } }, "UpdateSelectionThread").start(); } catch (Exception e) { progressDialog.setRunFinished(); peptideShakerGUI.catchException(e); } } }.start(); } /** * Returns the index of the peptide at the given row in the peptide table. * * @param row the row of interest * @return the index of the corresponding peptide */ private Integer getPeptideIndex(int row) { if (row != -1) { return (Integer) peptideTable.getValueAt(row, 0); } else { return -1; } } /** * Update the PDB table according to the selected protein in the protein * table. * * @param proteinKey the current protein key */ private void updatePdbTable(long aProteinKey) { final long proteinKey = aProteinKey; progressDialog = new ProgressDialogX( peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true ); progressDialog.setPrimaryProgressCounterIndeterminate(true); new Thread(new Runnable() { public void run() { progressDialog.setTitle("Getting PDB Data. Please Wait..."); try { progressDialog.setVisible(true); } catch (IndexOutOfBoundsException e) { // ignore } } }, "ProgressDialog").start(); new Thread("ExtractThread") { @Override public void run() { try { // get the accession number of the main match ProteinMatch proteinMatch = peptideShakerGUI.getIdentification().getProteinMatch(proteinKey); String tempAccession = proteinMatch.getLeadingAccession(); // find the pdb matches uniProtPdb = new FindPdbForUniprotAccessions(tempAccession, progressDialog); // @TODO: make it possible to cancel this process... // delete the previous matches DefaultTableModel dm = (DefaultTableModel) pdbMatchesJTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); dm = (DefaultTableModel) pdbChainsJTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); // clear the peptide to pdb mappings in the peptide table for (int i = 0; i < peptideTable.getRowCount() && !progressDialog.isRunCanceled(); i++) { peptideTable.setValueAt(false, i, peptideTable.getColumn("PDB").getModelIndex()); } int maxNumberOfChains = 1; // add the new matches to the pdb table for (int i = 0; i < uniProtPdb.getPdbs().size() && !progressDialog.isRunCanceled(); i++) { PdbParameter lParam = uniProtPdb.getPdbs().get(i); ((DefaultTableModel) pdbMatchesJTable.getModel()).addRow(new Object[]{ i + 1, addPdbDatabaseLink(lParam.getPdbaccession()), lParam.getTitle(), lParam.getExperiment_type(), lParam.getBlocks().length}); if (lParam.getBlocks().length > maxNumberOfChains) { maxNumberOfChains = lParam.getBlocks().length; } } if (!progressDialog.isRunCanceled()) { ((JSparklinesBarChartTableCellRenderer) pdbMatchesJTable.getColumn("Chains").getCellRenderer()).setMaxValue(maxNumberOfChains); if (!uniProtPdb.urlWasRead()) { ((TitledBorder) pdbMatchesPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Matches - Not Available Without Internet Connection!" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); } else { ((TitledBorder) pdbMatchesPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Matches (" + pdbMatchesJTable.getRowCount() + ")" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); } pdbMatchesPanel.repaint(); ((TitledBorder) pdbChainsPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Chains" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); pdbChainsPanel.repaint(); } progressDialog.setRunFinished(); } catch (Exception e) { progressDialog.setRunFinished(); peptideShakerGUI.catchException(e); } } }.start(); } /** * Updates the model type if the Jmol structure is currently visible. */ public void updateModelType() { if (jmolStructureShown) { if (ribbonModel) { jmolPanel.getViewer().evalString("select all; ribbon; backbone off"); } else if (backboneModel) { jmolPanel.getViewer().evalString("select all; backbone 100; ribbon off"); } } } /** * A simple class for displaying a Jmol viewer in a JPanel. */ public class JmolPanel extends JPanel { /** * The JmolViewer. */ private final JmolViewer viewer; /** * The current size of the JPanel. */ private final Dimension currentSize = new Dimension(); /** * The current rectangle of the JPanel. */ private final Rectangle rectClip = new Rectangle(); /** * Create a new JmolPanel. */ JmolPanel() { JmolAdapter adapter = new SmarterJmolAdapter(); viewer = JmolViewer.allocateViewer(this, adapter); } /** * Returns the JmolViewer. * * @return the JmolViewer */ public JmolViewer getViewer() { return viewer; } /** * Executes the given command line on the Jmol instance. * * @param rasmolScript the command line to execute */ public void executeCmd(String rasmolScript) { viewer.evalString(rasmolScript); } @Override public void paint(Graphics g) { getSize(currentSize); g.getClipBounds(rectClip); viewer.renderScreenImage(g, currentSize, rectClip); } } /** * Displays or hide sparklines in the tables. * * @param showSparkLines boolean indicating whether sparklines shall be * displayed or hidden */ public void showSparkLines(boolean showSparkLines) { ((JSparklinesArrayListBarChartTableCellRenderer) proteinTable.getColumn("Coverage").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesBarChartTableCellRenderer) proteinTable.getColumn("MS2 Quant.").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesBarChartTableCellRenderer) proteinTable.getColumn("MW").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesArrayListBarChartTableCellRenderer) proteinTable.getColumn("#Peptides").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesArrayListBarChartTableCellRenderer) proteinTable.getColumn("#Spectra").getCellRenderer()).showNumbers(!showSparkLines); String scoreColumnName = proteinTable.getColumnName(11); ((JSparklinesBarChartTableCellRenderer) proteinTable.getColumn(scoreColumnName).getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesBarChartTableCellRenderer) pdbMatchesJTable.getColumn("Chains").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesBarChartTableCellRenderer) pdbChainsJTable.getColumn("Coverage").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesIntervalChartTableCellRenderer) pdbChainsJTable.getColumn("PDB-Protein").getCellRenderer()).showNumbers(!showSparkLines); ((JSparklinesMultiIntervalChartTableCellRenderer) peptideTable.getColumn("Start").getCellRenderer()).showNumbers(!showSparkLines); proteinTable.revalidate(); proteinTable.repaint(); peptideTable.revalidate(); peptideTable.repaint(); pdbMatchesJTable.revalidate(); pdbMatchesJTable.repaint(); } /** * Transforms the PDB accession number into an HTML link to the PDB. Note * that this is a complete HTML with HTML and a href tags, where the main * use is to include it in the PDB tables. * * @param protein the PDB accession number to get the link for * @return the transformed accession number */ private String addPdbDatabaseLink(String pdbAccession) { return "<html><a href=\"" + getPDBAccesionLink(pdbAccession) + "\"><font color=\"" + TableProperties.getNotSelectedRowHtmlTagFontColor() + "\">" + pdbAccession + "</font></a></html>"; } /** * Returns the PDB accession number as a web link to the given structure at * https://www.rcsb.org. * * @param pdbAccession the PDB accession number * @return the PDB accession web link */ public String getPDBAccesionLink(String pdbAccession) { return "https://www.rcsb.org/pdb/explore/explore.do?structureId=" + pdbAccession; } /** * Update the peptide to PDB mappings. */ private void updatePeptideToPdbMapping() { setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); // clear the old mappings for (int i = 0; i < peptideTable.getRowCount() && !progressDialog.isRunCanceled(); i++) { peptideTable.setValueAt(false, i, peptideTable.getColumn("PDB").getModelIndex()); } jmolPanel.getViewer().evalString("select all; color grey"); // update the peptide selection int selectedChainIndex = (Integer) pdbChainsJTable.getValueAt(pdbChainsJTable.getSelectedRow(), 0); String currentChain = chains[selectedChainIndex - 1].getBlock(); // get the selected protein match SelfUpdatingTableModel tableModel = (SelfUpdatingTableModel) proteinTable.getModel(); int proteinIndex = tableModel.getViewIndex(proteinTable.getSelectedRow()); long proteinKey = proteinKeys[proteinIndex]; ProteinMatch proteinMatch = peptideShakerGUI.getIdentification().getProteinMatch(proteinKey); peptidePdbArray = new ArrayList<>(); // iterate the peptide table and highlight the covered areas for (int i = 0; i < peptideTable.getRowCount() && !progressDialog.isRunCanceled(); i++) { long peptideKey = peptideTableMap.get(getPeptideIndex(i)); PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); String peptideSequence = peptideMatch.getPeptide().getSequence(); for (int peptideStart : peptideMatch.getPeptide().getProteinMapping().get(proteinMatch.getLeadingAccession())) { int peptideEnd = peptideStart + peptideSequence.length(); jmolPanel.getViewer().evalString("select resno >=" + (peptideStart + 1 - chains[selectedChainIndex - 1].getDifference()) + " and resno <=" + (peptideEnd - chains[selectedChainIndex - 1].getDifference()) + " and chain = " + currentChain + "; color green"); if (peptideStart >= chains[selectedChainIndex - 1].getStartProtein() && peptideEnd <= chains[selectedChainIndex - 1].getEndProtein()) {//if (aminoAcidPattern.getIndexes(chainSequence, peptideShakerGUI.getIdentificationParameters().getSequenceMatchingParameters()).length != 0) { peptideTable.setValueAt(true, i, peptideTable.getColumn("PDB").getModelIndex()); peptidePdbArray.add(peptideKey); } if (progressDialog.isRunCanceled()) { break; } } } // highlight the selected peptide long peptideKey = peptideTableMap.get(getPeptideIndex(peptideTable.getSelectedRow())); PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); String peptideSequence = peptideMatch.getPeptide().getSequence(); for (int peptideStart : peptideMatch.getPeptide().getProteinMapping().get(proteinMatch.getLeadingAccession())) { if (progressDialog.isRunCanceled()) { break; } int peptideEnd = peptideStart + peptideSequence.length(); jmolPanel.getViewer().evalString( "select resno >=" + (peptideStart + 1 - chains[selectedChainIndex - 1].getDifference()) + " and resno <=" + (peptideEnd - chains[selectedChainIndex - 1].getDifference()) + " and chain = " + currentChain + "; color blue" ); } // remove old labels jmolPanel.getViewer().evalString("select all; label off"); DisplayParameters displayParameters = peptideShakerGUI.getDisplayParameters(); IdentificationParameters identificationParameters = peptideShakerGUI.getIdentificationParameters(); SequenceProvider sequenceProvider = peptideShakerGUI.getSequenceProvider(); ModificationParameters modificationParameters = identificationParameters.getSearchParameters().getModificationParameters(); SequenceMatchingParameters modificationSequenceMatchingParameters = identificationParameters.getModificationLocalizationParameters().getSequenceMatchingParameters(); // annotate the modified covered residues for (int i = 0; i < peptideTable.getRowCount() && !progressDialog.isRunCanceled(); i++) { peptideKey = peptideTableMap.get(getPeptideIndex(i)); peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); Peptide peptide = peptideMatch.getPeptide(); peptideSequence = peptide.getSequence(); String[] variableModifications = peptide.getIndexedVariableModifications(); String[] fixedModifications = peptide.getFixedModifications( modificationParameters, sequenceProvider, modificationSequenceMatchingParameters ); for (int peptideStart : peptide.getProteinMapping().get(proteinMatch.getLeadingAccession())) { if (progressDialog.isRunCanceled()) { break; } int peptideEnd = peptideStart + peptideSequence.length() - 1; for (int j = peptideStart; j < peptideEnd && !progressDialog.isRunCanceled(); j++) { String modName = variableModifications[j - peptideStart]; if (modName != null && displayParameters.isDisplayedPTM(modName)) { Color ptmColor = new Color(peptideShakerGUI.getIdentificationParameters().getSearchParameters().getModificationParameters().getColor(modName)); jmolPanel.getViewer().evalString( "select resno =" + (j - chains[selectedChainIndex - 1].getDifference()) + " and chain = " + currentChain + "; color [" + ptmColor.getRed() + "," + ptmColor.getGreen() + "," + ptmColor.getBlue() + "]" ); if (showModificationLabels) { jmolPanel.getViewer().evalString( "select resno =" + (j - chains[selectedChainIndex - 1].getDifference()) + " and chain = " + currentChain + " and *.ca; color [" + ptmColor.getRed() + "," + ptmColor.getGreen() + "," + ptmColor.getBlue() + "];" + "label " + modName ); } } modName = fixedModifications[j - peptideStart]; if (modName != null && displayParameters.isDisplayedPTM(modName)) { Color ptmColor = new Color(peptideShakerGUI.getIdentificationParameters().getSearchParameters().getModificationParameters().getColor(modName)); jmolPanel.getViewer().evalString( "select resno =" + (j - chains[selectedChainIndex - 1].getDifference()) + " and chain = " + currentChain + "; color [" + ptmColor.getRed() + "," + ptmColor.getGreen() + "," + ptmColor.getBlue() + "]" ); if (showModificationLabels) { jmolPanel.getViewer().evalString( "select resno =" + (j - chains[selectedChainIndex - 1].getDifference()) + " and chain = " + currentChain + " and *.ca; color [" + ptmColor.getRed() + "," + ptmColor.getGreen() + "," + ptmColor.getBlue() + "];" + "label " + modName ); } } } } } // resort the peptide table, required if sorted on the pdb column and the structure is changed peptideTable.getRowSorter().allRowsChanged(); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } /** * Update the main match for the given row in the protein table. * * @param mainMatch the protein match to use * @param proteinInferenceType the protein inference group type */ public void updateMainMatch(String mainMatch, int proteinInferenceType) { if (proteinTable.getRowCount() > 0) { DefaultTableModel dm = (DefaultTableModel) proteinTable.getModel(); dm.fireTableDataChanged(); reselect(); } } /** * Turns the spinning of the model on or off. * * @param spin if true the spinning is turned on. */ public void spinModel(boolean spin) { if (spin) { jmolPanel.getViewer().evalString("set spin y 20; spin"); } else { jmolPanel.getViewer().evalString("spin off"); } } /** * Returns the protein table. * * @return the protein table */ public JTable getProteinTable() { return proteinTable; } /** * Returns the peptide table. * * @return the peptide table */ public JTable getPeptideTable() { return peptideTable; } /** * Hides or displays the score columns in the protein and peptide tables. */ public void updateScores() { ((ProteinTableModel) proteinTable.getModel()).showScores(peptideShakerGUI.getDisplayParameters().showScores()); ((DefaultTableModel) proteinTable.getModel()).fireTableStructureChanged(); setTableProperties(); if (peptideShakerGUI.getSelectedTab() == PeptideShakerGUI.STRUCTURES_TAB_INDEX) { reselect(); } if (peptideShakerGUI.getDisplayParameters().showScores()) { proteinTableToolTips.set(proteinTable.getColumnCount() - 2, "Protein Score"); } else { proteinTableToolTips.set(proteinTable.getColumnCount() - 2, "Protein Confidence"); } updateProteinTableCellRenderers(); } /** * Update the PTM color coding. */ public void updateModificationColors() { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); // update the peptide table for (int i = 0; i < peptideTable.getRowCount(); i++) { long peptideKey = peptideTableMap.get(getPeptideIndex(i)); PeptideMatch peptideMatch = peptideShakerGUI.getIdentification().getPeptideMatch(peptideKey); String modifiedSequence = peptideShakerGUI.getDisplayFeaturesGenerator().getTaggedPeptideSequence(peptideMatch, true, true, true); peptideTable.setValueAt(modifiedSequence, i, peptideTable.getColumn("Sequence").getModelIndex()); } if (peptideTable.getRowCount() > 0) { // update the 3D structure peptideTableMouseReleased(null); } this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } /** * Update the protein inference type for the currently selected peptide. * * @param proteinInferenceType the protein inference type */ public void updatePeptideProteinInference(int proteinInferenceType) { peptideTable.setValueAt( proteinInferenceType, peptideTable.getSelectedRow(), peptideTable.getColumn("PI").getModelIndex() ); } /** * Export the table contents to the clipboard. * * @param index the table index type */ private void copyTableContentToClipboardOrFile( TableIndex index ) throws IOException { final TableIndex tableIndex = index; if (tableIndex == TableIndex.PROTEIN_TABLE || tableIndex == TableIndex.PEPTIDE_TABLE) { HashMap<String, ArrayList<ExportFeature>> exportFeatures = new HashMap<>(); ArrayList<ExportFeature> sectionContent = new ArrayList<>(); String textFileFilterDescription = "Tab separated text file (.txt)"; String gzipFileFilterDescription = "Gzipped tab separated text file (.gz)"; String excelFileFilterDescription = "Excel Workbook (.xls)"; String lastSelectedFolderPath = peptideShakerGUI.getLastSelectedFolder().getLastSelectedFolder(); String exportName = "Export"; switch (tableIndex) { case PROTEIN_TABLE: exportName = "Protein table"; break; case PEPTIDE_TABLE: exportName = "Peptide table"; break; default: break; } FileAndFileFilter selectedFileAndFilter = FileChooserUtil.getUserSelectedFile( this, new String[]{".xls", ".txt", ".gz"}, new String[]{excelFileFilterDescription, textFileFilterDescription, gzipFileFilterDescription}, "Export Report", lastSelectedFolderPath, exportName, false, true, false, 1 ); if (selectedFileAndFilter != null) { final File selectedFile = selectedFileAndFilter.getFile(); final ExportFormat exportFormat; final boolean gzip; if (selectedFileAndFilter.getFileFilter().getDescription().equalsIgnoreCase(textFileFilterDescription)) { exportFormat = ExportFormat.text; gzip = false; } else if (selectedFileAndFilter.getFileFilter().getDescription().equalsIgnoreCase(gzipFileFilterDescription)) { exportFormat = ExportFormat.text; gzip = true; } else { exportFormat = ExportFormat.excel; gzip = false; } progressDialog = new ProgressDialogX( peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true ); progressDialog.setTitle("Exporting Data. Please Wait..."); final String filePath = selectedFile.getPath(); new Thread(new Runnable() { public void run() { try { progressDialog.setVisible(true); } catch (IndexOutOfBoundsException e) { // ignore } } }, "ProgressDialog").start(); new Thread("ExportThread") { @Override public void run() { try { switch (tableIndex) { case PROTEIN_TABLE: sectionContent.add(PsProteinFeature.starred); sectionContent.add(PsProteinFeature.pi); sectionContent.add(PsProteinFeature.accession); sectionContent.add(PsProteinFeature.protein_description); sectionContent.add(PsProteinFeature.protein_group); sectionContent.add(PsProteinFeature.descriptions); sectionContent.add(PsProteinFeature.other_proteins); sectionContent.add(PsProteinFeature.chromosome); sectionContent.add(PsProteinFeature.coverage); sectionContent.add(PsProteinFeature.confident_coverage); sectionContent.add(PsProteinFeature.all_coverage); sectionContent.add(PsProteinFeature.possible_coverage); sectionContent.add(PsProteinFeature.validated_peptides); sectionContent.add(PsProteinFeature.peptides); sectionContent.add(PsProteinFeature.unique_peptides); sectionContent.add(PsProteinFeature.unique_validated_peptides); sectionContent.add(PsProteinFeature.validated_psms); sectionContent.add(PsProteinFeature.psms); sectionContent.add(PsProteinFeature.spectrum_counting_nsaf); sectionContent.add(PsProteinFeature.spectrum_counting_empai); sectionContent.add(PsProteinFeature.spectrum_counting_nsaf_percent); sectionContent.add(PsProteinFeature.spectrum_counting_empai_percent); sectionContent.add(PsProteinFeature.spectrum_counting_nsaf_ppm); sectionContent.add(PsProteinFeature.spectrum_counting_empai_ppm); sectionContent.add(PsProteinFeature.spectrum_counting_nsaf_fmol); sectionContent.add(PsProteinFeature.spectrum_counting_empai_fmol); sectionContent.add(PsProteinFeature.mw); sectionContent.add(PsProteinFeature.confidence); sectionContent.add(PsProteinFeature.validated); exportFeatures.put(PsProteinFeature.type, sectionContent); ExportScheme validatedProteinReport = new ExportScheme( "Protein Table", false, exportFeatures, "\t", true, true, 0, false, false, false ); PSExportFactory.writeExport( validatedProteinReport, selectedFile, exportFormat, gzip, peptideShakerGUI.getProjectParameters().getProjectUniqueName(), peptideShakerGUI.getProjectDetails(), peptideShakerGUI.getIdentification(), peptideShakerGUI.getIdentificationFeaturesGenerator(), peptideShakerGUI.getGeneMaps(), getDisplayedProteins(), null, null, peptideShakerGUI.getDisplayParameters().getnAASurroundingPeptides(), peptideShakerGUI.getIdentificationParameters(), peptideShakerGUI.getSequenceProvider(), peptideShakerGUI.getProteinDetailsProvider(), peptideShakerGUI.getSpectrumProvider(), peptideShakerGUI.getSpectrumCountingParameters(), progressDialog ); break; case PEPTIDE_TABLE: sectionContent.add(PsPeptideFeature.starred); sectionContent.add(PsPeptideFeature.pi); sectionContent.add(PsPeptideFeature.accessions); sectionContent.add(PsPeptideFeature.protein_description); sectionContent.add(PsPeptideFeature.protein_groups); sectionContent.add(PsPeptideFeature.sequence); sectionContent.add(PsPeptideFeature.modified_sequence); sectionContent.add(PsPeptideFeature.position); sectionContent.add(PsPeptideFeature.aaBefore); sectionContent.add(PsPeptideFeature.aaAfter); sectionContent.add(PsPeptideFeature.missed_cleavages); sectionContent.add(PsPeptideFeature.variable_ptms); sectionContent.add(PsPeptideFeature.fixed_ptms); sectionContent.add(PsPeptideFeature.psms); sectionContent.add(PsPeptideFeature.validated_psms); sectionContent.add(PsPeptideFeature.confidence); sectionContent.add(PsPeptideFeature.validated); exportFeatures.put(PsPeptideFeature.type, sectionContent); validatedProteinReport = new ExportScheme( "Peptide Table", false, exportFeatures, "\t", true, true, 0, false, false, false ); PSExportFactory.writeExport( validatedProteinReport, selectedFile, exportFormat, gzip, peptideShakerGUI.getProjectParameters().getProjectUniqueName(), peptideShakerGUI.getProjectDetails(), peptideShakerGUI.getIdentification(), peptideShakerGUI.getIdentificationFeaturesGenerator(), peptideShakerGUI.getGeneMaps(), null, getDisplayedPeptides(), null, peptideShakerGUI.getDisplayParameters().getnAASurroundingPeptides(), peptideShakerGUI.getIdentificationParameters(), peptideShakerGUI.getSequenceProvider(), peptideShakerGUI.getProteinDetailsProvider(), peptideShakerGUI.getSpectrumProvider(), peptideShakerGUI.getSpectrumCountingParameters(), progressDialog ); break; default: break; } boolean processCancelled = progressDialog.isRunCanceled(); progressDialog.setRunFinished(); if (!processCancelled) { JOptionPane.showMessageDialog( peptideShakerGUI, "Data copied to file:\n" + filePath, "Data Exported", JOptionPane.INFORMATION_MESSAGE ); } } catch (FileNotFoundException e) { progressDialog.setRunFinished(); JOptionPane.showMessageDialog( peptideShakerGUI, "An error occurred while generating the output. Please make sure " + "that the destination file is not opened by another application.", "Output Error", JOptionPane.ERROR_MESSAGE ); e.printStackTrace(); } catch (IllegalArgumentException e) { if (e.getMessage().contains("Invalid row number (65536)")) { progressDialog.setRunFinished(); JOptionPane.showMessageDialog( peptideShakerGUI, "An error occurred while generating the output. This format can contain only 65,535 lines.\n" // @TODO: update the excel export library? + "Please use a text export instead.", "Output Error", JOptionPane.ERROR_MESSAGE ); e.printStackTrace(); } else { progressDialog.setRunFinished(); JOptionPane.showMessageDialog( peptideShakerGUI, "An error occurred while generating the output.", "Output Error", JOptionPane.ERROR_MESSAGE ); e.printStackTrace(); } } catch (Exception e) { progressDialog.setRunFinished(); JOptionPane.showMessageDialog( peptideShakerGUI, "An error occurred while generating the output.", "Output Error", JOptionPane.ERROR_MESSAGE ); e.printStackTrace(); } } }.start(); } } else if (tableIndex == TableIndex.PDB_MATCHES || tableIndex == TableIndex.PDB_CHAINS) { // get the file to send the output to File selectedFile = peptideShakerGUI.getUserSelectedFile( "pdb_details.txt", ".txt", "Tab separated text file (.txt)", "Export...", false ); if (selectedFile != null) { if (tableIndex == TableIndex.PDB_CHAINS) { try ( SimpleFileWriter writer = new SimpleFileWriter(selectedFile, false)) { writer.writeLine( "", "Chain", "PDB-Start", "PDB-End", "Coverage" ); for (int i = 0; i < pdbChainsJTable.getRowCount(); i++) { XYDataPoint pdbCoverage = (XYDataPoint) pdbChainsJTable.getValueAt(i, 2); writer.writeLine( pdbChainsJTable.getValueAt(i, 0).toString(), pdbChainsJTable.getValueAt(i, 1).toString(), Double.toString(pdbCoverage.getX()), Double.toString(pdbCoverage.getY()), pdbChainsJTable.getValueAt(i, 3).toString() ); } JOptionPane.showMessageDialog( peptideShakerGUI, "Data copied to file:\n" + selectedFile.getPath(), "Data Exported", JOptionPane.INFORMATION_MESSAGE ); } } else if (tableIndex == TableIndex.PDB_MATCHES) { try ( BufferedWriter writer = new BufferedWriter(new FileWriter(selectedFile))) { Util.tableToFile( pdbMatchesJTable, "\t", null, true, writer ); JOptionPane.showMessageDialog( peptideShakerGUI, "Data copied to file:\n" + selectedFile.getPath(), "Data Exported", JOptionPane.INFORMATION_MESSAGE ); } } } } } /** * Reselect the protein, peptide and PSM. */ private void reselect() { long proteinKey = peptideShakerGUI.getSelectedProteinKey(); long peptideKey = peptideShakerGUI.getSelectedPeptideKey(); if (proteinKey != NO_KEY) { int proteinRow = getProteinRow(proteinKey); if (proteinRow != -1 && proteinRow < proteinTable.getRowCount()) { proteinTable.setRowSelectionInterval(proteinRow, proteinRow); } } if (peptideKey != NO_KEY) { int peptideRow = getPeptideRow(peptideKey); if (peptideRow != -1) { peptideTable.setRowSelectionInterval(peptideRow, peptideRow); } } } /** * Update the selected protein and peptide. * * @param scrollToVisible if true the table also scrolls to make the * selected row visible */ public void updateSelection(boolean scrollToVisible) { int proteinRow = 0; long proteinKey = peptideShakerGUI.getSelectedProteinKey(); long peptideKey = peptideShakerGUI.getSelectedPeptideKey(); String spectrumFile = peptideShakerGUI.getSelectedSpectrumFile(); String spectrumTitle = peptideShakerGUI.getSelectedSpectrumTitle(); Identification identification = peptideShakerGUI.getIdentification(); if (proteinKey == NO_KEY && peptideKey == NO_KEY && spectrumFile != null && spectrumTitle != null) { long psmKey = SpectrumMatch.getKey(spectrumFile, spectrumTitle); SpectrumMatch spectrumMatch = identification.getSpectrumMatch(psmKey); if (spectrumMatch != null && spectrumMatch.getBestPeptideAssumption() != null) { Peptide peptide = spectrumMatch.getBestPeptideAssumption().getPeptide(); peptideKey = peptide.getMatchingKey(peptideShakerGUI.getIdentificationParameters().getSequenceMatchingParameters()); } } if (proteinKey == NO_KEY && peptideKey != NO_KEY) { final long peptideKeyFinal = peptideKey; ProteinMatch tempProteinMatch = identification.getProteinIdentification().parallelStream() .map(key -> identification.getProteinMatch(key)) .filter(proteinMatch -> Arrays.stream(proteinMatch.getPeptideMatchesKeys()) .anyMatch(key -> key == peptideKeyFinal)) .findAny() .orElse(null); if (tempProteinMatch != null) { proteinKey = tempProteinMatch.getKey(); peptideShakerGUI.setSelectedItems(proteinKey, peptideKey, spectrumFile, spectrumTitle); } if (proteinKey != NO_KEY) { proteinRow = getProteinRow(proteinKey); } if (proteinKeys.length == 0) { clearData(); return; } if (proteinRow == -1) { peptideShakerGUI.resetSelectedItems(); proteinTableMouseReleased(null); } else if (proteinTable.getSelectedRow() != proteinRow) { proteinTable.setRowSelectionInterval(proteinRow, proteinRow); if (scrollToVisible) { proteinTable.scrollRectToVisible(proteinTable.getCellRect(proteinRow, 0, false)); } proteinTableMouseReleased(null); } int peptideRow = 0; if (peptideKey != NO_KEY) { peptideRow = getPeptideRow(peptideKey); } if (peptideTable.getSelectedRow() != peptideRow && peptideRow != -1) { peptideTable.setRowSelectionInterval(peptideRow, peptideRow); if (scrollToVisible) { peptideTable.scrollRectToVisible(peptideTable.getCellRect(peptideRow, 0, false)); } peptideTableMouseReleased(null); } if (spectrumFile != null && spectrumTitle != null) { peptideShakerGUI.setSelectedItems( peptideShakerGUI.getSelectedProteinKey(), peptideShakerGUI.getSelectedPeptideKey(), spectrumFile, spectrumTitle ); } } } /** * Provides to the PeptideShakerGUI instance the currently selected protein, * peptide and PSM. */ public void newItemSelection() { long proteinKey = NO_KEY; long peptideKey = NO_KEY; String spectrumFile = null; String spectrumTitle = null; if (proteinTable.getSelectedRow() != -1) { SelfUpdatingTableModel tableModel = (SelfUpdatingTableModel) proteinTable.getModel(); int proteinIndex = tableModel.getViewIndex(proteinTable.getSelectedRow()); proteinKey = proteinKeys[proteinIndex]; } if (peptideTable.getSelectedRow() != -1) { peptideKey = peptideTableMap.get(getPeptideIndex(peptideTable.getSelectedRow())); } if (proteinKey != peptideShakerGUI.getSelectedProteinKey() || peptideKey != peptideShakerGUI.getSelectedPeptideKey()) { long psmKey = peptideShakerGUI.getDefaultPsmSelection(peptideKey); SpectrumMatch spectrumMatch = peptideShakerGUI.getIdentification().getSpectrumMatch(psmKey); spectrumFile = spectrumMatch.getSpectrumFile(); spectrumTitle = spectrumMatch.getSpectrumTitle(); } peptideShakerGUI.setSelectedItems(proteinKey, peptideKey, spectrumFile, spectrumTitle); } /** * Returns the row of a desired protein. * * @param proteinKey the key of the protein * * @return the row of the desired protein */ private int getProteinRow(long proteinKey) { int modelIndex = IntStream.range(0, proteinKeys.length) .filter(i -> proteinKeys[i] == proteinKey) .findAny() .orElse(-1); return modelIndex == -1 ? -1 : ((SelfUpdatingTableModel) proteinTable.getModel()).getRowNumber(modelIndex); } /** * Returns the row of a desired peptide. * * @param peptideKey the key of the peptide * * @return the row of the desired peptide */ private int getPeptideRow(final long peptideKey) { int index = -1; for (int key : peptideTableMap.keySet()) { if (peptideTableMap.get(key).equals(peptideKey)) { index = key; break; } } for (int row = 0; row < peptideTable.getRowCount(); row++) { if ((Integer) peptideTable.getValueAt(row, 0) == index) { return row; } } return -1; // only works if/when the peptide table model is transformed into a SelfUpdatingTableModel // int modelIndex = peptideTableMap.entrySet().stream() // .filter(entry -> entry.getValue() == peptideKey) // .map(entry -> entry.getKey()) // .findAny() // .orElse(-1); // // return modelIndex == -1 ? -1 : ((SelfUpdatingTableModel) peptideTable.getModel()).getRowNumber(modelIndex); } /** * Clear all the data. */ public void clearData() { DefaultTableModel dm = (DefaultTableModel) proteinTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); dm = (DefaultTableModel) peptideTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); dm = (DefaultTableModel) pdbMatchesJTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); dm = (DefaultTableModel) pdbChainsJTable.getModel(); dm.getDataVector().removeAllElements(); dm.fireTableDataChanged(); peptideTableMap = new HashMap<>(); peptidePdbArray = new ArrayList<>(); currentlyDisplayedPdbFile = null; // empty the jmol panel if (jmolStructureShown) { jmolPanel = new JmolPanel(); pdbPanel.removeAll(); pdbPanel.add(jmolPanel); pdbPanel.revalidate(); pdbPanel.repaint(); jmolStructureShown = false; currentlyDisplayedPdbFile = null; ((TitledBorder) pdbOuterPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "PDB Structure" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); pdbOuterPanel.repaint(); } ((TitledBorder) proteinsPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Proteins" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); ((TitledBorder) peptidesPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Peptides" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); ((TitledBorder) pdbMatchesPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Peptide Spectrum Matches" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); ((TitledBorder) pdbChainsPanel.getBorder()).setTitle( PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING + "Spectrum & Fragment Ions" + PeptideShakerGUI.TITLED_BORDER_HORIZONTAL_PADDING ); } /** * Update the protein table cell renderers. */ private void updateProteinTableCellRenderers() { if (peptideShakerGUI.getIdentification() != null) { ((JSparklinesArrayListBarChartTableCellRenderer) proteinTable.getColumn("#Peptides").getCellRenderer()).setMaxValue(peptideShakerGUI.getMetrics().getMaxNPeptides()); ((JSparklinesArrayListBarChartTableCellRenderer) proteinTable.getColumn("#Spectra").getCellRenderer()).setMaxValue(peptideShakerGUI.getMetrics().getMaxNPsms()); ((JSparklinesBarChartTableCellRenderer) proteinTable.getColumn("MS2 Quant.").getCellRenderer()).setMaxValue(peptideShakerGUI.getMetrics().getMaxSpectrumCounting()); ((JSparklinesBarChartTableCellRenderer) proteinTable.getColumn("MW").getCellRenderer()).setMaxValue(peptideShakerGUI.getMetrics().getMaxMW()); String scoreColumnName = proteinTable.getColumnName(11); ((JSparklinesBarChartTableCellRenderer) proteinTable.getColumn(scoreColumnName).getCellRenderer()).setMaxValue(100.0); showSparkLines(peptideShakerGUI.showSparklines()); } } /** * Deactivates the self updating tables. * * @param selfUpdating boolean indicating whether the tables should update * their content */ public void selfUpdating(boolean selfUpdating) { if (proteinTable.getModel() instanceof SelfUpdatingTableModel) { ((SelfUpdatingTableModel) proteinTable.getModel()).setSelfUpdating(selfUpdating); } if (peptideTable.getModel() instanceof SelfUpdatingTableModel) { ((SelfUpdatingTableModel) peptideTable.getModel()).setSelfUpdating(selfUpdating); } } }
44.996994
294
0.612619
71e98796fb455e71e55a59ff72f0a47dfba95107
116,454
package com.huaweicloud.sdk.iotda.v5; import com.huaweicloud.sdk.core.http.FieldExistence; import com.huaweicloud.sdk.core.http.HttpMethod; import com.huaweicloud.sdk.core.http.HttpRequestDef; import com.huaweicloud.sdk.core.http.LocationType; import com.huaweicloud.sdk.iotda.v5.model.*; import java.util.List; import java.util.Map; import java.time.OffsetDateTime; @SuppressWarnings("unchecked") public class IoTDAMeta { public static final HttpRequestDef<CreateAccessCodeRequest, CreateAccessCodeResponse> createAccessCode = genForcreateAccessCode(); private static HttpRequestDef<CreateAccessCodeRequest, CreateAccessCodeResponse> genForcreateAccessCode() { // basic HttpRequestDef.Builder<CreateAccessCodeRequest, CreateAccessCodeResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateAccessCodeRequest.class, CreateAccessCodeResponse.class) .withName("CreateAccessCode") .withUri("/v5/iot/{project_id}/auth/accesscode") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateAccessCodeRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, CreateAccessCodeRequestBody.class, f -> f.withMarshaller(CreateAccessCodeRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<AddQueueRequest, AddQueueResponse> addQueue = genForaddQueue(); private static HttpRequestDef<AddQueueRequest, AddQueueResponse> genForaddQueue() { // basic HttpRequestDef.Builder<AddQueueRequest, AddQueueResponse> builder = HttpRequestDef.builder(HttpMethod.POST, AddQueueRequest.class, AddQueueResponse.class) .withName("AddQueue") .withUri("/v5/iot/{project_id}/amqp-queues") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(AddQueueRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, QueueInfo.class, f -> f.withMarshaller(AddQueueRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<BatchShowQueueRequest, BatchShowQueueResponse> batchShowQueue = genForbatchShowQueue(); private static HttpRequestDef<BatchShowQueueRequest, BatchShowQueueResponse> genForbatchShowQueue() { // basic HttpRequestDef.Builder<BatchShowQueueRequest, BatchShowQueueResponse> builder = HttpRequestDef.builder(HttpMethod.GET, BatchShowQueueRequest.class, BatchShowQueueResponse.class) .withName("BatchShowQueue") .withUri("/v5/iot/{project_id}/amqp-queues") .withContentType("application/json"); // requests builder.withRequestField("queue_name", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(BatchShowQueueRequest::getQueueName, (req, v) -> { req.setQueueName(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(BatchShowQueueRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(BatchShowQueueRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(BatchShowQueueRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(BatchShowQueueRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteQueueRequest, DeleteQueueResponse> deleteQueue = genFordeleteQueue(); private static HttpRequestDef<DeleteQueueRequest, DeleteQueueResponse> genFordeleteQueue() { // basic HttpRequestDef.Builder<DeleteQueueRequest, DeleteQueueResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteQueueRequest.class, DeleteQueueResponse.class) .withName("DeleteQueue") .withUri("/v5/iot/{project_id}/amqp-queues/{queue_id}") .withContentType("application/json"); // requests builder.withRequestField("queue_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteQueueRequest::getQueueId, (req, v) -> { req.setQueueId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteQueueRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteQueueResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ShowQueueRequest, ShowQueueResponse> showQueue = genForshowQueue(); private static HttpRequestDef<ShowQueueRequest, ShowQueueResponse> genForshowQueue() { // basic HttpRequestDef.Builder<ShowQueueRequest, ShowQueueResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowQueueRequest.class, ShowQueueResponse.class) .withName("ShowQueue") .withUri("/v5/iot/{project_id}/amqp-queues/{queue_id}") .withContentType("application/json"); // requests builder.withRequestField("queue_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowQueueRequest::getQueueId, (req, v) -> { req.setQueueId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowQueueRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<AddApplicationRequest, AddApplicationResponse> addApplication = genForaddApplication(); private static HttpRequestDef<AddApplicationRequest, AddApplicationResponse> genForaddApplication() { // basic HttpRequestDef.Builder<AddApplicationRequest, AddApplicationResponse> builder = HttpRequestDef.builder(HttpMethod.POST, AddApplicationRequest.class, AddApplicationResponse.class) .withName("AddApplication") .withUri("/v5/iot/{project_id}/apps") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(AddApplicationRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, AddApplication.class, f -> f.withMarshaller(AddApplicationRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteApplicationRequest, DeleteApplicationResponse> deleteApplication = genFordeleteApplication(); private static HttpRequestDef<DeleteApplicationRequest, DeleteApplicationResponse> genFordeleteApplication() { // basic HttpRequestDef.Builder<DeleteApplicationRequest, DeleteApplicationResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteApplicationRequest.class, DeleteApplicationResponse.class) .withName("DeleteApplication") .withUri("/v5/iot/{project_id}/apps/{app_id}") .withContentType("application/json"); // requests builder.withRequestField("app_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteApplicationRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteApplicationRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteApplicationResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ShowApplicationRequest, ShowApplicationResponse> showApplication = genForshowApplication(); private static HttpRequestDef<ShowApplicationRequest, ShowApplicationResponse> genForshowApplication() { // basic HttpRequestDef.Builder<ShowApplicationRequest, ShowApplicationResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowApplicationRequest.class, ShowApplicationResponse.class) .withName("ShowApplication") .withUri("/v5/iot/{project_id}/apps/{app_id}") .withContentType("application/json"); // requests builder.withRequestField("app_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowApplicationRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowApplicationRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowApplicationsRequest, ShowApplicationsResponse> showApplications = genForshowApplications(); private static HttpRequestDef<ShowApplicationsRequest, ShowApplicationsResponse> genForshowApplications() { // basic HttpRequestDef.Builder<ShowApplicationsRequest, ShowApplicationsResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowApplicationsRequest.class, ShowApplicationsResponse.class) .withName("ShowApplications") .withUri("/v5/iot/{project_id}/apps") .withContentType("application/json"); // requests builder.withRequestField("default_app", LocationType.Query, FieldExistence.NULL_IGNORE, Boolean.class, f -> f.withMarshaller(ShowApplicationsRequest::getDefaultApp, (req, v) -> { req.setDefaultApp(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowApplicationsRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateAsyncCommandRequest, CreateAsyncCommandResponse> createAsyncCommand = genForcreateAsyncCommand(); private static HttpRequestDef<CreateAsyncCommandRequest, CreateAsyncCommandResponse> genForcreateAsyncCommand() { // basic HttpRequestDef.Builder<CreateAsyncCommandRequest, CreateAsyncCommandResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateAsyncCommandRequest.class, CreateAsyncCommandResponse.class) .withName("CreateAsyncCommand") .withUri("/v5/iot/{project_id}/devices/{device_id}/async-commands") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CreateAsyncCommandRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateAsyncCommandRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, AsyncDeviceCommandRequest.class, f -> f.withMarshaller(CreateAsyncCommandRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowAsyncDeviceCommandRequest, ShowAsyncDeviceCommandResponse> showAsyncDeviceCommand = genForshowAsyncDeviceCommand(); private static HttpRequestDef<ShowAsyncDeviceCommandRequest, ShowAsyncDeviceCommandResponse> genForshowAsyncDeviceCommand() { // basic HttpRequestDef.Builder<ShowAsyncDeviceCommandRequest, ShowAsyncDeviceCommandResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowAsyncDeviceCommandRequest.class, ShowAsyncDeviceCommandResponse.class) .withName("ShowAsyncDeviceCommand") .withUri("/v5/iot/{project_id}/devices/{device_id}/async-commands/{command_id}") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowAsyncDeviceCommandRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("command_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowAsyncDeviceCommandRequest::getCommandId, (req, v) -> { req.setCommandId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowAsyncDeviceCommandRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateBatchTaskRequest, CreateBatchTaskResponse> createBatchTask = genForcreateBatchTask(); private static HttpRequestDef<CreateBatchTaskRequest, CreateBatchTaskResponse> genForcreateBatchTask() { // basic HttpRequestDef.Builder<CreateBatchTaskRequest, CreateBatchTaskResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateBatchTaskRequest.class, CreateBatchTaskResponse.class) .withName("CreateBatchTask") .withUri("/v5/iot/{project_id}/batchtasks") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateBatchTaskRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, CreateBatchTask.class, f -> f.withMarshaller(CreateBatchTaskRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ListBatchTasksRequest, ListBatchTasksResponse> listBatchTasks = genForlistBatchTasks(); private static HttpRequestDef<ListBatchTasksRequest, ListBatchTasksResponse> genForlistBatchTasks() { // basic HttpRequestDef.Builder<ListBatchTasksRequest, ListBatchTasksResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListBatchTasksRequest.class, ListBatchTasksResponse.class) .withName("ListBatchTasks") .withUri("/v5/iot/{project_id}/batchtasks") .withContentType("application/json"); // requests builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListBatchTasksRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("task_type", LocationType.Query, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ListBatchTasksRequest::getTaskType, (req, v) -> { req.setTaskType(v); }) ); builder.withRequestField("status", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListBatchTasksRequest::getStatus, (req, v) -> { req.setStatus(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListBatchTasksRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListBatchTasksRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListBatchTasksRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListBatchTasksRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowBatchTaskRequest, ShowBatchTaskResponse> showBatchTask = genForshowBatchTask(); private static HttpRequestDef<ShowBatchTaskRequest, ShowBatchTaskResponse> genForshowBatchTask() { // basic HttpRequestDef.Builder<ShowBatchTaskRequest, ShowBatchTaskResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowBatchTaskRequest.class, ShowBatchTaskResponse.class) .withName("ShowBatchTask") .withUri("/v5/iot/{project_id}/batchtasks/{task_id}") .withContentType("application/json"); // requests builder.withRequestField("task_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowBatchTaskRequest::getTaskId, (req, v) -> { req.setTaskId(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ShowBatchTaskRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowBatchTaskRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ShowBatchTaskRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowBatchTaskRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteBatchTaskFileRequest, DeleteBatchTaskFileResponse> deleteBatchTaskFile = genFordeleteBatchTaskFile(); private static HttpRequestDef<DeleteBatchTaskFileRequest, DeleteBatchTaskFileResponse> genFordeleteBatchTaskFile() { // basic HttpRequestDef.Builder<DeleteBatchTaskFileRequest, DeleteBatchTaskFileResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteBatchTaskFileRequest.class, DeleteBatchTaskFileResponse.class) .withName("DeleteBatchTaskFile") .withUri("/v5/iot/{project_id}/batchtask-files/{file_id}") .withContentType("application/json"); // requests builder.withRequestField("file_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteBatchTaskFileRequest::getFileId, (req, v) -> { req.setFileId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteBatchTaskFileRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteBatchTaskFileResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListBatchTaskFilesRequest, ListBatchTaskFilesResponse> listBatchTaskFiles = genForlistBatchTaskFiles(); private static HttpRequestDef<ListBatchTaskFilesRequest, ListBatchTaskFilesResponse> genForlistBatchTaskFiles() { // basic HttpRequestDef.Builder<ListBatchTaskFilesRequest, ListBatchTaskFilesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListBatchTaskFilesRequest.class, ListBatchTaskFilesResponse.class) .withName("ListBatchTaskFiles") .withUri("/v5/iot/{project_id}/batchtask-files") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListBatchTaskFilesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UploadBatchTaskFileRequest, UploadBatchTaskFileResponse> uploadBatchTaskFile = genForuploadBatchTaskFile(); private static HttpRequestDef<UploadBatchTaskFileRequest, UploadBatchTaskFileResponse> genForuploadBatchTaskFile() { // basic HttpRequestDef.Builder<UploadBatchTaskFileRequest, UploadBatchTaskFileResponse> builder = HttpRequestDef.builder(HttpMethod.POST, UploadBatchTaskFileRequest.class, UploadBatchTaskFileResponse.class) .withName("UploadBatchTaskFile") .withUri("/v5/iot/{project_id}/batchtask-files") .withContentType("multipart/form-data"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UploadBatchTaskFileRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UploadBatchTaskFileRequestBody.class, f -> f.withMarshaller(UploadBatchTaskFileRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<AddCertificateRequest, AddCertificateResponse> addCertificate = genForaddCertificate(); private static HttpRequestDef<AddCertificateRequest, AddCertificateResponse> genForaddCertificate() { // basic HttpRequestDef.Builder<AddCertificateRequest, AddCertificateResponse> builder = HttpRequestDef.builder(HttpMethod.POST, AddCertificateRequest.class, AddCertificateResponse.class) .withName("AddCertificate") .withUri("/v5/iot/{project_id}/certificates") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(AddCertificateRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, CreateCertificateDTO.class, f -> f.withMarshaller(AddCertificateRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CheckCertificateRequest, CheckCertificateResponse> checkCertificate = genForcheckCertificate(); private static HttpRequestDef<CheckCertificateRequest, CheckCertificateResponse> genForcheckCertificate() { // basic HttpRequestDef.Builder<CheckCertificateRequest, CheckCertificateResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CheckCertificateRequest.class, CheckCertificateResponse.class) .withName("CheckCertificate") .withUri("/v5/iot/{project_id}/certificates/{certificate_id}/action") .withContentType("application/json"); // requests builder.withRequestField("certificate_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CheckCertificateRequest::getCertificateId, (req, v) -> { req.setCertificateId(v); }) ); builder.withRequestField("action_id", LocationType.Query, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CheckCertificateRequest::getActionId, (req, v) -> { req.setActionId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CheckCertificateRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, VerifyCertificateDTO.class, f -> f.withMarshaller(CheckCertificateRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CheckCertificateResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<DeleteCertificateRequest, DeleteCertificateResponse> deleteCertificate = genFordeleteCertificate(); private static HttpRequestDef<DeleteCertificateRequest, DeleteCertificateResponse> genFordeleteCertificate() { // basic HttpRequestDef.Builder<DeleteCertificateRequest, DeleteCertificateResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteCertificateRequest.class, DeleteCertificateResponse.class) .withName("DeleteCertificate") .withUri("/v5/iot/{project_id}/certificates/{certificate_id}") .withContentType("application/json"); // requests builder.withRequestField("certificate_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteCertificateRequest::getCertificateId, (req, v) -> { req.setCertificateId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteCertificateRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteCertificateResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListCertificatesRequest, ListCertificatesResponse> listCertificates = genForlistCertificates(); private static HttpRequestDef<ListCertificatesRequest, ListCertificatesResponse> genForlistCertificates() { // basic HttpRequestDef.Builder<ListCertificatesRequest, ListCertificatesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListCertificatesRequest.class, ListCertificatesResponse.class) .withName("ListCertificates") .withUri("/v5/iot/{project_id}/certificates") .withContentType("application/json"); // requests builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListCertificatesRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListCertificatesRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListCertificatesRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListCertificatesRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListCertificatesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateCommandRequest, CreateCommandResponse> createCommand = genForcreateCommand(); private static HttpRequestDef<CreateCommandRequest, CreateCommandResponse> genForcreateCommand() { // basic HttpRequestDef.Builder<CreateCommandRequest, CreateCommandResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateCommandRequest.class, CreateCommandResponse.class) .withName("CreateCommand") .withUri("/v5/iot/{project_id}/devices/{device_id}/commands") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CreateCommandRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateCommandRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, DeviceCommandRequest.class, f -> f.withMarshaller(CreateCommandRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<AddDeviceGroupRequest, AddDeviceGroupResponse> addDeviceGroup = genForaddDeviceGroup(); private static HttpRequestDef<AddDeviceGroupRequest, AddDeviceGroupResponse> genForaddDeviceGroup() { // basic HttpRequestDef.Builder<AddDeviceGroupRequest, AddDeviceGroupResponse> builder = HttpRequestDef.builder(HttpMethod.POST, AddDeviceGroupRequest.class, AddDeviceGroupResponse.class) .withName("AddDeviceGroup") .withUri("/v5/iot/{project_id}/device-group") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(AddDeviceGroupRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NULL_IGNORE, AddDeviceGroupDTO.class, f -> f.withMarshaller(AddDeviceGroupRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateOrDeleteDeviceInGroupRequest, CreateOrDeleteDeviceInGroupResponse> createOrDeleteDeviceInGroup = genForcreateOrDeleteDeviceInGroup(); private static HttpRequestDef<CreateOrDeleteDeviceInGroupRequest, CreateOrDeleteDeviceInGroupResponse> genForcreateOrDeleteDeviceInGroup() { // basic HttpRequestDef.Builder<CreateOrDeleteDeviceInGroupRequest, CreateOrDeleteDeviceInGroupResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateOrDeleteDeviceInGroupRequest.class, CreateOrDeleteDeviceInGroupResponse.class) .withName("CreateOrDeleteDeviceInGroup") .withUri("/v5/iot/{project_id}/device-group/{group_id}/action") .withContentType("application/json"); // requests builder.withRequestField("group_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CreateOrDeleteDeviceInGroupRequest::getGroupId, (req, v) -> { req.setGroupId(v); }) ); builder.withRequestField("action_id", LocationType.Query, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CreateOrDeleteDeviceInGroupRequest::getActionId, (req, v) -> { req.setActionId(v); }) ); builder.withRequestField("device_id", LocationType.Query, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CreateOrDeleteDeviceInGroupRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateOrDeleteDeviceInGroupRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateOrDeleteDeviceInGroupResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<DeleteDeviceGroupRequest, DeleteDeviceGroupResponse> deleteDeviceGroup = genFordeleteDeviceGroup(); private static HttpRequestDef<DeleteDeviceGroupRequest, DeleteDeviceGroupResponse> genFordeleteDeviceGroup() { // basic HttpRequestDef.Builder<DeleteDeviceGroupRequest, DeleteDeviceGroupResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteDeviceGroupRequest.class, DeleteDeviceGroupResponse.class) .withName("DeleteDeviceGroup") .withUri("/v5/iot/{project_id}/device-group/{group_id}") .withContentType("application/json"); // requests builder.withRequestField("group_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteDeviceGroupRequest::getGroupId, (req, v) -> { req.setGroupId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteDeviceGroupRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteDeviceGroupResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListDeviceGroupsRequest, ListDeviceGroupsResponse> listDeviceGroups = genForlistDeviceGroups(); private static HttpRequestDef<ListDeviceGroupsRequest, ListDeviceGroupsResponse> genForlistDeviceGroups() { // basic HttpRequestDef.Builder<ListDeviceGroupsRequest, ListDeviceGroupsResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListDeviceGroupsRequest.class, ListDeviceGroupsResponse.class) .withName("ListDeviceGroups") .withUri("/v5/iot/{project_id}/device-group") .withContentType("application/json"); // requests builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListDeviceGroupsRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDeviceGroupsRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListDeviceGroupsRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("last_modified_time", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDeviceGroupsRequest::getLastModifiedTime, (req, v) -> { req.setLastModifiedTime(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDeviceGroupsRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDeviceGroupsRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowDeviceGroupRequest, ShowDeviceGroupResponse> showDeviceGroup = genForshowDeviceGroup(); private static HttpRequestDef<ShowDeviceGroupRequest, ShowDeviceGroupResponse> genForshowDeviceGroup() { // basic HttpRequestDef.Builder<ShowDeviceGroupRequest, ShowDeviceGroupResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowDeviceGroupRequest.class, ShowDeviceGroupResponse.class) .withName("ShowDeviceGroup") .withUri("/v5/iot/{project_id}/device-group/{group_id}") .withContentType("application/json"); // requests builder.withRequestField("group_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowDeviceGroupRequest::getGroupId, (req, v) -> { req.setGroupId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowDeviceGroupRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowDevicesInGroupRequest, ShowDevicesInGroupResponse> showDevicesInGroup = genForshowDevicesInGroup(); private static HttpRequestDef<ShowDevicesInGroupRequest, ShowDevicesInGroupResponse> genForshowDevicesInGroup() { // basic HttpRequestDef.Builder<ShowDevicesInGroupRequest, ShowDevicesInGroupResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowDevicesInGroupRequest.class, ShowDevicesInGroupResponse.class) .withName("ShowDevicesInGroup") .withUri("/v5/iot/{project_id}/device-group/{group_id}/devices") .withContentType("application/json"); // requests builder.withRequestField("group_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowDevicesInGroupRequest::getGroupId, (req, v) -> { req.setGroupId(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ShowDevicesInGroupRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowDevicesInGroupRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ShowDevicesInGroupRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowDevicesInGroupRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdateDeviceGroupRequest, UpdateDeviceGroupResponse> updateDeviceGroup = genForupdateDeviceGroup(); private static HttpRequestDef<UpdateDeviceGroupRequest, UpdateDeviceGroupResponse> genForupdateDeviceGroup() { // basic HttpRequestDef.Builder<UpdateDeviceGroupRequest, UpdateDeviceGroupResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateDeviceGroupRequest.class, UpdateDeviceGroupResponse.class) .withName("UpdateDeviceGroup") .withUri("/v5/iot/{project_id}/device-group/{group_id}") .withContentType("application/json"); // requests builder.withRequestField("group_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateDeviceGroupRequest::getGroupId, (req, v) -> { req.setGroupId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateDeviceGroupRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UpdateDeviceGroupDTO.class, f -> f.withMarshaller(UpdateDeviceGroupRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<AddDeviceRequest, AddDeviceResponse> addDevice = genForaddDevice(); private static HttpRequestDef<AddDeviceRequest, AddDeviceResponse> genForaddDevice() { // basic HttpRequestDef.Builder<AddDeviceRequest, AddDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.POST, AddDeviceRequest.class, AddDeviceResponse.class) .withName("AddDevice") .withUri("/v5/iot/{project_id}/devices") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(AddDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, AddDevice.class, f -> f.withMarshaller(AddDeviceRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteDeviceRequest, DeleteDeviceResponse> deleteDevice = genFordeleteDevice(); private static HttpRequestDef<DeleteDeviceRequest, DeleteDeviceResponse> genFordeleteDevice() { // basic HttpRequestDef.Builder<DeleteDeviceRequest, DeleteDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteDeviceRequest.class, DeleteDeviceResponse.class) .withName("DeleteDevice") .withUri("/v5/iot/{project_id}/devices/{device_id}") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteDeviceRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteDeviceResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<FreezeDeviceRequest, FreezeDeviceResponse> freezeDevice = genForfreezeDevice(); private static HttpRequestDef<FreezeDeviceRequest, FreezeDeviceResponse> genForfreezeDevice() { // basic HttpRequestDef.Builder<FreezeDeviceRequest, FreezeDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.POST, FreezeDeviceRequest.class, FreezeDeviceResponse.class) .withName("FreezeDevice") .withUri("/v5/iot/{project_id}/devices/{device_id}/freeze") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(FreezeDeviceRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(FreezeDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(FreezeDeviceResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListDevicesRequest, ListDevicesResponse> listDevices = genForlistDevices(); private static HttpRequestDef<ListDevicesRequest, ListDevicesResponse> genForlistDevices() { // basic HttpRequestDef.Builder<ListDevicesRequest, ListDevicesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListDevicesRequest.class, ListDevicesResponse.class) .withName("ListDevices") .withUri("/v5/iot/{project_id}/devices") .withContentType("application/json"); // requests builder.withRequestField("product_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getProductId, (req, v) -> { req.setProductId(v); }) ); builder.withRequestField("gateway_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getGatewayId, (req, v) -> { req.setGatewayId(v); }) ); builder.withRequestField("is_cascade_query", LocationType.Query, FieldExistence.NULL_IGNORE, Boolean.class, f -> f.withMarshaller(ListDevicesRequest::getIsCascadeQuery, (req, v) -> { req.setIsCascadeQuery(v); }) ); builder.withRequestField("node_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getNodeId, (req, v) -> { req.setNodeId(v); }) ); builder.withRequestField("device_name", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getDeviceName, (req, v) -> { req.setDeviceName(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListDevicesRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListDevicesRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("start_time", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getStartTime, (req, v) -> { req.setStartTime(v); }) ); builder.withRequestField("end_time", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getEndTime, (req, v) -> { req.setEndTime(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDevicesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ResetDeviceSecretRequest, ResetDeviceSecretResponse> resetDeviceSecret = genForresetDeviceSecret(); private static HttpRequestDef<ResetDeviceSecretRequest, ResetDeviceSecretResponse> genForresetDeviceSecret() { // basic HttpRequestDef.Builder<ResetDeviceSecretRequest, ResetDeviceSecretResponse> builder = HttpRequestDef.builder(HttpMethod.POST, ResetDeviceSecretRequest.class, ResetDeviceSecretResponse.class) .withName("ResetDeviceSecret") .withUri("/v5/iot/{project_id}/devices/{device_id}/action") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ResetDeviceSecretRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("action_id", LocationType.Query, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ResetDeviceSecretRequest::getActionId, (req, v) -> { req.setActionId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ResetDeviceSecretRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, ResetDeviceSecret.class, f -> f.withMarshaller(ResetDeviceSecretRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowDeviceRequest, ShowDeviceResponse> showDevice = genForshowDevice(); private static HttpRequestDef<ShowDeviceRequest, ShowDeviceResponse> genForshowDevice() { // basic HttpRequestDef.Builder<ShowDeviceRequest, ShowDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowDeviceRequest.class, ShowDeviceResponse.class) .withName("ShowDevice") .withUri("/v5/iot/{project_id}/devices/{device_id}") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowDeviceRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UnfreezeDeviceRequest, UnfreezeDeviceResponse> unfreezeDevice = genForunfreezeDevice(); private static HttpRequestDef<UnfreezeDeviceRequest, UnfreezeDeviceResponse> genForunfreezeDevice() { // basic HttpRequestDef.Builder<UnfreezeDeviceRequest, UnfreezeDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.POST, UnfreezeDeviceRequest.class, UnfreezeDeviceResponse.class) .withName("UnfreezeDevice") .withUri("/v5/iot/{project_id}/devices/{device_id}/unfreeze") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UnfreezeDeviceRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UnfreezeDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UnfreezeDeviceResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<UpdateDeviceRequest, UpdateDeviceResponse> updateDevice = genForupdateDevice(); private static HttpRequestDef<UpdateDeviceRequest, UpdateDeviceResponse> genForupdateDevice() { // basic HttpRequestDef.Builder<UpdateDeviceRequest, UpdateDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateDeviceRequest.class, UpdateDeviceResponse.class) .withName("UpdateDevice") .withUri("/v5/iot/{project_id}/devices/{device_id}") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateDeviceRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UpdateDevice.class, f -> f.withMarshaller(UpdateDeviceRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowDeviceShadowRequest, ShowDeviceShadowResponse> showDeviceShadow = genForshowDeviceShadow(); private static HttpRequestDef<ShowDeviceShadowRequest, ShowDeviceShadowResponse> genForshowDeviceShadow() { // basic HttpRequestDef.Builder<ShowDeviceShadowRequest, ShowDeviceShadowResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowDeviceShadowRequest.class, ShowDeviceShadowResponse.class) .withName("ShowDeviceShadow") .withUri("/v5/iot/{project_id}/devices/{device_id}/shadow") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowDeviceShadowRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowDeviceShadowRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdateDeviceShadowDesiredDataRequest, UpdateDeviceShadowDesiredDataResponse> updateDeviceShadowDesiredData = genForupdateDeviceShadowDesiredData(); private static HttpRequestDef<UpdateDeviceShadowDesiredDataRequest, UpdateDeviceShadowDesiredDataResponse> genForupdateDeviceShadowDesiredData() { // basic HttpRequestDef.Builder<UpdateDeviceShadowDesiredDataRequest, UpdateDeviceShadowDesiredDataResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateDeviceShadowDesiredDataRequest.class, UpdateDeviceShadowDesiredDataResponse.class) .withName("UpdateDeviceShadowDesiredData") .withUri("/v5/iot/{project_id}/devices/{device_id}/shadow") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateDeviceShadowDesiredDataRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateDeviceShadowDesiredDataRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UpdateDesireds.class, f -> f.withMarshaller(UpdateDeviceShadowDesiredDataRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateMessageRequest, CreateMessageResponse> createMessage = genForcreateMessage(); private static HttpRequestDef<CreateMessageRequest, CreateMessageResponse> genForcreateMessage() { // basic HttpRequestDef.Builder<CreateMessageRequest, CreateMessageResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateMessageRequest.class, CreateMessageResponse.class) .withName("CreateMessage") .withUri("/v5/iot/{project_id}/devices/{device_id}/messages") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(CreateMessageRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateMessageRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, DeviceMessageRequest.class, f -> f.withMarshaller(CreateMessageRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ListDeviceMessagesRequest, ListDeviceMessagesResponse> listDeviceMessages = genForlistDeviceMessages(); private static HttpRequestDef<ListDeviceMessagesRequest, ListDeviceMessagesResponse> genForlistDeviceMessages() { // basic HttpRequestDef.Builder<ListDeviceMessagesRequest, ListDeviceMessagesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListDeviceMessagesRequest.class, ListDeviceMessagesResponse.class) .withName("ListDeviceMessages") .withUri("/v5/iot/{project_id}/devices/{device_id}/messages") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ListDeviceMessagesRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListDeviceMessagesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowDeviceMessageRequest, ShowDeviceMessageResponse> showDeviceMessage = genForshowDeviceMessage(); private static HttpRequestDef<ShowDeviceMessageRequest, ShowDeviceMessageResponse> genForshowDeviceMessage() { // basic HttpRequestDef.Builder<ShowDeviceMessageRequest, ShowDeviceMessageResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowDeviceMessageRequest.class, ShowDeviceMessageResponse.class) .withName("ShowDeviceMessage") .withUri("/v5/iot/{project_id}/devices/{device_id}/messages/{message_id}") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowDeviceMessageRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("message_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowDeviceMessageRequest::getMessageId, (req, v) -> { req.setMessageId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowDeviceMessageRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateProductRequest, CreateProductResponse> createProduct = genForcreateProduct(); private static HttpRequestDef<CreateProductRequest, CreateProductResponse> genForcreateProduct() { // basic HttpRequestDef.Builder<CreateProductRequest, CreateProductResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateProductRequest.class, CreateProductResponse.class) .withName("CreateProduct") .withUri("/v5/iot/{project_id}/products") .withContentType("application/json;charset=UTF-8"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateProductRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NULL_IGNORE, AddProduct.class, f -> f.withMarshaller(CreateProductRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteProductRequest, DeleteProductResponse> deleteProduct = genFordeleteProduct(); private static HttpRequestDef<DeleteProductRequest, DeleteProductResponse> genFordeleteProduct() { // basic HttpRequestDef.Builder<DeleteProductRequest, DeleteProductResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteProductRequest.class, DeleteProductResponse.class) .withName("DeleteProduct") .withUri("/v5/iot/{project_id}/products/{product_id}") .withContentType("application/json"); // requests builder.withRequestField("product_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteProductRequest::getProductId, (req, v) -> { req.setProductId(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteProductRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteProductRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteProductResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListProductsRequest, ListProductsResponse> listProducts = genForlistProducts(); private static HttpRequestDef<ListProductsRequest, ListProductsResponse> genForlistProducts() { // basic HttpRequestDef.Builder<ListProductsRequest, ListProductsResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListProductsRequest.class, ListProductsResponse.class) .withName("ListProducts") .withUri("/v5/iot/{project_id}/products") .withContentType("application/json"); // requests builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListProductsRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListProductsRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListProductsRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListProductsRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListProductsRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowProductRequest, ShowProductResponse> showProduct = genForshowProduct(); private static HttpRequestDef<ShowProductRequest, ShowProductResponse> genForshowProduct() { // basic HttpRequestDef.Builder<ShowProductRequest, ShowProductResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowProductRequest.class, ShowProductResponse.class) .withName("ShowProduct") .withUri("/v5/iot/{project_id}/products/{product_id}") .withContentType("application/json"); // requests builder.withRequestField("product_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowProductRequest::getProductId, (req, v) -> { req.setProductId(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowProductRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowProductRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdateProductRequest, UpdateProductResponse> updateProduct = genForupdateProduct(); private static HttpRequestDef<UpdateProductRequest, UpdateProductResponse> genForupdateProduct() { // basic HttpRequestDef.Builder<UpdateProductRequest, UpdateProductResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateProductRequest.class, UpdateProductResponse.class) .withName("UpdateProduct") .withUri("/v5/iot/{project_id}/products/{product_id}") .withContentType("application/json;charset=UTF-8"); // requests builder.withRequestField("product_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateProductRequest::getProductId, (req, v) -> { req.setProductId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateProductRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UpdateProduct.class, f -> f.withMarshaller(UpdateProductRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ListPropertiesRequest, ListPropertiesResponse> listProperties = genForlistProperties(); private static HttpRequestDef<ListPropertiesRequest, ListPropertiesResponse> genForlistProperties() { // basic HttpRequestDef.Builder<ListPropertiesRequest, ListPropertiesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListPropertiesRequest.class, ListPropertiesResponse.class) .withName("ListProperties") .withUri("/v5/iot/{project_id}/devices/{device_id}/properties") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ListPropertiesRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("service_id", LocationType.Query, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ListPropertiesRequest::getServiceId, (req, v) -> { req.setServiceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListPropertiesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdatePropertiesRequest, UpdatePropertiesResponse> updateProperties = genForupdateProperties(); private static HttpRequestDef<UpdatePropertiesRequest, UpdatePropertiesResponse> genForupdateProperties() { // basic HttpRequestDef.Builder<UpdatePropertiesRequest, UpdatePropertiesResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdatePropertiesRequest.class, UpdatePropertiesResponse.class) .withName("UpdateProperties") .withUri("/v5/iot/{project_id}/devices/{device_id}/properties") .withContentType("application/json"); // requests builder.withRequestField("device_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdatePropertiesRequest::getDeviceId, (req, v) -> { req.setDeviceId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdatePropertiesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, DevicePropertiesRequest.class, f -> f.withMarshaller(UpdatePropertiesRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateRoutingRuleRequest, CreateRoutingRuleResponse> createRoutingRule = genForcreateRoutingRule(); private static HttpRequestDef<CreateRoutingRuleRequest, CreateRoutingRuleResponse> genForcreateRoutingRule() { // basic HttpRequestDef.Builder<CreateRoutingRuleRequest, CreateRoutingRuleResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateRoutingRuleRequest.class, CreateRoutingRuleResponse.class) .withName("CreateRoutingRule") .withUri("/v5/iot/{project_id}/routing-rule/rules") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateRoutingRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, AddRuleReq.class, f -> f.withMarshaller(CreateRoutingRuleRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateRuleActionRequest, CreateRuleActionResponse> createRuleAction = genForcreateRuleAction(); private static HttpRequestDef<CreateRuleActionRequest, CreateRuleActionResponse> genForcreateRuleAction() { // basic HttpRequestDef.Builder<CreateRuleActionRequest, CreateRuleActionResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateRuleActionRequest.class, CreateRuleActionResponse.class) .withName("CreateRuleAction") .withUri("/v5/iot/{project_id}/routing-rule/actions") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateRuleActionRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, AddActionReq.class, f -> f.withMarshaller(CreateRuleActionRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteRoutingRuleRequest, DeleteRoutingRuleResponse> deleteRoutingRule = genFordeleteRoutingRule(); private static HttpRequestDef<DeleteRoutingRuleRequest, DeleteRoutingRuleResponse> genFordeleteRoutingRule() { // basic HttpRequestDef.Builder<DeleteRoutingRuleRequest, DeleteRoutingRuleResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteRoutingRuleRequest.class, DeleteRoutingRuleResponse.class) .withName("DeleteRoutingRule") .withUri("/v5/iot/{project_id}/routing-rule/rules/{rule_id}") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteRoutingRuleRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteRoutingRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteRoutingRuleResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<DeleteRuleActionRequest, DeleteRuleActionResponse> deleteRuleAction = genFordeleteRuleAction(); private static HttpRequestDef<DeleteRuleActionRequest, DeleteRuleActionResponse> genFordeleteRuleAction() { // basic HttpRequestDef.Builder<DeleteRuleActionRequest, DeleteRuleActionResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteRuleActionRequest.class, DeleteRuleActionResponse.class) .withName("DeleteRuleAction") .withUri("/v5/iot/{project_id}/routing-rule/actions/{action_id}") .withContentType("application/json"); // requests builder.withRequestField("action_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteRuleActionRequest::getActionId, (req, v) -> { req.setActionId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteRuleActionRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteRuleActionResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListRoutingRulesRequest, ListRoutingRulesResponse> listRoutingRules = genForlistRoutingRules(); private static HttpRequestDef<ListRoutingRulesRequest, ListRoutingRulesResponse> genForlistRoutingRules() { // basic HttpRequestDef.Builder<ListRoutingRulesRequest, ListRoutingRulesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListRoutingRulesRequest.class, ListRoutingRulesResponse.class) .withName("ListRoutingRules") .withUri("/v5/iot/{project_id}/routing-rule/rules") .withContentType("application/json"); // requests builder.withRequestField("resource", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getResource, (req, v) -> { req.setResource(v); }) ); builder.withRequestField("event", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getEvent, (req, v) -> { req.setEvent(v); }) ); builder.withRequestField("app_type", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getAppType, (req, v) -> { req.setAppType(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("rule_name", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getRuleName, (req, v) -> { req.setRuleName(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListRoutingRulesRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListRoutingRulesRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRoutingRulesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ListRuleActionsRequest, ListRuleActionsResponse> listRuleActions = genForlistRuleActions(); private static HttpRequestDef<ListRuleActionsRequest, ListRuleActionsResponse> genForlistRuleActions() { // basic HttpRequestDef.Builder<ListRuleActionsRequest, ListRuleActionsResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListRuleActionsRequest.class, ListRuleActionsResponse.class) .withName("ListRuleActions") .withUri("/v5/iot/{project_id}/routing-rule/actions") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRuleActionsRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("channel", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRuleActionsRequest::getChannel, (req, v) -> { req.setChannel(v); }) ); builder.withRequestField("app_type", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRuleActionsRequest::getAppType, (req, v) -> { req.setAppType(v); }) ); builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRuleActionsRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListRuleActionsRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRuleActionsRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListRuleActionsRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRuleActionsRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowRoutingRuleRequest, ShowRoutingRuleResponse> showRoutingRule = genForshowRoutingRule(); private static HttpRequestDef<ShowRoutingRuleRequest, ShowRoutingRuleResponse> genForshowRoutingRule() { // basic HttpRequestDef.Builder<ShowRoutingRuleRequest, ShowRoutingRuleResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowRoutingRuleRequest.class, ShowRoutingRuleResponse.class) .withName("ShowRoutingRule") .withUri("/v5/iot/{project_id}/routing-rule/rules/{rule_id}") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowRoutingRuleRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowRoutingRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowRuleActionRequest, ShowRuleActionResponse> showRuleAction = genForshowRuleAction(); private static HttpRequestDef<ShowRuleActionRequest, ShowRuleActionResponse> genForshowRuleAction() { // basic HttpRequestDef.Builder<ShowRuleActionRequest, ShowRuleActionResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowRuleActionRequest.class, ShowRuleActionResponse.class) .withName("ShowRuleAction") .withUri("/v5/iot/{project_id}/routing-rule/actions/{action_id}") .withContentType("application/json"); // requests builder.withRequestField("action_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowRuleActionRequest::getActionId, (req, v) -> { req.setActionId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowRuleActionRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdateRoutingRuleRequest, UpdateRoutingRuleResponse> updateRoutingRule = genForupdateRoutingRule(); private static HttpRequestDef<UpdateRoutingRuleRequest, UpdateRoutingRuleResponse> genForupdateRoutingRule() { // basic HttpRequestDef.Builder<UpdateRoutingRuleRequest, UpdateRoutingRuleResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateRoutingRuleRequest.class, UpdateRoutingRuleResponse.class) .withName("UpdateRoutingRule") .withUri("/v5/iot/{project_id}/routing-rule/rules/{rule_id}") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateRoutingRuleRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateRoutingRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UpdateRuleReq.class, f -> f.withMarshaller(UpdateRoutingRuleRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdateRuleActionRequest, UpdateRuleActionResponse> updateRuleAction = genForupdateRuleAction(); private static HttpRequestDef<UpdateRuleActionRequest, UpdateRuleActionResponse> genForupdateRuleAction() { // basic HttpRequestDef.Builder<UpdateRuleActionRequest, UpdateRuleActionResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateRuleActionRequest.class, UpdateRuleActionResponse.class) .withName("UpdateRuleAction") .withUri("/v5/iot/{project_id}/routing-rule/actions/{action_id}") .withContentType("application/json"); // requests builder.withRequestField("action_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateRuleActionRequest::getActionId, (req, v) -> { req.setActionId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateRuleActionRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, UpdateActionReq.class, f -> f.withMarshaller(UpdateRuleActionRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ChangeRuleStatusRequest, ChangeRuleStatusResponse> changeRuleStatus = genForchangeRuleStatus(); private static HttpRequestDef<ChangeRuleStatusRequest, ChangeRuleStatusResponse> genForchangeRuleStatus() { // basic HttpRequestDef.Builder<ChangeRuleStatusRequest, ChangeRuleStatusResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, ChangeRuleStatusRequest.class, ChangeRuleStatusResponse.class) .withName("ChangeRuleStatus") .withUri("/v5/iot/{project_id}/rules/{rule_id}/status") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ChangeRuleStatusRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ChangeRuleStatusRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, RuleStatus.class, f -> f.withMarshaller(ChangeRuleStatusRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<CreateRuleRequest, CreateRuleResponse> createRule = genForcreateRule(); private static HttpRequestDef<CreateRuleRequest, CreateRuleResponse> genForcreateRule() { // basic HttpRequestDef.Builder<CreateRuleRequest, CreateRuleResponse> builder = HttpRequestDef.builder(HttpMethod.POST, CreateRuleRequest.class, CreateRuleResponse.class) .withName("CreateRule") .withUri("/v5/iot/{project_id}/rules") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(CreateRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, Rule.class, f -> f.withMarshaller(CreateRuleRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<DeleteRuleRequest, DeleteRuleResponse> deleteRule = genFordeleteRule(); private static HttpRequestDef<DeleteRuleRequest, DeleteRuleResponse> genFordeleteRule() { // basic HttpRequestDef.Builder<DeleteRuleRequest, DeleteRuleResponse> builder = HttpRequestDef.builder(HttpMethod.DELETE, DeleteRuleRequest.class, DeleteRuleResponse.class) .withName("DeleteRule") .withUri("/v5/iot/{project_id}/rules/{rule_id}") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(DeleteRuleRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(DeleteRuleResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<ListRulesRequest, ListRulesResponse> listRules = genForlistRules(); private static HttpRequestDef<ListRulesRequest, ListRulesResponse> genForlistRules() { // basic HttpRequestDef.Builder<ListRulesRequest, ListRulesResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ListRulesRequest.class, ListRulesResponse.class) .withName("ListRules") .withUri("/v5/iot/{project_id}/rules") .withContentType("application/json"); // requests builder.withRequestField("app_id", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRulesRequest::getAppId, (req, v) -> { req.setAppId(v); }) ); builder.withRequestField("rule_type", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRulesRequest::getRuleType, (req, v) -> { req.setRuleType(v); }) ); builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListRulesRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRulesRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListRulesRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListRulesRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ShowRuleRequest, ShowRuleResponse> showRule = genForshowRule(); private static HttpRequestDef<ShowRuleRequest, ShowRuleResponse> genForshowRule() { // basic HttpRequestDef.Builder<ShowRuleRequest, ShowRuleResponse> builder = HttpRequestDef.builder(HttpMethod.GET, ShowRuleRequest.class, ShowRuleResponse.class) .withName("ShowRule") .withUri("/v5/iot/{project_id}/rules/{rule_id}") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(ShowRuleRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ShowRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); // response return builder.build(); } public static final HttpRequestDef<UpdateRuleRequest, UpdateRuleResponse> updateRule = genForupdateRule(); private static HttpRequestDef<UpdateRuleRequest, UpdateRuleResponse> genForupdateRule() { // basic HttpRequestDef.Builder<UpdateRuleRequest, UpdateRuleResponse> builder = HttpRequestDef.builder(HttpMethod.PUT, UpdateRuleRequest.class, UpdateRuleResponse.class) .withName("UpdateRule") .withUri("/v5/iot/{project_id}/rules/{rule_id}") .withContentType("application/json"); // requests builder.withRequestField("rule_id", LocationType.Path, FieldExistence.NON_NULL_NON_EMPTY, String.class, f -> f.withMarshaller(UpdateRuleRequest::getRuleId, (req, v) -> { req.setRuleId(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UpdateRuleRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NON_NULL_NON_EMPTY, Rule.class, f -> f.withMarshaller(UpdateRuleRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<ListResourcesByTagsRequest, ListResourcesByTagsResponse> listResourcesByTags = genForlistResourcesByTags(); private static HttpRequestDef<ListResourcesByTagsRequest, ListResourcesByTagsResponse> genForlistResourcesByTags() { // basic HttpRequestDef.Builder<ListResourcesByTagsRequest, ListResourcesByTagsResponse> builder = HttpRequestDef.builder(HttpMethod.POST, ListResourcesByTagsRequest.class, ListResourcesByTagsResponse.class) .withName("ListResourcesByTags") .withUri("/v5/iot/{project_id}/tags/query-resources") .withContentType("application/json"); // requests builder.withRequestField("limit", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListResourcesByTagsRequest::getLimit, (req, v) -> { req.setLimit(v); }) ); builder.withRequestField("marker", LocationType.Query, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListResourcesByTagsRequest::getMarker, (req, v) -> { req.setMarker(v); }) ); builder.withRequestField("offset", LocationType.Query, FieldExistence.NULL_IGNORE, Integer.class, f -> f.withMarshaller(ListResourcesByTagsRequest::getOffset, (req, v) -> { req.setOffset(v); }) ); builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(ListResourcesByTagsRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NULL_IGNORE, QueryResourceByTagsDTO.class, f -> f.withMarshaller(ListResourcesByTagsRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response return builder.build(); } public static final HttpRequestDef<TagDeviceRequest, TagDeviceResponse> tagDevice = genFortagDevice(); private static HttpRequestDef<TagDeviceRequest, TagDeviceResponse> genFortagDevice() { // basic HttpRequestDef.Builder<TagDeviceRequest, TagDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.POST, TagDeviceRequest.class, TagDeviceResponse.class) .withName("TagDevice") .withUri("/v5/iot/{project_id}/tags/bind-resource") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(TagDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NULL_IGNORE, BindTagsDTO.class, f -> f.withMarshaller(TagDeviceRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(TagDeviceResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } public static final HttpRequestDef<UntagDeviceRequest, UntagDeviceResponse> untagDevice = genForuntagDevice(); private static HttpRequestDef<UntagDeviceRequest, UntagDeviceResponse> genForuntagDevice() { // basic HttpRequestDef.Builder<UntagDeviceRequest, UntagDeviceResponse> builder = HttpRequestDef.builder(HttpMethod.POST, UntagDeviceRequest.class, UntagDeviceResponse.class) .withName("UntagDevice") .withUri("/v5/iot/{project_id}/tags/unbind-resource") .withContentType("application/json"); // requests builder.withRequestField("Instance-Id", LocationType.Header, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UntagDeviceRequest::getInstanceId, (req, v) -> { req.setInstanceId(v); }) ); builder.withRequestField("body", LocationType.Body, FieldExistence.NULL_IGNORE, UnbindTagsDTO.class, f -> f.withMarshaller(UntagDeviceRequest::getBody, (req, v) -> { req.setBody(v); }) ); // response builder.withResponseField( "body", LocationType.Body, FieldExistence.NULL_IGNORE, String.class, f -> f.withMarshaller(UntagDeviceResponse::getBody, (response, data)->{ response.setBody(data); }) ); return builder.build(); } }
36.993011
186
0.595763
7e88ac88207401c2fb7d9d1098690950be399c94
5,285
/** * ***************************************************************************** * Copyright 2013 Lars Behnke * * 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.patern.clustering.hierarchical; import java.awt.Color; import java.util.ArrayList; import java.util.List; public class Cluster { public Object obj; private String name; private Cluster parent; private List<Cluster> children; private Distance distance = new Distance(); protected Color color = Color.BLACK; public Cluster(String name){ this.name = name; } public Cluster(Object obj) { this.obj = obj; this.name = String.valueOf(obj.toString()); } public Cluster(Object obj, String name){ this.obj = obj; this.name = name; } public Distance getDistance() { return distance; } public Double getWeightValue() { return distance.getWeight(); } public Double getDistanceValue() { return distance.getDistance(); } public void setDistance(Distance distance) { this.distance = distance; } public List<Cluster> getChildren() { if (children == null) { children = new ArrayList<>(); } return children; } public void setChildren(List<Cluster> children) { this.children = children; } public Cluster getParent() { return parent; } public void setParent(Cluster parent) { this.parent = parent; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public void addChild(Cluster cluster) { getChildren().add(cluster); } public boolean contains(Cluster cluster) { return getChildren().contains(cluster); } @Override public String toString() { return "Cluster " + name; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Cluster other = (Cluster) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { return (name == null) ? 0 : name.hashCode(); } public boolean isLeaf() { return getChildren().isEmpty(); } public int countLeafs() { return countLeafs(this, 0); } public int countLeafs(Cluster node, int count) { if (node.isLeaf()) { count++; } for (Cluster child : node.getChildren()) { count += child.countLeafs(); } return count; } public void getLeafs(List<Cluster> leafs){ if(isLeaf()){ leafs.add(this); }else{ for (Cluster child : children) { child.getLeafs(leafs); } } } public void toConsole(int indent) { for (int i = 0; i < indent; i++) { System.out.print(" "); } String str = getName() + (isLeaf() ? " (leaf)" : "") + (distance != null ? " distance: " + distance : ""); System.out.println(str); for (Cluster child : getChildren()) { child.toConsole(indent + 1); } } public double getTotalDistance() { Double dist = getDistance() == null ? 0 : getDistance().getDistance(); if (getChildren().size() > 0) { dist += children.get(0).getTotalDistance(); } return dist; } /** * Splits dendrogram into multiple clusters by cutting distance. * * @param cut * @param found clusters from cut * @author palas */ public void makeCut(double cut, List<Cluster> found){ if(cut < distance.getDistance()){ for (Cluster child : children) { if(!child.isLeaf()){ child.makeCut(cut, found); }else{ found.add(child); } } }else{ found.add(this); } } public void setColorRecursively(Color color) { setColor(color); for (Cluster child : children) { child.setColorRecursively(color); } } }
24.354839
115
0.529801
93636401d3bf579b3d80c5cd6f79385e70ae4920
1,736
package com.codahale.gpgj; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import java.security.SecureRandom; /** * An abstract base class for ECC key generators. * <p/> * Only supports NIST P-256, P-384, and P-521 keys, as per * <a href="http://www.ietf.org/rfc/rfc6637.txt">RFC 6637</a>. * * @see <a href="http://www.ietf.org/rfc/rfc6637.txt">RFC 6637</a> * @deprecated Not supported in GnuPG or BouncyCastle yet. */ @Deprecated abstract class AbstractEcKeyGenerator { protected static final ECDomainParameters P256 = convert(NISTNamedCurves.getByName("P-256")); protected static final ECDomainParameters P384 = convert(NISTNamedCurves.getByName("P-384")); protected static final ECDomainParameters P521 = convert(NISTNamedCurves.getByName("P-521")); private static ECDomainParameters convert(X9ECParameters params) { return new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed()); } private final ECDomainParameters parameters; protected AbstractEcKeyGenerator(ECDomainParameters parameters) { this.parameters = parameters; } public AsymmetricCipherKeyPair generate(SecureRandom random) { final ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(new ECKeyGenerationParameters(parameters, random)); return generator.generateKeyPair(); } }
39.454545
97
0.745968
64c68f9cbffa35145fa08afdbf4ce502cf4691e0
3,514
/* * Copyright 2018 Murat Artim (muratartim@gmail.com). * * 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 equinox.task; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ExecutionException; import equinox.Equinox; import equinox.data.fileType.AircraftModel; import equinox.data.ui.QVLVPosition; import equinox.task.InternalEquinoxTask.ShortRunningTask; import equinox.utility.AlphanumComparator2; /** * Class for get frame/stringer positions task. * * @author Murat Artim * @date Aug 4, 2015 * @time 12:33:55 PM */ public class GetQVLVPositions extends InternalEquinoxTask<ArrayList<QVLVPosition>> implements ShortRunningTask { /** Requesting panel. */ private final QVLVPositionRequestingPanel panel_; /** Aircraft model. */ private final AircraftModel model_; /** * Creates get frame/stringer positions task. * * @param panel * Requesting panel. * @param model * Aircraft model. */ public GetQVLVPositions(QVLVPositionRequestingPanel panel, AircraftModel model) { panel_ = panel; model_ = model; } @Override public boolean canBeCancelled() { return false; } @Override public String getTaskTitle() { return "Get frame/stringer positions"; } @Override protected ArrayList<QVLVPosition> call() throws Exception { // update progress info updateTitle("Retrieving frame/stringer positions..."); updateMessage("Please wait..."); // initialize list ArrayList<QVLVPosition> positions = new ArrayList<>(); // get connection to database try (Connection connection = Equinox.DBC_POOL.getConnection()) { // create statement try (Statement statement = connection.createStatement()) { // create query String sql = "select distinct qv_pos, lv_pos from grids_" + model_.getID(); sql += " where qv_pos is not null and lv_pos is not null order by qv_pos, lv_pos"; // execute query try (ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { positions.add(new QVLVPosition(resultSet.getString("qv_pos"), resultSet.getString("lv_pos"))); } } } } // sort positions Collections.sort(positions, new AlphanumComparator2()); // return list return positions; } @Override protected void succeeded() { // call ancestor super.succeeded(); // set angles try { panel_.setQVLVPositions(get()); } // exception occurred catch (InterruptedException | ExecutionException e) { handleResultRetrievalException(e); } } /** * Interface for frame/stringer position requesting panels. * * @author Murat Artim * @date Nov 28, 2014 * @time 2:18:37 PM */ public interface QVLVPositionRequestingPanel { /** * Sets element group names to this panel. * * @param positions * Frame/stringer positions. */ void setQVLVPositions(ArrayList<QVLVPosition> positions); } }
25.1
112
0.713432
e08b42c63237288d82d9c17db480e52d8867b2f0
1,015
package com.moon.poi.excel.annotation; import com.moon.core.lang.Unsupported; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 索引 * * @author moonsky */ @Unsupported("暂不支持") @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface TableIndexer { /** * 序号标题; * <p> * 序号列依附于普通列存在,表示插入到普通列前面 * <p> * 索引列的标题名称与所在列最末级标题同级,并自动继承所在列的"高级"标题 * * @return 标题名称 */ String value() default "#"; /** * 索引开始序号 * * @return 序号值 */ int startFrom() default 1; /** * 增量 * * @return 数值 */ int step() default 1; /** * 默认在所在列前面,当{@link #ending()}为{@code true}时,放在所在列后面 * * @return true | false */ boolean ending() default false; /** * 集合字段是否全局计数 * * @return true: 全局计数 */ boolean joinGlobal() default false; }
17.20339
56
0.589163
939cce1babff9784e99cee08546af152554c5036
2,570
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.storage.file.datalake.models; /** * AccessControlChangeCounters contains counts of operations that change Access Control Lists recursively. */ public class AccessControlChangeCounters { private long changedDirectoriesCount; private long changedFilesCount; private long failedChangesCount; /** * The number of directories where Access Control List has been updated successfully. * * @return The number of directories where Access Control List has been updated successfully. */ public long getChangedDirectoriesCount() { return this.changedDirectoriesCount; } /** * Sets the number of directories where Access Control List has been updated successfully. * @param changedDirectoriesCount The number of directories where Access Control List has been updated * successfully. * @return The updated object. */ public AccessControlChangeCounters setChangedDirectoriesCount(long changedDirectoriesCount) { this.changedDirectoriesCount = changedDirectoriesCount; return this; } /** * Returns the number of files where Access Control List has been updated successfully. * * @return The number of files where Access Control List has been updated successfully. */ public long getChangedFilesCount() { return this.changedFilesCount; } /** * Sets number of files where Access Control List has been updated successfully. * * @param changedFilesCount The number of files where Access Control List has been updated successfully. * @return The updated object */ public AccessControlChangeCounters setChangedFilesCount(long changedFilesCount) { this.changedFilesCount = changedFilesCount; return this; } /** * Returns the number of paths where Access Control List update has failed. * * @return The number of paths where Access Control List update has failed. */ public long getFailedChangesCount() { return failedChangesCount; } /** * Sets the number of paths where Access Control List update has failed. * @param failedChangesCount The number of paths where Access Control List update has failed. * @return The updated object. */ public AccessControlChangeCounters setFailedChangesCount(long failedChangesCount) { this.failedChangesCount = failedChangesCount; return this; } }
35.205479
108
0.714786
13f47813dda73e3dd0ad6a568c1dd44b9a0089e6
1,427
package com.android.picshow.utils; import android.support.v4.app.Fragment; import android.util.SparseArray; import com.android.picshow.app.AlbumSetPage; import com.android.picshow.app.TimeLinePage; import java.util.ArrayList; import java.util.HashMap; /** * Created by yuntao.wei on 2017/11/28. * github:https://github.com/YuntaoWei * blog:http://blog.csdn.net/qq_17541215 */ public class PageFactory { private static SparseArray<Fragment> frg = new SparseArray<>(); public static final int INDEX_TIMELINE = 0; public static final int INDEX_ALBUMSET = 1; public static final int INDEX_ALBUM = 2; static enum PageEnum { PAGE_TIMELINE,PAGE_ALBUMSET,PAGE_ALBUM }; public static Fragment loadPage(int pos) { if (frg.get(pos) == null) { frg.put(pos, createPage(pos)); } return frg.get(pos); } public static ArrayList<Fragment> getMainPage() { ArrayList<Fragment> pages = new ArrayList<>(); pages.add(loadPage(INDEX_TIMELINE)); pages.add(loadPage(INDEX_ALBUMSET)); return pages; } private static Fragment createPage(int position) { PageEnum frg = PageEnum.values()[position]; switch (frg) { case PAGE_TIMELINE: return new TimeLinePage(); case PAGE_ALBUMSET: return new AlbumSetPage(); } return null; } }
25.035088
67
0.648213