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
6aa8a0c8f6f3008a9ecf2d9219563340ee19b66b
4,607
/* This question is from https://leetcode.com/problems/serialize-and-deserialize-bst/ Difficulty: medium Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. */ // Tree traversal, Binary search tree, T:O(N), M:O(N), 16ms /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ // preoder, T:O(N), S:O(N), 17ms public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); preorder(root, sb); return sb.toString(); } public void preorder(TreeNode root, StringBuilder sb){ if(root == null){ return; } sb.append(String.valueOf(root.val)+","); preorder(root.left, sb); preorder(root.right, sb); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] strArr = data.split(","); if(strArr.length <= 1){ if(strArr[0].equals("")){ return null; }else{ return new TreeNode(Integer.valueOf(strArr[0])); } } TreeNode root = new TreeNode(Integer.valueOf(strArr[0])); for(int i = 1; i < strArr.length; i++){ insert(root, Integer.valueOf(strArr[i])); } return root; } public void insert(TreeNode root, int val){ if(root == null) return; if(root.val < val){ if(root.right == null){ root.right = new TreeNode(val); }else{ insert(root.right, val); } }else{ if(root.left == null){ root.left = new TreeNode(val); }else{ insert(root.left, val); } } } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root)); // BFS, T:O(N), S:O(N), 27ms public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { Deque<TreeNode> q = new LinkedList(); List<String> strList = new LinkedList(); q.add(root); while(q.size() > 0){ int size = q.size(); for(int i = 0 ;i < size; i++){ TreeNode node = q.poll(); if(node != null){ q.add(node.left); q.add(node.right); strList.add(String.valueOf(node.val)); }else{ strList.add("null"); } } } return String.join(",", strList.toArray(new String[strList.size()])); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] nodes = data.split(","); if((nodes.length == 1) && (nodes[0].equals("null"))) return null; Deque<TreeNode> q = new LinkedList(); TreeNode head = new TreeNode(Integer.valueOf(nodes[0])); q.add(head); int index = 1; while(q.size() > 0){ int size = q.size(); for(int i = 0; i < size; i++){ TreeNode node = q.poll(); if(nodes[index].equals("null")){ node.left = null; }else{ node.left = new TreeNode(Integer.valueOf(nodes[index])); q.add(node.left); } index++; if(nodes[index].equals("null")){ node.right = null; }else{ node.right = new TreeNode(Integer.valueOf(nodes[index])); q.add(node.right); } index++; } } return head; } }
32.443662
307
0.54135
4f12fd1fab124db59e5a1c44c6237d01e59bb54c
3,445
/* * Copyright (c) Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.domain.purchasing.planning.requirement; import java.math.BigDecimal; import org.opentaps.foundation.service.ServiceException; import org.opentaps.foundation.service.ServiceInterface; /** * Interface for Requirement services. */ public interface RequirementServiceInterface extends ServiceInterface { /** * Sets the requirement ID, required parameter for all requirement services. * @param requirementId the requirement ID */ public void setRequirementId(String requirementId); /** * Sets the party ID, required parameter for {@link #updateRequirementSupplier} and {@link #updateRequirementSupplierAndQuantity}. * @param partyId the party ID */ public void setPartyId(String partyId); /** * Sets the new party ID, required parameter for {@link #updateRequirementSupplier} and {@link #updateRequirementSupplierAndQuantity}. * @param newPartyId the new party ID */ public void setNewPartyId(String newPartyId); /** * Sets the quantity, required parameter for {@link #updateRequirementSupplierAndQuantity}. * @param quantity the fromDate */ public void setQuantity(BigDecimal quantity); /** * Service to close a requirement. This should only be called as an ECA when a requirement status * is set to REQ_ORDERED. * @throws ServiceException if an error occurs * @see #setRequirementId required input <code>requirementId</code> */ public void closeRequirement() throws ServiceException; /** * Service to cancel a requirement. Sets its status to REQ_REJECTED. * @throws ServiceException if an error occurs * @see #setRequirementId required input <code>requirementId</code> */ public void cancelRequirement() throws ServiceException; /** * Service to update a requirement supplier from <code>partyId</code> to <code>newPartyId</code>. * @throws ServiceException if an error occurs * @see #setRequirementId required input <code>requirementId</code> * @see #setPartyId required input <code>partyId</code> * @see #setNewPartyId required input <code>newPartyId</code> */ public void updateRequirementSupplier() throws ServiceException; /** * Service to update the supplier and or the quantity of a requirement. * @throws ServiceException if an error occurs * @see #setRequirementId required input <code>requirementId</code> * @see #setPartyId required input <code>partyId</code> * @see #setNewPartyId required input <code>newPartyId</code> * @see #setQuantity required input <code>quantity</code> */ public void updateRequirementSupplierAndQuantity() throws ServiceException; }
39.597701
138
0.724819
7cbcb251e4b1a7afb3f2441bb81cff5579d190ec
1,130
/** * © Nowina Solutions, 2015-2015 * * Concédée sous licence EUPL, version 1.1 ou – dès leur approbation par la Commission européenne - versions ultérieures de l’EUPL (la «Licence»). * Vous ne pouvez utiliser la présente œuvre que conformément à la Licence. * Vous pouvez obtenir une copie de la Licence à l’adresse suivante: * * http://ec.europa.eu/idabc/eupl5 * * Sauf obligation légale ou contractuelle écrite, le logiciel distribué sous la Licence est distribué «en l’état», * SANS GARANTIES OU CONDITIONS QUELLES QU’ELLES SOIENT, expresses ou implicites. * Consultez la Licence pour les autorisations et les restrictions linguistiques spécifiques relevant de la Licence. */ package lu.nowina.nexu.api; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; @XmlType(name = "feedbackStatus") @XmlEnum public enum FeedbackStatus { NO_PRODUCT_FOUND, PRODUCT_NOT_SUPPORTED, NO_KEYS, EXCEPTION, SUCCESS, FAILED, SIGNATURE_VERIFICATION_FAILED; public String value() { return name(); } public static FeedbackStatus fromValue(String v) { return valueOf(v); } }
33.235294
151
0.755752
24d633d6c00932776d2bc9781a540b80177e0484
3,050
package org.geoladris.config.providers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.geoladris.Geoladris; import org.geoladris.config.Config; import org.junit.After; import org.junit.Before; import org.junit.Test; import net.sf.json.JSONObject; public class RoleConfigProviderTest { private File configDir, roleDir; private RoleConfigProvider provider; private Config config; @Before public void setup() throws IOException { configDir = File.createTempFile("geoladris", ""); configDir.delete(); configDir.mkdir(); roleDir = new File(configDir, RoleConfigProvider.ROLE_DIR); roleDir.mkdir(); provider = new RoleConfigProvider(); config = mock(Config.class); when(config.getDir()).thenReturn(configDir); } @After public void teardown() throws IOException { FileUtils.deleteDirectory(configDir); } @Test public void noRoleOnRequest() throws Exception { HttpServletRequest request = mockRequest(null); Map<String, JSONObject> conf = provider.getPluginConfig(config, new HashMap<String, JSONObject>(), request); assertNull(conf); } @Test public void roleWithoutSpecificConf() throws Exception { HttpServletRequest request = mockRequest("role1"); Map<String, JSONObject> conf = provider.getPluginConfig(config, new HashMap<String, JSONObject>(), request); assertNull(conf); } @Test public void addsPlugin() throws Exception { String role = "role1"; File tmp = new File(roleDir, role + ".json"); FileWriter writer = new FileWriter(tmp); String pluginName = "p1"; IOUtils.write("{ '" + pluginName + "' : { mymodule : {'a' : true }}}", writer); writer.close(); HttpServletRequest request = mockRequest(role); Map<String, JSONObject> pluginConfs = provider.getPluginConfig(config, new HashMap<String, JSONObject>(), request); assertEquals(1, pluginConfs.size()); assertTrue(pluginConfs.containsKey(pluginName)); JSONObject pluginConf = pluginConfs.get(pluginName); assertTrue(pluginConf.getJSONObject("mymodule").getBoolean("a")); tmp.delete(); } @Test public void cannnotBeCached() { assertFalse(this.provider.canBeCached()); } private HttpServletRequest mockRequest(String role) { HttpServletRequest request = mock(HttpServletRequest.class); HttpSession session = mock(HttpSession.class); when(request.getSession()).thenReturn(session); when(session.getAttribute(Geoladris.ATTR_ROLE)).thenReturn(role); return request; } }
28.773585
85
0.730492
4199c8751cc461114e82d8b86269a983221eefa5
1,263
package com.cq.szyk.mapfluxcommon.expetion; import com.cq.szyk.mapfluxcommon.response.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * @author lyz * @describe 全局异常捕获 * @date 2019/5/24 */ @ControllerAdvice public class ExceptionCatch { private static final Logger LOGGER = LoggerFactory.getLogger(Exception.class); @ExceptionHandler(MyException.class) @ResponseBody public Response myException(MyException e) { LOGGER.error(e.getMessage()); ResultCode resultCode = e.getResultCode(); return new ResponseResult(resultCode); } @ExceptionHandler(Exception.class) @ResponseBody public Response exception(Exception e) { LOGGER.error(e.getMessage()); if("不允许访问".equals(e.getMessage())){ CustomizeCode customizeCode = new CustomizeCode(false, 2000, "用户权限不足!"); return new ResponseResult(customizeCode); } CustomizeCode customizeCode = new CustomizeCode(false, 2000, e.getMessage()); return new ResponseResult(customizeCode); } }
30.804878
85
0.720507
5618b253c3568414fd224680e8b88d3963d2368e
1,088
package com.ovit.nswy.member.service; import com.github.pagehelper.PageInfo; import com.ovit.nswy.member.model.request.GetUserQuery; import com.ovit.nswy.member.model.request.ListFollowQuery; import com.ovit.nswy.member.model.request.UserQuery; import com.ovit.nswy.member.model.response.FansDTO; import com.ovit.nswy.member.model.response.ListAppDTO; import com.ovit.nswy.member.model.response.UserDTO; import java.util.List; import java.util.Map; /** * Created by ${huipei.x} on 2017-12-5. */ public interface UserService { PageInfo<UserDTO> listUser(Map<String,Object> params); UserDTO getUserByQuery(GetUserQuery getUserQuery); UserDTO getUserMemberName(GetUserQuery getUserQuery); Integer updateStartFlag(Integer startFlag, Integer id); ListAppDTO getAppStartFlag(String account); List<FansDTO> listfollow(ListFollowQuery listFollowQuery); Integer updateStatusByaccount(String account,String toAccount); Map<String,Object> queryRealNameAndStatus(Map<String, Object> map); Map<String,Object> getDisplayNameByAccount(String account); }
30.222222
71
0.788603
05dac49d775e5f4d1c57d2b60620c4360ee651e1
3,325
package it.unicam.ids.c3.corriere; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import it.unicam.ids.c3.acquisti.Acquisto; import it.unicam.ids.c3.luogo.LuogoService; import it.unicam.ids.c3.luogo.Magazzino; import it.unicam.ids.c3.ordine.DettaglioOrdine; import it.unicam.ids.c3.ordine.Ordine; import it.unicam.ids.c3.user.UserService; @RestController @RequestMapping("/corriere") public class CorriereController { @Autowired UserService userSer; @Autowired CorriereService corriereSer; @Autowired LuogoService luogoSer; @GetMapping("/lista-consegne") public ResponseEntity<List<Ordine>> getAllConsegne() { List<Ordine> ordini = corriereSer.getListaConsegna(userSer.getUserDetails().getId()); return new ResponseEntity<>(ordini, HttpStatus.OK); } @GetMapping("/ordine") public ResponseEntity<?> getDettagliOrdine(@RequestParam Long idOrdine) { try { DettaglioOrdine dettagli = corriereSer.getDettagliOrdine(idOrdine); return ResponseEntity.ok(dettagli); } catch (Exception e) { return ResponseEntity.badRequest().body(HttpStatus.BAD_REQUEST); } } @GetMapping("/lista-ritiri") public ResponseEntity<?> getAllRitiri(@RequestParam Long idOrdine) { List<Acquisto> listaRitiri = corriereSer.getListaRitiro(idOrdine); return new ResponseEntity<>(listaRitiri, HttpStatus.OK); } @GetMapping("/indirizzo-ritiro") public ResponseEntity<?> getIndirizzoRitiro(@RequestParam Long idNegozio) { return new ResponseEntity<>(corriereSer.getIndirizzoLuogoConsegna(idNegozio), HttpStatus.OK); } @GetMapping("/conferma-consegna") public ResponseEntity<?> confermaConsegna(@RequestParam Long idOrdine) { try { corriereSer.setStatoOrdine(idOrdine); corriereSer.rimuoviOrdineConsegna(idOrdine, userSer.getUserDetails().getId()); } catch (Exception e) { return ResponseEntity.badRequest().body(HttpStatus.BAD_REQUEST); } return ResponseEntity.ok().body(null); } @GetMapping("/modifica-luogo-consegna") public ResponseEntity<?> aggiornaLuogoConsegna(@RequestParam Long idOrdine, @RequestParam Long idLuogo) { try { corriereSer.cambiaLuogoConsegna(idOrdine, idLuogo); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } return ResponseEntity.ok().body(null); } @GetMapping("/lista-magazzini") public ResponseEntity<?> getAllMagazzini() { List<Magazzino> magazzini = luogoSer.getAllMagazzini(); return new ResponseEntity<>(magazzini, HttpStatus.OK); } @GetMapping("/stato") public ResponseEntity<Boolean> getOperativo() { return ResponseEntity.ok(corriereSer.getOperativo(userSer.getUserDetails().getId())); } @GetMapping("/cambia-stato") public ResponseEntity<?> setOperativo() { try { corriereSer.setOperativo(userSer.getUserDetails().getId()); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } return ResponseEntity.ok().body(null); } }
32.281553
106
0.768722
9cb2f58e8b36ea5b61c0c83c52c650cc6e4c570f
2,455
package kr.co.wkim.address.config; import java.util.Collection; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.Topic; import org.springframework.data.redis.serializer.GenericToStringSerializer; /** * * redis config * * created by wkimdev * */ public class RedisConfig { // yml properties 파일에 환경설정이 되어 있어야 함 // 환경설정 이후, value 어노테이션으로 프로퍼티스값 불러옴. @Value("${}") private String pubChannel; @Value("${}") private String redisHost; @Value("${}") private int redisPort; @Value("${}") private String redisPassword; // bean 어노테이션으로 // setup, connection factory값을 가져온다. // org.springframework.context.annotation 의 Configuration 어노테이션과 // Bean 어노테이션 코드를 이용하여 스프링 컨테이너에 새 로운 빈 객체를 제공할 수 있다. @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(redisHost); jedisConnectionFactory.setPort(redisPort); jedisConnectionFactory.setPassword(redisPassword); jedisConnectionFactory.setUsePool(true); return jedisConnectionFactory; } // redis Template Setup @Bean public RedisTemplate<String, Object> redisTemplate() { final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(jedisConnectionFactory()); template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class)); return template; } /** * redis listner * @return RedisMessageListenerContainer */ @Bean public RedisMessageListenerContainer redisContainer() { final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(jedisConnectionFactory()); // subscribe 채널 등록 container.addMessageListener(messageListener(), topics()); return container; } private Collection<? extends Topic> topics() { // TODO Auto-generated method stub return null; } private MessageListener messageListener() { // TODO Auto-generated method stub return null; } }
29.22619
89
0.766599
8d91778ba7861b17d94d53ed7a2966500194abb5
893
package com.halo.shardingjdbc.module.deptment.controller; import com.halo.shardingjdbc.module.deptment.entity.TDeptment; import com.halo.shardingjdbc.module.deptment.service.TDeptmentService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * 部门表(用hint根据部门名称分表)(TDeptment)表控制层 * * @author halomzh * @since 2020-09-09 00:04:19 */ @RestController @RequestMapping("tDeptment") public class TDeptmentController { /** * 服务对象 */ @Resource private TDeptmentService tDeptmentService; /** * 通过主键查询单条数据 * * @param id 主键 * @return 单条数据 */ @GetMapping("selectOne") public TDeptment selectOne(Long id) { return this.tDeptmentService.queryById(id); } }
24.135135
70
0.727884
b0cecf78b95fce3a8c4d854a4c26b65e9e04644e
9,542
/* * Copyright (c) 2015. OPPO Co., Ltd. */ package com.k2.mobile.app.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @Title DateUtil.java * @Package com.oppo.mo.utils * @Description 日期工具类 * @Company K2 * * @author Jason.Wu * @date 2015-01-27 15:13:00 * @version V1.0 */ public class DateUtil { /** * 时间字符串格式化(dd-MM-yyyy HH:mm:ss) * * @param time * @return */ public static String datetimeFormat1(String time) { Date date = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat formatter1 = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss"); try { date = formatter.parse(time); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } String changeTime = formatter1.format(date); return changeTime; } /** * 时间字符串格式化(MM.dd hh:mm) * * @param time * @return * @throws ParseException */ public static String datetimeFormat(String time) throws ParseException { if(null == time){ return null; } /* Date date = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date = formatter.parse(time); StringBuilder sb = new StringBuilder(); sb.append(date.getMonth()<10 ? ("0" + date.getMonth()) : (date.getMonth() + "")); sb.append("."); sb.append(date.getDay()<10 ? ("0" + date.getDay()) : (date.getDay() + "")); sb.append(" "); sb.append(date.getHours()<10 ? ("0" + date.getHours()) : (date.getHours() + "")); sb.append(":"); sb.append(date.getMinutes()<10 ? ("0" + date.getMinutes()) : (date.getMinutes() + "")); */ DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = sdf.parse(time); } catch (ParseException e) { e.printStackTrace(); } SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatter = s.format(date); StringBuilder sb = new StringBuilder(); String[] times = formatter.split(" "); if(null != times && times.length > 1){ String[] ymd = times[0].split("-"); if(null != ymd && ymd.length > 2){ sb.append(ymd[1].length()<2 ? "0" + ymd[1] : ymd[1]); sb.append("."); sb.append(ymd[2].length()<2 ? "0" + ymd[2] : ymd[2]); } sb.append(" "); String[] hms = times[1].split(":"); if(null != hms && hms.length > 2){ sb.append(hms[0].length()<2 ? "0" + hms[0] : hms[0]); sb.append(":"); sb.append(hms[1].length()<2 ? "0" + hms[1] : hms[1]); } } return sb.toString(); } /** * 时间字符串格式化(yyyy-MM-dd HH:mm:ss * * @param time * @return */ public static String datetimeFormat2(String time) { Date date = null; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { date = formatter.parse(time); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } String changeTime = formatter1.format(date); return changeTime; } /** * 设置缺省时间 * * @param time * @return */ public static String setDefaultTime(String time) { if (time.equals("2014-01-01 00:00:00")) { time = "----"; } return time; } /** * @return yyyy-MM-dd HH:mm:ss */ public static String getDownloadDateStr() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format(new Date()); } /** * @return yyyyMMdd_HH-mm-ss */ public static String getPhotoDateStr() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HH-mm-ss"); return sdf.format(new Date()); } /** * @return yyyy-MM-dd */ public static String getDate_hms() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); return sdf.format(new Date()); } /** * @return yyyy-MM-dd */ public static String getDate_hms(String time) { if(null == time || "".equals(time.trim())){ return null; } SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date date = null; try { date = ymd.parse(time); } catch (ParseException e) { e.printStackTrace(); } return sdf.format(date); } /** * @return yyyy-MM-dd */ public static String getDate_ymd() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(new Date()); } /** * @return yyyy-MM-dd */ public static String getDate_ymd(String time) { if(null == time || "".equals(time.trim())){ return null; } SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = ymd.parse(time); } catch (ParseException e) { e.printStackTrace(); } return sdf.format(date); } /** * @return yyyy-MM-dd */ public static String getDate_ymdhm(String time) { if(null == time || "".equals(time.trim())){ return null; } SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = null; try { date = ymd.parse(time); } catch (ParseException e) { e.printStackTrace(); } return sdf.format(date); } // /** // * 字符串转换成日期 // * @param str // * @return date // */ // public static Date stringToDateTimeFormat(String str) { // // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date date = null; // try { // date = format.parse(str); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } /** * 字符串转换成日期 * * @param str * @return date */ public static String stringToDateTimeFormat(String str) { String tmp = str.substring(0, 19); return tmp.replace("T", " "); } public static String dateTimeStringFormat(String str) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); try { date = format.parse(str); } catch (ParseException e) { e.printStackTrace(); } return format.format(date); } /** * 根据时区改变时间 * * @param time * @return changeTime */ public static String chageServerTime(String time) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ParsePosition pos = new ParsePosition(0); Date strDate = formatter.parse(time, pos); long utcTime = strDate.getTime(); long localOffset = strDate.getTimezoneOffset() * 60000; long localTime = utcTime - localOffset; Date date = new Date(localTime); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String changeTime = formatter1.format(date); return changeTime; } /** * 根据时区还原�?时区时间 * * @param time * @return changeTime */ public static String recoveryServerTime(String time) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ParsePosition pos = new ParsePosition(0); Date strDate = formatter.parse(time, pos); long utcTime = strDate.getTime(); long localOffset = strDate.getTimezoneOffset() * 60000; long localTime = utcTime + localOffset; Date date = new Date(localTime); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String changeTime = formatter1.format(date); return changeTime; } /** * 解析字符串,获取当天是几号 * * @param time * @return changeTime */ public static int getDay(String str){ int day = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = sdf.parse(str); Calendar cal = Calendar.getInstance(); cal.setTime(date); day = cal.get(Calendar.DATE); //日 } catch (ParseException e) { e.printStackTrace(); } return day; } // 把日期转为字符串 public static String ConverToString(Date date) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(date); } // 把字符串转为日期 public static Date ConverToDate(String strDate) throws Exception { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.parse(strDate); } // 时间对比(天) public static boolean timeComparison(String oldTime, String newTime) { // System.out.println("oldTime = "+oldTime+" , newTime = "+newTime); if(null == oldTime){ return false; } // 转换时间格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date d1 = sdf.parse(oldTime); Date d2 = sdf.parse(newTime); //一个月比较 if(Math.abs(((d1.getTime() - d2.getTime()))) <= 30) { return true; } } catch (ParseException e) { e.printStackTrace(); } return false; } /** * 时间比较大小 * * @param t1、t2 字符串时间, * @return int 比较结果-1:时间格式不正确,0:时间相等,1:t1时间大于t2, 2:t1时间小于t2, */ public static int timeComparingSize(String t1, String t2){ DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar c1=java.util.Calendar.getInstance(); Calendar c2=java.util.Calendar.getInstance(); try { c1.setTime(df.parse(t1)); c2.setTime(df.parse(t2)); }catch(ParseException e){ return -1; // 格式出错 } int result = c1.compareTo(c2); if(result == 0){ return 0; // t1相等t2 } else if (result < 0) { return 2; // t1小于t2 } else { return 1; // t1大于t2 } } }
24.784416
89
0.626598
0062ebfc76b3aaa5ed2996ae0083e106579c7cc3
7,022
package slimeknights.tconstruct.library.tools.helper; import lombok.Getter; import lombok.RequiredArgsConstructor; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Style; import net.minecraft.network.chat.TextColor; import net.minecraft.network.chat.TextComponent; import net.minecraft.util.Mth; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Tier; import slimeknights.tconstruct.TConstruct; import slimeknights.tconstruct.library.modifiers.ModifierEntry; import slimeknights.tconstruct.library.tools.SlotType; import slimeknights.tconstruct.library.tools.nbt.IToolStackView; import slimeknights.tconstruct.library.tools.nbt.ToolStack; import slimeknights.tconstruct.library.tools.stat.INumericToolStat; import slimeknights.tconstruct.library.tools.stat.IToolStat; import slimeknights.tconstruct.library.tools.stat.ToolStats; import slimeknights.tconstruct.library.utils.Util; import java.util.ArrayList; import java.util.List; import java.util.function.UnaryOperator; import static java.awt.Color.HSBtoRGB; /** Builder for tool stats */ @SuppressWarnings("UnusedReturnValue") @RequiredArgsConstructor public class TooltipBuilder { private static final TextColor MAX = valueToColor(1, 1); private static final UnaryOperator<Style> APPLY_MAX = style -> style.withColor(MAX); /** Formatted broken string */ private static final Component TOOLTIP_BROKEN = TConstruct.makeTranslation("tooltip", "tool.broken").withStyle(ChatFormatting.BOLD, ChatFormatting.DARK_RED); /** Prefixed broken string */ private static final Component TOOLTIP_BROKEN_PREFIXED = ToolStats.DURABILITY.getPrefix().append(TOOLTIP_BROKEN); private final IToolStackView tool; @Getter private final List<Component> tooltips; public TooltipBuilder(ToolStack tool) { this.tool = tool; this.tooltips = new ArrayList<>(); } /** * Adds the given text to the tooltip * * @param textComponent the text component to add * @return the tooltip builder */ public TooltipBuilder add(Component textComponent) { this.tooltips.add(textComponent); return this; } /** Formats the stat value */ private <T> Component formatValue(IToolStat<T> stat) { return stat.formatValue(tool.getStats().get(stat)); } /** * Adds the given stat to the tooltip * * @param stat Stat to add * @return the tooltip builder */ public TooltipBuilder add(IToolStat<?> stat) { this.tooltips.add(formatValue(stat)); return this; } /** * Adds harvest tier to the tooltip * * @return the tooltip builder */ public TooltipBuilder addTier() { Tier tier = tool.getDefinition().getData().getHarvestLogic().getTier(tool); this.tooltips.add(ToolStats.HARVEST_TIER.formatValue(tier)); return this; } /** * Adds the given stat to the tooltip if above 0 * * @param stat Stat to add * @return the tooltip builder */ public TooltipBuilder addOptional(INumericToolStat<?> stat) { return addOptional(stat, 1.0f); } /** * Adds the given stat to the tooltip if above 0, scaling by the given value * * @param stat Stat to add * @param scale Amount to scale this value by * @return the tooltip builder */ public TooltipBuilder addOptional(INumericToolStat<?> stat, float scale) { float value = tool.getStats().get(stat).floatValue(); if (value > 0) { this.tooltips.add(stat.formatValue(value * scale)); } return this; } /** Applies formatting for durability with a reference durability */ public static Component formatDurability(int durability, int ref, boolean textIfBroken) { if (textIfBroken && durability == 0) { return TOOLTIP_BROKEN_PREFIXED; } return ToolStats.DURABILITY.getPrefix().append(formatPartialAmount(durability, ref)); } /** * Takes a value between 0.0 and 1.0. * Returns a color between red and green, depending on the value. 1.0 is green. * If the value goes above 1.0 it continues along the color spectrum. */ public static TextColor valueToColor(float value, float max) { // 0.0 -> 0 = red // 1.0 -> 1/3 = green // 1.5 -> 1/2 = aqua float hue = Mth.clamp(((value / max) / 3), 0.01f, 0.5f); return TextColor.fromRgb(HSBtoRGB(hue, 0.65f, 0.8f)); } /** * Formats a fraction with color based on the percent * @param value Value * @param max Max value * @return Formatted amount */ public static Component formatPartialAmount(int value, int max) { return new TextComponent(Util.COMMA_FORMAT.format(value)) .withStyle(style -> style.withColor(valueToColor(value, max))) .append(new TextComponent(" / ").withStyle(ChatFormatting.GRAY)) .append(new TextComponent(Util.COMMA_FORMAT.format(max)).withStyle(APPLY_MAX)); } /** * Adds the durability to the tooltip * * @return the tooltip builder */ public TooltipBuilder addDurability() { // never show broken text in this context this.tooltips.add(formatDurability(tool.getCurrentDurability(), tool.getStats().getInt(ToolStats.DURABILITY), false)); return this; } /** * Adds the given stat to the tooltip, summing in the attribute value * * @return the tooltip builder */ public TooltipBuilder addWithAttribute(INumericToolStat<?> stat, Attribute attribute) { float damage = (float) attribute.getDefaultValue(); Player player = Minecraft.getInstance().player; if (player != null) { AttributeInstance instance = player.getAttribute(attribute); if (instance != null) { damage = (float) instance.getBaseValue(); } } this.tooltips.add(stat.formatValue(damage + tool.getStats().get(stat).floatValue())); return this; } /** * Adds the specific free slot to the tooltip * @param slotType Type of slot to add * @return the tooltip builder */ public TooltipBuilder addFreeSlots(SlotType slotType) { int slots = tool.getFreeSlots(slotType); if (slots > 0) { this.tooltips.add(IToolStat.formatNumber(slotType.getPrefix(), slotType.getColor(), slots)); } return this; } /** * Adds the current free modifiers to the tooltip * * @return the tooltip builder */ public TooltipBuilder addAllFreeSlots() { for (SlotType slotType : SlotType.getAllSlotTypes()) { addFreeSlots(slotType); } return this; } /** * Adds the modifier information to the tooltip * * @return the tooltip builder */ public TooltipBuilder addModifierInfo(boolean advanced) { for (ModifierEntry entry : tool.getModifierList()) { if (entry.getModifier().shouldDisplay(advanced)) { this.tooltips.add(entry.getModifier().getDisplayName(tool, entry.getLevel())); } } return this; } }
32.063927
159
0.711051
886056a960649e0935ddd80afa96909eaf55b380
172
package Interface; public class EmiteCachorro implements EmiteSom { @Override public void emitirSom() { System.out.println("A cachorro diz Au AU"); } }
17.2
49
0.680233
79d5dfb6ebace9c2857084a1a3ebf770152f2dcf
1,189
package org.apereo.cas.uma.web.controllers.permission; import org.apereo.cas.uma.web.controllers.BaseUmaEndpointControllerTests; import lombok.val; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link UmaPermissionRegistrationEndpointControllerTests}. * * @author Misagh Moayyed * @since 6.0.0 */ @Tag("OAuth") public class UmaPermissionRegistrationEndpointControllerTests extends BaseUmaEndpointControllerTests { @Test public void verifyPermissionRegistrationOperation() throws Exception { val results = authenticateUmaRequestWithProtectionScope(); val body = createUmaPermissionRegistrationRequest(100).toJson(); val response = umaPermissionRegistrationEndpointController.handle(body, results.getLeft(), results.getMiddle()); assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); assertNotNull(response.getBody()); val model = (Map) response.getBody(); assertTrue(model.containsKey("code")); assertTrue(model.containsKey("message")); } }
34.970588
120
0.75778
b87979b580f09d2256ad1ca205a8e6cd9c294b18
1,315
/* * @author Jon Deering Copyright 2011 Saint Louis University. Licensed under the Educational Community 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.osedu.org/licenses/ECL-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 detectimages; import java.io.Serializable; public class pixel implements Comparable, Serializable { protected short x; protected short y; public pixel(int a, int b) { x = (short) a; y = (short) b; } public int compare(Object o1, Object o2) { pixel a = (pixel) o1; pixel b = (pixel) o2; if (a.x < b.x) { return 1; } if (a.x > b.x) { return -1; } return 0; } public int compareTo(Object o) { pixel b = (pixel) o; if (this.x < b.x) { return 1; } if (this.x > b.x) { return -1; } return 0; } }
23.909091
137
0.604563
bdf56ed4bc0430df75902d97ca469ee23324d6c8
4,116
package br.fapema.morholt.android.initial.load; import java.util.ArrayList; import java.util.Collection; import java.util.List; import br.fapema.morholt.android.R; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.TextView; import br.fapema.morholt.android.MyApplication; import br.fapema.morholt.android.db.DBHelper; import br.fapema.morholt.android.model.ProjectInfo; import br.fapema.morholt.android.wizardpager.wizard.basic.Values; public class LoadActivity extends BaseListActivity { private LoadListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.initial_load); final List<LoadListValues> loadList = getLoadList(); setHeaders(loadList); ListView view = (ListView) findViewById(android.R.id.list); adapter = new LoadListAdapter(getApplicationContext(), this, loadList); view.setAdapter(adapter); /* view.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(view.getContext(), "xxx", Toast.LENGTH_SHORT).show(); } });*/ } private void setHeaders(final List<LoadListValues> loadList) { TextView description1 = (TextView) findViewById(R.id.header_line1); TextView description2 = (TextView) findViewById(R.id.header_line2); description1.setText("Carregar coleta"); description2.setText("Escolha:"); TextView columnHeader1 = (TextView) findViewById(R.id.column_header1); TextView columnHeader2 = (TextView) findViewById(R.id.column_header2); TextView columnHeader3 = (TextView) findViewById(R.id.column_header3); TextView columnHeader4 = (TextView) findViewById(R.id.column_header4); TextView columnHeader5 = (TextView) findViewById(R.id.column_header5); TextView columnHeader6 = (TextView) findViewById(R.id.column_delete); if (loadList.size() > 0) { columnHeader1.setText(loadList.get(0).getColumnOneHeader()); columnHeader2.setText(loadList.get(0).getColumnTwoHeader()); columnHeader3.setText(loadList.get(0).getColumnThreeHeader()); columnHeader4.setText(loadList.get(0).getColumnFourHeader()); columnHeader5.setText(loadList.get(0).getColumnPhotoSentToServerHeader()); columnHeader6.setText(loadList.get(0).getColumnDelete()); } } private List<LoadListValues> getLoadList() { List< LoadListValues> threeColumnListViewInterface = new ArrayList<LoadListValues>(); List<Values> collects = DBHelper.listAll(ProjectInfo.getTableName(), "_id desc"); for (Values values : collects) { threeColumnListViewInterface.add(new LoadListValues(values)); } return threeColumnListViewInterface; } @Override public void onListItemClick(ListView l, View v, final int position, long id) { super.onListItemClick(l, v, position, id); Values selectedItem = (Values) adapter.getItem(position); openLoadDialog(position, selectedItem); } private void openLoadDialog(final int position, Values selectedItem) { new AlertDialog.Builder(this).setTitle("Carregar?") .setMessage("Quer carregar esse item,\n id = " + selectedItem.getAsString("_id") + ", np = " + selectedItem.getAsText("np") + " ?") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { loadDataIntoApplication(position); open(R.id.action_edit); } private void loadDataIntoApplication(final int position) { Values selectedItem = (Values) adapter.getItem(position); MyApplication application = (MyApplication) getApplication(); // application.setPreData(selectedItem.preData); application.setValues(selectedItem); application.setCurrentCollectPage(0); application.setLoaded(true); application.pagelist.initializeRepeats(); } }).setNegativeButton(android.R.string.no, null).show(); } }
38.111111
137
0.75826
b2d5ba633be43b34f32ae5d18a66f154d629221a
1,356
package state_manager; import java.util.ArrayList; import cell.SugarCell; import grid.Grid; import grid.Location; import simulation_objects.SugarAgent; public class SugarStateManager extends StateManager{ public static final String SIMULATION_NAME = "Sugar"; public SugarStateManager(Grid initialState) { super(initialState); } @Override public void handleCell(Location loc) { SugarCell currentCell = (SugarCell)currentGrid.get(loc); SugarAgent currentAgent = currentCell.getSugarAgent(); if (currentAgent != null) { Location toMove = neighborWithMostSugar(loc, currentAgent); if (toMove != null) { ((SugarCell) tempGrid.get(toMove)).moveInAgent(currentAgent); ((SugarCell) tempGrid.get(loc)).removeAgent(); } } else { currentCell.regenSugar(); } } private Location neighborWithMostSugar(Location loc, SugarAgent currentAgent) { ArrayList<Location> neighborsInVisionLocations = currentGrid.getNeighborsInVision(loc, currentAgent.getVision()); int maxSugar = -1; Location locationToMove = null; for (Location l : neighborsInVisionLocations) { if (((SugarCell) currentGrid.get(l)).getSugar() > maxSugar && ((SugarCell)currentGrid.get(l)).getSugarAgent() == null) { maxSugar = ((SugarCell) currentGrid.get(l)).getSugar(); locationToMove = l; } } return locationToMove; } }
26.588235
123
0.733038
42111ed0a3053abbe04612fb667cddf8a1f018ec
3,742
package uk.gov.hmcts.reform.sscscorbackend.thirdparty.ccd; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; import java.util.List; import org.junit.Before; import org.junit.Test; import uk.gov.hmcts.reform.ccd.client.CoreCaseDataApi; import uk.gov.hmcts.reform.sscs.ccd.config.CcdRequestDetails; import uk.gov.hmcts.reform.sscs.ccd.service.CreateCcdCaseService; import uk.gov.hmcts.reform.sscs.ccd.service.ReadCcdCaseService; import uk.gov.hmcts.reform.sscs.ccd.service.SearchCcdCaseService; import uk.gov.hmcts.reform.sscs.ccd.service.UpdateCcdCaseService; import uk.gov.hmcts.reform.sscs.idam.IdamService; import uk.gov.hmcts.reform.sscs.idam.IdamTokens; import uk.gov.hmcts.reform.sscscorbackend.thirdparty.ccd.api.CcdAddUser; import uk.gov.hmcts.reform.sscscorbackend.thirdparty.ccd.api.CcdHistoryEvent; public class CorCcdServiceTest { private CcdClient ccdClient; private IdamService idamService; private String authToken; private String serviceAuthToken; private String userId; private String jurisdictionId; private String caseTypeId; private CcdRequestDetails ccdRequestDetails; private CorCcdService corCcdService; private long caseId; @Before public void setUp() throws Exception { ccdClient = mock(CcdClient.class); idamService = mock(IdamService.class); authToken = "authToken"; serviceAuthToken = "serviceAuthToken"; userId = "userId"; when(idamService.getIdamTokens()).thenReturn( IdamTokens.builder().idamOauth2Token(authToken).serviceAuthorization(serviceAuthToken).userId(userId).build() ); jurisdictionId = "jurisdictionId"; caseTypeId = "caseTypeId"; ccdRequestDetails = CcdRequestDetails.builder() .jurisdictionId(jurisdictionId) .caseTypeId(caseTypeId) .build(); corCcdService = new CorCcdService( mock(CreateCcdCaseService.class), mock(SearchCcdCaseService.class), mock(UpdateCcdCaseService.class), mock(ReadCcdCaseService.class), ccdClient, idamService, ccdRequestDetails, mock(CoreCaseDataApi.class) ); caseId = 123L; } @Test public void canAddUserToCase() { String userToAdd = "userToAdd"; corCcdService.addUserToCase(userToAdd, caseId); verify(ccdClient).addUserToCase( authToken, serviceAuthToken, userId, jurisdictionId, caseTypeId, caseId, new CcdAddUser(userToAdd) ); } @Test public void canRemoveAUser() { String userToRemove = "userToRemove"; corCcdService.removeUserFromCase(userToRemove, caseId); verify(ccdClient).removeUserFromCase(authToken, serviceAuthToken, userId, jurisdictionId, caseTypeId, caseId, userToRemove); } @Test public void canGetHistoryEvents() { List<CcdHistoryEvent> historyEvents = asList(new CcdHistoryEvent("id")); when(ccdClient.getHistoryEvents(authToken, serviceAuthToken, userId, jurisdictionId, caseTypeId, caseId)).thenReturn(historyEvents); List<CcdHistoryEvent> actualHistoryEvents = corCcdService.getHistoryEvents(caseId); assertThat(actualHistoryEvents, is(historyEvents)); } }
34.648148
125
0.656601
26eb16100ae7c55c268d5740e611b527c7ec69dc
2,825
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.examples.nqueens.domain; import java.util.List; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningScore; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty; import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.examples.common.domain.AbstractPersistable; import org.optaplanner.persistence.xstream.api.score.buildin.simple.SimpleScoreXStreamConverter; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; @PlanningSolution @XStreamAlias("NQueens") public class NQueens extends AbstractPersistable { private int n; private List<Column> columnList; private List<Row> rowList; private List<Queen> queenList; @XStreamConverter(SimpleScoreXStreamConverter.class) private SimpleScore score; public int getN() { return n; } public void setN(int n) { this.n = n; } @ProblemFactCollectionProperty public List<Column> getColumnList() { return columnList; } public void setColumnList(List<Column> columnList) { this.columnList = columnList; } @ValueRangeProvider(id = "rowRange") @ProblemFactCollectionProperty public List<Row> getRowList() { return rowList; } public void setRowList(List<Row> rowList) { this.rowList = rowList; } @PlanningEntityCollectionProperty public List<Queen> getQueenList() { return queenList; } public void setQueenList(List<Queen> queenList) { this.queenList = queenList; } @PlanningScore public SimpleScore getScore() { return score; } public void setScore(SimpleScore score) { this.score = score; } // ************************************************************************ // Complex methods // ************************************************************************ }
29.123711
96
0.689912
1930d2e40b381651c68edaab453f0fceed49423c
309
package ru.textanalysis.tawt.awf.rule; import ru.textanalysis.tawt.ms.model.sp.Word; public interface AwfRules { void init(); boolean establishRelation(Word main, Word dep); boolean establishRelation(int i, Word main, Word rightWord); boolean establishRelationForPretext(Word pretext, Word word); }
20.6
62
0.779935
aa14e36484a895c21cc7bb0c40cc7463399b384b
5,337
package org.firstinspires.ftc.teamcode.ServoTestPractice; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.SubSystems.Robot; import java.io.IOException; @TeleOp(name="Servo Test KhizarK") public class ServoTest_KhizarKhan extends LinearOpMode{ private Robot robot; double PreTime = 0; double CurrentTime = 0; ElapsedTime timer = new ElapsedTime(); public void initOpMode() throws IOException { this.robot = new Robot (this, timer); } public void runOpMode() { try { initOpMode(); } catch (IOException e) { e.printStackTrace(); } robot.initServosAuto(); telemetry.clearAll(); waitForStart(); //waits for start while (opModeIsActive()) { //Get gamepad inputs robot.getGamePadInputs(); //Get the current time CurrentTime = timer.nanoseconds(); //GAMEPAD 1 CODE //main claw arm servo test if (robot.leftStickX > 0.5) //controls main claw ARM itself robot.control.modifyServo(robot.mainClawArm, 0.005); else if (robot.leftStickX > 0.1) robot.control.modifyServo(robot.mainClawArm, 0.001); else if (robot.leftStickX > -0.1) //do nothing robot.control.modifyServo(robot.mainClawArm, -0.0); else if (robot.leftStickX > -0.5) robot.control.modifyServo(robot.mainClawArm, -0.001); else robot.control.modifyServo(robot.mainClawArm, -0.005); if (robot.rightStickY > 0.5) //these control main claw arm rotation robot.control.modifyServo(robot.mainClawRotation, 0.005); else if (robot.rightStickY > 0.1) robot.control.modifyServo(robot.mainClawRotation, 0.001); else if (robot.rightStickY > -0.1) //do nothing robot.control.modifyServo(robot.mainClawRotation, -0.0); else if (robot.rightStickY > -0.5) robot.control.modifyServo(robot.mainClawRotation, -0.001); else robot.control.modifyServo(robot.mainClawRotation, -0.005); if (robot.rightStickX > 0.5) //controls main claw itself robot.control.modifyServo(robot.mainClaw,0.005); else if (robot.rightStickX > 0.1) robot.control.modifyServo(robot.mainClaw,0.001); else if (robot.rightStickX > -0.1) //do nothing robot.control.modifyServo(robot.mainClaw,0.0); else if (robot.rightStickX > -0.5) robot.control.modifyServo(robot.mainClaw,-0.001); else robot.control.modifyServo(robot.mainClaw,-0.005); //EVERYTHING FROM HERE IS GAMEPAD 2 //controls servos for capstone arms if (robot.leftStickX2 > 0.5) //controls capstone arm robot.control.modifyServo(robot.csArm,0.005); else if (robot.leftStickX2 > 0.1) robot.control.modifyServo(robot.csArm,0.001); else if (robot.leftStickX2 > -0.1) //do nothing robot.control.modifyServo(robot.csArm,0.0); else if (robot.leftStickX2 > -0.5) robot.control.modifyServo(robot.csArm,-0.001); else robot.control.modifyServo(robot.csArm,-0.005); if (robot.rightStickX2 > 0.5) //controls capstone claw robot.control.modifyServo(robot.csClaw,0.005); else if (robot.rightStickX2 > 0.1) robot.control.modifyServo(robot.csClaw,0.001); else if (robot.rightStickX2 > -0.1) //do nothing robot.control.modifyServo(robot.csClaw,0.0); else if (robot.rightStickX2 > -0.5) robot.control.modifyServo(robot.csClaw,-0.001); else robot.control.modifyServo(robot.csClaw,-0.005); //control servos for foundation claw if (robot.leftStickY2 > 0.5) //controls left foundation claw robot.control.modifyServo(robot.fClawL,0.005); else if (robot.leftStickY2 > 0.1) robot.control.modifyServo(robot.fClawL,0.001); else if (robot.leftStickY2 > -0.1) //do nothing robot.control.modifyServo(robot.fClawL,0.0); else if (robot.leftStickY2 > -0.5) robot.control.modifyServo(robot.fClawL,-0.001); else robot.control.modifyServo(robot.fClawL,-0.005); if (robot.rightStickY2 > 0.5) //controls right foundation claw robot.control.modifyServo(robot.fClawR,0.005); else if (robot.rightStickY2 > 0.1) robot.control.modifyServo(robot.fClawR,0.001); else if (robot.rightStickY2 > -0.1) //do nothing robot.control.modifyServo(robot.fClawR,0.0); else if (robot.rightStickY2 > -0.5) robot.control.modifyServo(robot.fClawR,-0.001); else robot.control.modifyServo(robot.fClawR,-0.005); sleep(100); } } }
38.956204
79
0.588158
bc38401ee0c3c9c9728bb2158eb374224d66953d
90
package org.eclipse.dataspaceconnector.spi.iam; public interface RegistrationService { }
18
47
0.833333
de602b19786f83300140e3b657b3d9ff25d505b1
2,740
package org.loadtest4j.drivers.jmeter.util; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.JarURLConnection; import java.net.URL; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; public final class Resources { private Resources() {} /** * Adapted from https://github.com/nguyenq/tess4j * * @param source the jar resource (file or 'folder') * @param destination the destination to copy the resource to * @throws IOException if copying didn't work */ public static void copy(String source, File destination) throws IOException { final URL resourceUrl = Resources.class.getClassLoader().getResource(source); final JarURLConnection jarConnection; try { jarConnection = (JarURLConnection) resourceUrl.openConnection(); } catch (NullPointerException e) { throw new IOException("Could not open a connection to the URL: " + source); } try (JarFile jarFile = jarConnection.getJarFile()) { String jarConnectionEntryName = jarConnection.getEntryName(); if (!jarConnectionEntryName.endsWith("/")) { jarConnectionEntryName += "/"; } // Iterate all entries in the jar file. for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) { final JarEntry jarEntry = e.nextElement(); final String jarEntryName = jarEntry.getName(); // Extract files only if they match the path. if (jarEntryName.startsWith(jarConnectionEntryName)) { final String filename = jarEntryName.substring(jarConnectionEntryName.length()); final File targetFile = new File(destination, filename); if (jarEntry.isDirectory()) { final boolean success = targetFile.mkdirs(); if (!success) { throw new IOException("Mkdir failed for: " + targetFile.getAbsolutePath()); } } else { if (!targetFile.exists() || targetFile.length() != jarEntry.getSize()) { try (InputStream is = jarFile.getInputStream(jarEntry); OutputStream out = FileUtils.openOutputStream(targetFile)) { IOUtils.copy(is, out); } } } } } } } }
38.591549
103
0.579197
dac185155420e53724a6af0ff4642fa16d5e150e
2,992
package org.jnet.core.helper; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import sun.reflect.ReflectionFactory; import com.google.common.collect.ImmutableMap; public class PojoHelper { public static final List<Class<?>> primitiveTypes = Arrays.asList(Boolean.class, Byte.class, Short.class, Character.class, Integer.class, Long.class, Float.class, Double.class, String.class); public static final List<Class<?>> arrayTypes = Arrays.asList(boolean[].class, byte[].class, short[].class, char[].class, int[].class, long[].class, float[].class, double[].class, Object[].class); private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new ImmutableMap.Builder<Class<?>, Class<?>>() .put(boolean.class, Boolean.class).put(byte.class, Byte.class).put(char.class, Character.class) .put(double.class, Double.class).put(float.class, Float.class).put(int.class, Integer.class) .put(long.class, Long.class).put(short.class, Short.class).put(void.class, Void.class).build(); private PojoHelper() { } public static boolean isPrimitive(Class<?> clazz) { return clazz.isPrimitive() || primitiveTypes.contains(clazz); } public static void forEachField(Object object, int mofifiersToIgnore, FieldConsumer consumer) throws Exception { Class<?> clazz = object.getClass(); while (clazz != Object.class) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if ((field.getModifiers() & mofifiersToIgnore) != 0) { continue; } boolean isAccessible = field.isAccessible(); field.setAccessible(true); Object fieldValue = field.get(object); consumer.consume(field, fieldValue); field.setAccessible(isAccessible); } clazz = clazz.getSuperclass(); } } public static interface FieldConsumer { void consume(Field field, Object value) throws Exception; } @SuppressWarnings("unchecked") public static <T> Class<T> primitiveToWrapper(Class<T> c) { return c.isPrimitive() ? (Class<T>) PRIMITIVES_TO_WRAPPERS.get(c) : c; } @SuppressWarnings("unchecked") public static <T> T instantiate(Class<T> cls) { return Unchecker.uncheck(() -> { try { Constructor<T> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { // Create instance of the given class final Constructor<T> constructor = (Constructor<T>) cls.getDeclaredConstructors()[0]; constructor.setAccessible(true); final List<Object> params = new ArrayList<Object>(); for (Class<?> pType : constructor.getParameterTypes()) { params.add((pType.isPrimitive()) ? PojoHelper.primitiveToWrapper(pType).newInstance() : null); } return cls.cast(constructor.newInstance(params.toArray())); } }); } }
36.048193
118
0.696858
929fd428a16cb26dfe3d9e360978f9eada4f4a1c
2,101
package bu.dsp.fgraph; import java.time.Duration; import java.util.TreeSet; import javax.annotation.Nonnull; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.statefun.sdk.Context; import org.apache.flink.statefun.sdk.StatefulFunction; import org.apache.flink.statefun.sdk.annotations.Persisted; import org.apache.flink.statefun.sdk.state.Expiration; import org.apache.flink.statefun.sdk.state.PersistedTable; import bu.dsp.fgraph.FGraphMessages.EdgeMessage; import bu.dsp.fgraph.FGraphMessages.OutputMessage; import bu.dsp.fgraph.FGraphTypes.Vertex; final class FGraphFunction implements StatefulFunction { // PersistedTable<srcId, neighbors-sorted-by-timestamp> @Persisted PersistedTable<String, TreeSet<Vertex>> relationsTable = PersistedTable.of( "relations-table", String.class, TypeInformation.of(new TypeHint<TreeSet<Vertex>>(){}).getTypeClass(), Expiration.expireAfterWriting(Duration.ofHours(1))); @Override public void invoke(Context context, Object input) { if (!(input instanceof EdgeMessage)) { throw new IllegalArgumentException("Unknown message received " + input); } EdgeMessage in = (EdgeMessage) input; // get neighbors of the vertex from the table TreeSet<Vertex> nbs = getNbsFromTable(in.getSrcId()); // if exists, return false and do nothing nbs.add(new Vertex(in.getSrcId(), in.getDstId(), in.getTimestamp())); // update the table relationsTable.set(in.getSrcId(), nbs); OutputMessage out = new OutputMessage(in.getSrcId(), in.getDstId(), in.getTimestamp()); context.send(FGraphConstants.RESULT_EGRESS, out); } /** * Get neighbors treeset from table */ @Nonnull private TreeSet<Vertex> getNbsFromTable(String key) { TreeSet<Vertex> nbs = null; if (relationsTable.get(key) == null) { nbs = new TreeSet<Vertex>(new FGraphTypes.Vertex.NeighborComparator()); relationsTable.set(key, nbs); return nbs; } return relationsTable.get(key); } }
32.828125
91
0.732984
915b946535a8cc2b3834bad31da1eb976a0206c2
5,791
/* * 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 br.senac.tads3.pi03b.projetoautomata.servlets; import br.senac.tads3.pi03b.projetoautomata.dao.ProdutoDAO; import br.senac.tads3.pi03b.projetoautomata.dao.UnidadeDAO; import br.senac.tads3.pi03b.projetoautomata.models.Produto; import br.senac.tads3.pi03b.projetoautomata.services.ProdutoService; import br.senac.tads3.pi03b.projetoautomata.utils.Funcoes; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author matheus_santo */ @WebServlet(name = "ProdutoServlet", urlPatterns = {"/produtos"}) public class ProdutoServlet extends HttpServlet { private ProdutoService service; private ProdutoDAO dao; private UnidadeDAO daoU; public static final String LIST = "WEB-INF/jsp/lista_produtos.jsp"; public static final String INSERT_OR_EDIT = "WEB-INF/jsp/produto_cadastrar.jsp"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forward = ""; String action = request.getParameter("action"); dao = new ProdutoDAO(); daoU = new UnidadeDAO(); try { request.setAttribute("listaUnidades", daoU.getListaUnidades()); } catch (SQLException ex) { Logger.getLogger(ProdutoServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ProdutoServlet.class.getName()).log(Level.SEVERE, null, ex); } if ("delete".equalsIgnoreCase(action)) { forward = LIST; String id = String.valueOf(request.getParameter("id")); try { dao.excluir(id); } catch (Exception ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } try { request.setAttribute("produtos", dao.getListaProdutos()); } catch (SQLException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } } else if ("edit".equalsIgnoreCase(action)) { forward = INSERT_OR_EDIT; String id = request.getParameter("id"); Produto produto = null; try { produto = dao.getProdutoById(id); request.setAttribute("uni", produto.getUnidade()); request.setAttribute("status", produto.getInativo()); } catch (SQLException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("produto", produto); } else if ("insert".equalsIgnoreCase(action)) { forward = INSERT_OR_EDIT; } else { forward = LIST; try { request.setAttribute("produtos", dao.getListaProdutos()); } catch (SQLException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } } RequestDispatcher view = request.getRequestDispatcher(forward); view.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Funcoes func = new Funcoes(); Produto produto = new Produto(); produto.setId(request.getParameter("id")); produto.setModelo(request.getParameter("modelo")); produto.setUnidade(request.getParameter("unidade")); produto.setValorCusto(Double.parseDouble(func.tiraNaoNumero(request.getParameter("valorCusto")))); produto.setValorVenda(Double.parseDouble(func.tiraNaoNumero(request.getParameter("valorVenda")))); produto.setNotasInternas(request.getParameter("notasInternas")); produto.setInativo(Integer.parseInt(request.getParameter("inativo"))); service = new ProdutoService(); if (service.validarCampos(produto)) { dao = new ProdutoDAO(); try { dao.acao(produto); } catch (Exception ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } } RequestDispatcher view = request.getRequestDispatcher(LIST); try { request.setAttribute("produtos", dao.getListaProdutos()); } catch (SQLException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex); } view.forward(request, response); } }
45.242188
123
0.634605
fe27ec40ed6b428dff6c742e4fcf9c908a1dfeec
931
package sanjurjo7.lucre; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid=Lucre.MODID, name=Lucre.MODNAME, version=Lucre.VERSION) public class Lucre { public static final String MODID = "lucre"; public static final String MODNAME = "Lucre"; public static final String VERSION = "0.0.1"; @Instance public static Lucre instance = new Lucre(); @EventHandler public void preInit (FMLPreInitializationEvent e) { } @EventHandler public void init (FMLInitializationEvent e) { } @EventHandler public void postInit (FMLPostInitializationEvent e) { } } }
27.382353
70
0.754028
f5b63adc30c51a5a987570edb53677b664ff2fc8
784
package edu.nccu.cs.recorder.util; import java.nio.ByteBuffer; import java.util.Arrays; public class ByteUtils { public static byte[] getBytesFromLong(final long i) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(i); return buffer.array(); } public static byte[] mergeByteArrays(final byte[] array1, byte[] array2) { byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } public static long getLongFromBytes(byte[] bytes) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.put(bytes); buffer.flip(); return buffer.getLong(); } }
30.153846
82
0.664541
5b98444fe2755e7c22d4e17de4d2ccfefbdb9bd8
665
package com.yapp.yongyong.domain.user.mapper; import com.yapp.yongyong.domain.user.dto.UserDto; import com.yapp.yongyong.domain.user.entity.User; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; @Mapper public interface UserMapper { UserMapper INSTANCE = Mappers.getMapper(UserMapper.class); @Mapping(source = "user.id", target = "id") @Mapping(source = "user.nickname",target = "nickname") @Mapping(source = "user.email",target = "email") @Mapping(source = "user.imageUrl",target = "imageUrl") @Mapping(source = "user.introduction",target = "introduction") UserDto toDto(User user); }
33.25
66
0.730827
74fa50e85c7ef2aa99253db5997b85cddb4f0ff4
33,571
/* * (C) Copyright IBM Corp. 2020. * * 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.ibm.cloud.blockchain.v3.model; import com.ibm.cloud.blockchain.v3.model.ClientAuth; import com.ibm.cloud.blockchain.v3.model.ConfigPeerAdminService; import com.ibm.cloud.blockchain.v3.model.ConfigPeerAuthentication; import com.ibm.cloud.blockchain.v3.model.ConfigPeerChaincode; import com.ibm.cloud.blockchain.v3.model.ConfigPeerChaincodeExternalBuildersItem; import com.ibm.cloud.blockchain.v3.model.ConfigPeerChaincodeGolang; import com.ibm.cloud.blockchain.v3.model.ConfigPeerChaincodeLogging; import com.ibm.cloud.blockchain.v3.model.ConfigPeerChaincodeSystem; import com.ibm.cloud.blockchain.v3.model.ConfigPeerClient; import com.ibm.cloud.blockchain.v3.model.ConfigPeerDeliveryclient; import com.ibm.cloud.blockchain.v3.model.ConfigPeerDeliveryclientAddressOverridesItem; import com.ibm.cloud.blockchain.v3.model.ConfigPeerDiscovery; import com.ibm.cloud.blockchain.v3.model.ConfigPeerGossip; import com.ibm.cloud.blockchain.v3.model.ConfigPeerGossipElection; import com.ibm.cloud.blockchain.v3.model.ConfigPeerGossipPvtData; import com.ibm.cloud.blockchain.v3.model.ConfigPeerGossipPvtDataImplicitCollectionDisseminationPolicy; import com.ibm.cloud.blockchain.v3.model.ConfigPeerGossipState; import com.ibm.cloud.blockchain.v3.model.ConfigPeerKeepalive; import com.ibm.cloud.blockchain.v3.model.ConfigPeerKeepaliveClient; import com.ibm.cloud.blockchain.v3.model.ConfigPeerKeepaliveDeliveryClient; import com.ibm.cloud.blockchain.v3.model.ConfigPeerLimits; import com.ibm.cloud.blockchain.v3.model.ConfigPeerLimitsConcurrency; import com.ibm.cloud.blockchain.v3.model.ConfigPeerUpdate; import com.ibm.cloud.blockchain.v3.model.ConfigPeerUpdatePeer; import com.ibm.cloud.blockchain.v3.model.CryptoEnrollmentComponent; import com.ibm.cloud.blockchain.v3.model.Metrics; import com.ibm.cloud.blockchain.v3.model.MetricsStatsd; import com.ibm.cloud.blockchain.v3.model.NodeOu; import com.ibm.cloud.blockchain.v3.model.PeerResources; import com.ibm.cloud.blockchain.v3.model.ResourceLimits; import com.ibm.cloud.blockchain.v3.model.ResourceObject; import com.ibm.cloud.blockchain.v3.model.ResourceObjectCouchDb; import com.ibm.cloud.blockchain.v3.model.ResourceObjectFabV1; import com.ibm.cloud.blockchain.v3.model.ResourceObjectFabV2; import com.ibm.cloud.blockchain.v3.model.ResourceRequests; import com.ibm.cloud.blockchain.v3.model.UpdateEnrollmentCryptoField; import com.ibm.cloud.blockchain.v3.model.UpdateEnrollmentCryptoFieldCa; import com.ibm.cloud.blockchain.v3.model.UpdateEnrollmentCryptoFieldTlsca; import com.ibm.cloud.blockchain.v3.model.UpdateMspCryptoField; import com.ibm.cloud.blockchain.v3.model.UpdateMspCryptoFieldCa; import com.ibm.cloud.blockchain.v3.model.UpdateMspCryptoFieldComponent; import com.ibm.cloud.blockchain.v3.model.UpdateMspCryptoFieldTlsca; import com.ibm.cloud.blockchain.v3.model.UpdatePeerBodyCrypto; import com.ibm.cloud.blockchain.v3.model.UpdatePeerOptions; import com.ibm.cloud.blockchain.v3.utils.TestUtilities; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Unit test class for the UpdatePeerOptions model. */ public class UpdatePeerOptionsTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testUpdatePeerOptions() throws Throwable { ConfigPeerKeepaliveClient configPeerKeepaliveClientModel = new ConfigPeerKeepaliveClient.Builder() .interval("60s") .timeout("20s") .build(); assertEquals(configPeerKeepaliveClientModel.interval(), "60s"); assertEquals(configPeerKeepaliveClientModel.timeout(), "20s"); ConfigPeerKeepaliveDeliveryClient configPeerKeepaliveDeliveryClientModel = new ConfigPeerKeepaliveDeliveryClient.Builder() .interval("60s") .timeout("20s") .build(); assertEquals(configPeerKeepaliveDeliveryClientModel.interval(), "60s"); assertEquals(configPeerKeepaliveDeliveryClientModel.timeout(), "20s"); ConfigPeerKeepalive configPeerKeepaliveModel = new ConfigPeerKeepalive.Builder() .minInterval("60s") .client(configPeerKeepaliveClientModel) .deliveryClient(configPeerKeepaliveDeliveryClientModel) .build(); assertEquals(configPeerKeepaliveModel.minInterval(), "60s"); assertEquals(configPeerKeepaliveModel.client(), configPeerKeepaliveClientModel); assertEquals(configPeerKeepaliveModel.deliveryClient(), configPeerKeepaliveDeliveryClientModel); ConfigPeerGossipElection configPeerGossipElectionModel = new ConfigPeerGossipElection.Builder() .startupGracePeriod("15s") .membershipSampleInterval("1s") .leaderAliveThreshold("10s") .leaderElectionDuration("5s") .build(); assertEquals(configPeerGossipElectionModel.startupGracePeriod(), "15s"); assertEquals(configPeerGossipElectionModel.membershipSampleInterval(), "1s"); assertEquals(configPeerGossipElectionModel.leaderAliveThreshold(), "10s"); assertEquals(configPeerGossipElectionModel.leaderElectionDuration(), "5s"); ConfigPeerGossipPvtDataImplicitCollectionDisseminationPolicy configPeerGossipPvtDataImplicitCollectionDisseminationPolicyModel = new ConfigPeerGossipPvtDataImplicitCollectionDisseminationPolicy.Builder() .requiredPeerCount(Double.valueOf("0")) .maxPeerCount(Double.valueOf("1")) .build(); assertEquals(configPeerGossipPvtDataImplicitCollectionDisseminationPolicyModel.requiredPeerCount(), Double.valueOf("0")); assertEquals(configPeerGossipPvtDataImplicitCollectionDisseminationPolicyModel.maxPeerCount(), Double.valueOf("1")); ConfigPeerGossipPvtData configPeerGossipPvtDataModel = new ConfigPeerGossipPvtData.Builder() .pullRetryThreshold("60s") .transientstoreMaxBlockRetention(Double.valueOf("1000")) .pushAckTimeout("3s") .btlPullMargin(Double.valueOf("10")) .reconcileBatchSize(Double.valueOf("10")) .reconcileSleepInterval("1m") .reconciliationEnabled(true) .skipPullingInvalidTransactionsDuringCommit(false) .implicitCollectionDisseminationPolicy(configPeerGossipPvtDataImplicitCollectionDisseminationPolicyModel) .build(); assertEquals(configPeerGossipPvtDataModel.pullRetryThreshold(), "60s"); assertEquals(configPeerGossipPvtDataModel.transientstoreMaxBlockRetention(), Double.valueOf("1000")); assertEquals(configPeerGossipPvtDataModel.pushAckTimeout(), "3s"); assertEquals(configPeerGossipPvtDataModel.btlPullMargin(), Double.valueOf("10")); assertEquals(configPeerGossipPvtDataModel.reconcileBatchSize(), Double.valueOf("10")); assertEquals(configPeerGossipPvtDataModel.reconcileSleepInterval(), "1m"); assertEquals(configPeerGossipPvtDataModel.reconciliationEnabled(), Boolean.valueOf(true)); assertEquals(configPeerGossipPvtDataModel.skipPullingInvalidTransactionsDuringCommit(), Boolean.valueOf(false)); assertEquals(configPeerGossipPvtDataModel.implicitCollectionDisseminationPolicy(), configPeerGossipPvtDataImplicitCollectionDisseminationPolicyModel); ConfigPeerGossipState configPeerGossipStateModel = new ConfigPeerGossipState.Builder() .enabled(true) .checkInterval("10s") .responseTimeout("3s") .batchSize(Double.valueOf("10")) .blockBufferSize(Double.valueOf("100")) .maxRetries(Double.valueOf("3")) .build(); assertEquals(configPeerGossipStateModel.enabled(), Boolean.valueOf(true)); assertEquals(configPeerGossipStateModel.checkInterval(), "10s"); assertEquals(configPeerGossipStateModel.responseTimeout(), "3s"); assertEquals(configPeerGossipStateModel.batchSize(), Double.valueOf("10")); assertEquals(configPeerGossipStateModel.blockBufferSize(), Double.valueOf("100")); assertEquals(configPeerGossipStateModel.maxRetries(), Double.valueOf("3")); ConfigPeerGossip configPeerGossipModel = new ConfigPeerGossip.Builder() .useLeaderElection(true) .orgLeader(false) .membershipTrackerInterval("5s") .maxBlockCountToStore(Double.valueOf("100")) .maxPropagationBurstLatency("10ms") .maxPropagationBurstSize(Double.valueOf("10")) .propagateIterations(Double.valueOf("3")) .pullInterval("4s") .pullPeerNum(Double.valueOf("3")) .requestStateInfoInterval("4s") .publishStateInfoInterval("4s") .stateInfoRetentionInterval("0s") .publishCertPeriod("10s") .skipBlockVerification(false) .dialTimeout("3s") .connTimeout("2s") .recvBuffSize(Double.valueOf("20")) .sendBuffSize(Double.valueOf("200")) .digestWaitTime("1s") .requestWaitTime("1500ms") .responseWaitTime("2s") .aliveTimeInterval("5s") .aliveExpirationTimeout("25s") .reconnectInterval("25s") .election(configPeerGossipElectionModel) .pvtData(configPeerGossipPvtDataModel) .state(configPeerGossipStateModel) .build(); assertEquals(configPeerGossipModel.useLeaderElection(), Boolean.valueOf(true)); assertEquals(configPeerGossipModel.orgLeader(), Boolean.valueOf(false)); assertEquals(configPeerGossipModel.membershipTrackerInterval(), "5s"); assertEquals(configPeerGossipModel.maxBlockCountToStore(), Double.valueOf("100")); assertEquals(configPeerGossipModel.maxPropagationBurstLatency(), "10ms"); assertEquals(configPeerGossipModel.maxPropagationBurstSize(), Double.valueOf("10")); assertEquals(configPeerGossipModel.propagateIterations(), Double.valueOf("3")); assertEquals(configPeerGossipModel.pullInterval(), "4s"); assertEquals(configPeerGossipModel.pullPeerNum(), Double.valueOf("3")); assertEquals(configPeerGossipModel.requestStateInfoInterval(), "4s"); assertEquals(configPeerGossipModel.publishStateInfoInterval(), "4s"); assertEquals(configPeerGossipModel.stateInfoRetentionInterval(), "0s"); assertEquals(configPeerGossipModel.publishCertPeriod(), "10s"); assertEquals(configPeerGossipModel.skipBlockVerification(), Boolean.valueOf(false)); assertEquals(configPeerGossipModel.dialTimeout(), "3s"); assertEquals(configPeerGossipModel.connTimeout(), "2s"); assertEquals(configPeerGossipModel.recvBuffSize(), Double.valueOf("20")); assertEquals(configPeerGossipModel.sendBuffSize(), Double.valueOf("200")); assertEquals(configPeerGossipModel.digestWaitTime(), "1s"); assertEquals(configPeerGossipModel.requestWaitTime(), "1500ms"); assertEquals(configPeerGossipModel.responseWaitTime(), "2s"); assertEquals(configPeerGossipModel.aliveTimeInterval(), "5s"); assertEquals(configPeerGossipModel.aliveExpirationTimeout(), "25s"); assertEquals(configPeerGossipModel.reconnectInterval(), "25s"); assertEquals(configPeerGossipModel.election(), configPeerGossipElectionModel); assertEquals(configPeerGossipModel.pvtData(), configPeerGossipPvtDataModel); assertEquals(configPeerGossipModel.state(), configPeerGossipStateModel); ConfigPeerAuthentication configPeerAuthenticationModel = new ConfigPeerAuthentication.Builder() .timewindow("15m") .build(); assertEquals(configPeerAuthenticationModel.timewindow(), "15m"); ConfigPeerClient configPeerClientModel = new ConfigPeerClient.Builder() .connTimeout("2s") .build(); assertEquals(configPeerClientModel.connTimeout(), "2s"); ConfigPeerDeliveryclientAddressOverridesItem configPeerDeliveryclientAddressOverridesItemModel = new ConfigPeerDeliveryclientAddressOverridesItem.Builder() .from("n3a3ec3-myorderer.ibp.us-south.containers.appdomain.cloud:7050") .to("n3a3ec3-myorderer2.ibp.us-south.containers.appdomain.cloud:7050") .caCertsFile("my-data/cert.pem") .build(); assertEquals(configPeerDeliveryclientAddressOverridesItemModel.from(), "n3a3ec3-myorderer.ibp.us-south.containers.appdomain.cloud:7050"); assertEquals(configPeerDeliveryclientAddressOverridesItemModel.to(), "n3a3ec3-myorderer2.ibp.us-south.containers.appdomain.cloud:7050"); assertEquals(configPeerDeliveryclientAddressOverridesItemModel.caCertsFile(), "my-data/cert.pem"); ConfigPeerDeliveryclient configPeerDeliveryclientModel = new ConfigPeerDeliveryclient.Builder() .reconnectTotalTimeThreshold("60m") .connTimeout("2s") .reConnectBackoffThreshold("60m") .addressOverrides(new java.util.ArrayList<ConfigPeerDeliveryclientAddressOverridesItem>(java.util.Arrays.asList(configPeerDeliveryclientAddressOverridesItemModel))) .build(); assertEquals(configPeerDeliveryclientModel.reconnectTotalTimeThreshold(), "60m"); assertEquals(configPeerDeliveryclientModel.connTimeout(), "2s"); assertEquals(configPeerDeliveryclientModel.reConnectBackoffThreshold(), "60m"); assertEquals(configPeerDeliveryclientModel.addressOverrides(), new java.util.ArrayList<ConfigPeerDeliveryclientAddressOverridesItem>(java.util.Arrays.asList(configPeerDeliveryclientAddressOverridesItemModel))); ConfigPeerAdminService configPeerAdminServiceModel = new ConfigPeerAdminService.Builder() .listenAddress("0.0.0.0:7051") .build(); assertEquals(configPeerAdminServiceModel.listenAddress(), "0.0.0.0:7051"); ConfigPeerDiscovery configPeerDiscoveryModel = new ConfigPeerDiscovery.Builder() .enabled(true) .authCacheEnabled(true) .authCacheMaxSize(Double.valueOf("1000")) .authCachePurgeRetentionRatio(Double.valueOf("0.75")) .orgMembersAllowedAccess(false) .build(); assertEquals(configPeerDiscoveryModel.enabled(), Boolean.valueOf(true)); assertEquals(configPeerDiscoveryModel.authCacheEnabled(), Boolean.valueOf(true)); assertEquals(configPeerDiscoveryModel.authCacheMaxSize(), Double.valueOf("1000")); assertEquals(configPeerDiscoveryModel.authCachePurgeRetentionRatio(), Double.valueOf("0.75")); assertEquals(configPeerDiscoveryModel.orgMembersAllowedAccess(), Boolean.valueOf(false)); ConfigPeerLimitsConcurrency configPeerLimitsConcurrencyModel = new ConfigPeerLimitsConcurrency.Builder() .endorserService(Double.valueOf("2500")) .deliverService(Double.valueOf("2500")) .build(); assertEquals(configPeerLimitsConcurrencyModel.endorserService(), Double.valueOf("2500")); assertEquals(configPeerLimitsConcurrencyModel.deliverService(), Double.valueOf("2500")); ConfigPeerLimits configPeerLimitsModel = new ConfigPeerLimits.Builder() .concurrency(configPeerLimitsConcurrencyModel) .build(); assertEquals(configPeerLimitsModel.concurrency(), configPeerLimitsConcurrencyModel); ConfigPeerUpdatePeer configPeerUpdatePeerModel = new ConfigPeerUpdatePeer.Builder() .id("john-doe") .networkId("dev") .keepalive(configPeerKeepaliveModel) .gossip(configPeerGossipModel) .authentication(configPeerAuthenticationModel) .client(configPeerClientModel) .deliveryclient(configPeerDeliveryclientModel) .adminService(configPeerAdminServiceModel) .validatorPoolSize(Double.valueOf("8")) .discovery(configPeerDiscoveryModel) .limits(configPeerLimitsModel) .build(); assertEquals(configPeerUpdatePeerModel.id(), "john-doe"); assertEquals(configPeerUpdatePeerModel.networkId(), "dev"); assertEquals(configPeerUpdatePeerModel.keepalive(), configPeerKeepaliveModel); assertEquals(configPeerUpdatePeerModel.gossip(), configPeerGossipModel); assertEquals(configPeerUpdatePeerModel.authentication(), configPeerAuthenticationModel); assertEquals(configPeerUpdatePeerModel.client(), configPeerClientModel); assertEquals(configPeerUpdatePeerModel.deliveryclient(), configPeerDeliveryclientModel); assertEquals(configPeerUpdatePeerModel.adminService(), configPeerAdminServiceModel); assertEquals(configPeerUpdatePeerModel.validatorPoolSize(), Double.valueOf("8")); assertEquals(configPeerUpdatePeerModel.discovery(), configPeerDiscoveryModel); assertEquals(configPeerUpdatePeerModel.limits(), configPeerLimitsModel); ConfigPeerChaincodeGolang configPeerChaincodeGolangModel = new ConfigPeerChaincodeGolang.Builder() .dynamicLink(false) .build(); assertEquals(configPeerChaincodeGolangModel.dynamicLink(), Boolean.valueOf(false)); ConfigPeerChaincodeExternalBuildersItem configPeerChaincodeExternalBuildersItemModel = new ConfigPeerChaincodeExternalBuildersItem.Builder() .path("/path/to/directory") .name("descriptive-build-name") .environmentWhitelist(new java.util.ArrayList<String>(java.util.Arrays.asList("GOPROXY"))) .build(); assertEquals(configPeerChaincodeExternalBuildersItemModel.path(), "/path/to/directory"); assertEquals(configPeerChaincodeExternalBuildersItemModel.name(), "descriptive-build-name"); assertEquals(configPeerChaincodeExternalBuildersItemModel.environmentWhitelist(), new java.util.ArrayList<String>(java.util.Arrays.asList("GOPROXY"))); ConfigPeerChaincodeSystem configPeerChaincodeSystemModel = new ConfigPeerChaincodeSystem.Builder() .cscc(true) .lscc(true) .escc(true) .vscc(true) .qscc(true) .build(); assertEquals(configPeerChaincodeSystemModel.cscc(), Boolean.valueOf(true)); assertEquals(configPeerChaincodeSystemModel.lscc(), Boolean.valueOf(true)); assertEquals(configPeerChaincodeSystemModel.escc(), Boolean.valueOf(true)); assertEquals(configPeerChaincodeSystemModel.vscc(), Boolean.valueOf(true)); assertEquals(configPeerChaincodeSystemModel.qscc(), Boolean.valueOf(true)); ConfigPeerChaincodeLogging configPeerChaincodeLoggingModel = new ConfigPeerChaincodeLogging.Builder() .level("info") .shim("warning") .format("%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}") .build(); assertEquals(configPeerChaincodeLoggingModel.level(), "info"); assertEquals(configPeerChaincodeLoggingModel.shim(), "warning"); assertEquals(configPeerChaincodeLoggingModel.format(), "%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}"); ConfigPeerChaincode configPeerChaincodeModel = new ConfigPeerChaincode.Builder() .golang(configPeerChaincodeGolangModel) .externalBuilders(new java.util.ArrayList<ConfigPeerChaincodeExternalBuildersItem>(java.util.Arrays.asList(configPeerChaincodeExternalBuildersItemModel))) .installTimeout("300s") .startuptimeout("300s") .executetimeout("30s") .system(configPeerChaincodeSystemModel) .logging(configPeerChaincodeLoggingModel) .build(); assertEquals(configPeerChaincodeModel.golang(), configPeerChaincodeGolangModel); assertEquals(configPeerChaincodeModel.externalBuilders(), new java.util.ArrayList<ConfigPeerChaincodeExternalBuildersItem>(java.util.Arrays.asList(configPeerChaincodeExternalBuildersItemModel))); assertEquals(configPeerChaincodeModel.installTimeout(), "300s"); assertEquals(configPeerChaincodeModel.startuptimeout(), "300s"); assertEquals(configPeerChaincodeModel.executetimeout(), "30s"); assertEquals(configPeerChaincodeModel.system(), configPeerChaincodeSystemModel); assertEquals(configPeerChaincodeModel.logging(), configPeerChaincodeLoggingModel); MetricsStatsd metricsStatsdModel = new MetricsStatsd.Builder() .network("udp") .address("127.0.0.1:8125") .writeInterval("10s") .prefix("server") .build(); assertEquals(metricsStatsdModel.network(), "udp"); assertEquals(metricsStatsdModel.address(), "127.0.0.1:8125"); assertEquals(metricsStatsdModel.writeInterval(), "10s"); assertEquals(metricsStatsdModel.prefix(), "server"); Metrics metricsModel = new Metrics.Builder() .provider("prometheus") .statsd(metricsStatsdModel) .build(); assertEquals(metricsModel.provider(), "prometheus"); assertEquals(metricsModel.statsd(), metricsStatsdModel); ConfigPeerUpdate configPeerUpdateModel = new ConfigPeerUpdate.Builder() .peer(configPeerUpdatePeerModel) .chaincode(configPeerChaincodeModel) .metrics(metricsModel) .build(); assertEquals(configPeerUpdateModel.peer(), configPeerUpdatePeerModel); assertEquals(configPeerUpdateModel.chaincode(), configPeerChaincodeModel); assertEquals(configPeerUpdateModel.metrics(), metricsModel); CryptoEnrollmentComponent cryptoEnrollmentComponentModel = new CryptoEnrollmentComponent.Builder() .admincerts(new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))) .build(); assertEquals(cryptoEnrollmentComponentModel.admincerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))); UpdateEnrollmentCryptoFieldCa updateEnrollmentCryptoFieldCaModel = new UpdateEnrollmentCryptoFieldCa.Builder() .host("n3a3ec3-myca.ibp.us-south.containers.appdomain.cloud") .port(Double.valueOf("7054")) .name("ca") .tlsCert("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=") .enrollId("admin") .enrollSecret("password") .build(); assertEquals(updateEnrollmentCryptoFieldCaModel.host(), "n3a3ec3-myca.ibp.us-south.containers.appdomain.cloud"); assertEquals(updateEnrollmentCryptoFieldCaModel.port(), Double.valueOf("7054")); assertEquals(updateEnrollmentCryptoFieldCaModel.name(), "ca"); assertEquals(updateEnrollmentCryptoFieldCaModel.tlsCert(), "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="); assertEquals(updateEnrollmentCryptoFieldCaModel.enrollId(), "admin"); assertEquals(updateEnrollmentCryptoFieldCaModel.enrollSecret(), "password"); UpdateEnrollmentCryptoFieldTlsca updateEnrollmentCryptoFieldTlscaModel = new UpdateEnrollmentCryptoFieldTlsca.Builder() .host("n3a3ec3-myca.ibp.us-south.containers.appdomain.cloud") .port(Double.valueOf("7054")) .name("tlsca") .tlsCert("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=") .enrollId("admin") .enrollSecret("password") .csrHosts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))) .build(); assertEquals(updateEnrollmentCryptoFieldTlscaModel.host(), "n3a3ec3-myca.ibp.us-south.containers.appdomain.cloud"); assertEquals(updateEnrollmentCryptoFieldTlscaModel.port(), Double.valueOf("7054")); assertEquals(updateEnrollmentCryptoFieldTlscaModel.name(), "tlsca"); assertEquals(updateEnrollmentCryptoFieldTlscaModel.tlsCert(), "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="); assertEquals(updateEnrollmentCryptoFieldTlscaModel.enrollId(), "admin"); assertEquals(updateEnrollmentCryptoFieldTlscaModel.enrollSecret(), "password"); assertEquals(updateEnrollmentCryptoFieldTlscaModel.csrHosts(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))); UpdateEnrollmentCryptoField updateEnrollmentCryptoFieldModel = new UpdateEnrollmentCryptoField.Builder() .component(cryptoEnrollmentComponentModel) .ca(updateEnrollmentCryptoFieldCaModel) .tlsca(updateEnrollmentCryptoFieldTlscaModel) .build(); assertEquals(updateEnrollmentCryptoFieldModel.component(), cryptoEnrollmentComponentModel); assertEquals(updateEnrollmentCryptoFieldModel.ca(), updateEnrollmentCryptoFieldCaModel); assertEquals(updateEnrollmentCryptoFieldModel.tlsca(), updateEnrollmentCryptoFieldTlscaModel); UpdateMspCryptoFieldCa updateMspCryptoFieldCaModel = new UpdateMspCryptoFieldCa.Builder() .rootCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))) .caIntermediateCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))) .build(); assertEquals(updateMspCryptoFieldCaModel.rootCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))); assertEquals(updateMspCryptoFieldCaModel.caIntermediateCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))); UpdateMspCryptoFieldTlsca updateMspCryptoFieldTlscaModel = new UpdateMspCryptoFieldTlsca.Builder() .rootCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))) .caIntermediateCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))) .build(); assertEquals(updateMspCryptoFieldTlscaModel.rootCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))); assertEquals(updateMspCryptoFieldTlscaModel.caIntermediateCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))); ClientAuth clientAuthModel = new ClientAuth.Builder() .type("noclientcert") .tlsCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))) .build(); assertEquals(clientAuthModel.type(), "noclientcert"); assertEquals(clientAuthModel.tlsCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))); UpdateMspCryptoFieldComponent updateMspCryptoFieldComponentModel = new UpdateMspCryptoFieldComponent.Builder() .ekey("testString") .ecert("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=") .adminCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))) .tlsKey("testString") .tlsCert("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=") .clientAuth(clientAuthModel) .build(); assertEquals(updateMspCryptoFieldComponentModel.ekey(), "testString"); assertEquals(updateMspCryptoFieldComponentModel.ecert(), "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="); assertEquals(updateMspCryptoFieldComponentModel.adminCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))); assertEquals(updateMspCryptoFieldComponentModel.tlsKey(), "testString"); assertEquals(updateMspCryptoFieldComponentModel.tlsCert(), "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="); assertEquals(updateMspCryptoFieldComponentModel.clientAuth(), clientAuthModel); UpdateMspCryptoField updateMspCryptoFieldModel = new UpdateMspCryptoField.Builder() .ca(updateMspCryptoFieldCaModel) .tlsca(updateMspCryptoFieldTlscaModel) .component(updateMspCryptoFieldComponentModel) .build(); assertEquals(updateMspCryptoFieldModel.ca(), updateMspCryptoFieldCaModel); assertEquals(updateMspCryptoFieldModel.tlsca(), updateMspCryptoFieldTlscaModel); assertEquals(updateMspCryptoFieldModel.component(), updateMspCryptoFieldComponentModel); UpdatePeerBodyCrypto updatePeerBodyCryptoModel = new UpdatePeerBodyCrypto.Builder() .enrollment(updateEnrollmentCryptoFieldModel) .msp(updateMspCryptoFieldModel) .build(); assertEquals(updatePeerBodyCryptoModel.enrollment(), updateEnrollmentCryptoFieldModel); assertEquals(updatePeerBodyCryptoModel.msp(), updateMspCryptoFieldModel); NodeOu nodeOuModel = new NodeOu.Builder() .enabled(true) .build(); assertEquals(nodeOuModel.enabled(), Boolean.valueOf(true)); ResourceRequests resourceRequestsModel = new ResourceRequests.Builder() .cpu("100m") .memory("256MiB") .build(); assertEquals(resourceRequestsModel.cpu(), "100m"); assertEquals(resourceRequestsModel.memory(), "256MiB"); ResourceLimits resourceLimitsModel = new ResourceLimits.Builder() .cpu("100m") .memory("256MiB") .build(); assertEquals(resourceLimitsModel.cpu(), "100m"); assertEquals(resourceLimitsModel.memory(), "256MiB"); ResourceObjectFabV2 resourceObjectFabV2Model = new ResourceObjectFabV2.Builder() .requests(resourceRequestsModel) .limits(resourceLimitsModel) .build(); assertEquals(resourceObjectFabV2Model.requests(), resourceRequestsModel); assertEquals(resourceObjectFabV2Model.limits(), resourceLimitsModel); ResourceObjectCouchDb resourceObjectCouchDbModel = new ResourceObjectCouchDb.Builder() .requests(resourceRequestsModel) .limits(resourceLimitsModel) .build(); assertEquals(resourceObjectCouchDbModel.requests(), resourceRequestsModel); assertEquals(resourceObjectCouchDbModel.limits(), resourceLimitsModel); ResourceObject resourceObjectModel = new ResourceObject.Builder() .requests(resourceRequestsModel) .limits(resourceLimitsModel) .build(); assertEquals(resourceObjectModel.requests(), resourceRequestsModel); assertEquals(resourceObjectModel.limits(), resourceLimitsModel); ResourceObjectFabV1 resourceObjectFabV1Model = new ResourceObjectFabV1.Builder() .requests(resourceRequestsModel) .limits(resourceLimitsModel) .build(); assertEquals(resourceObjectFabV1Model.requests(), resourceRequestsModel); assertEquals(resourceObjectFabV1Model.limits(), resourceLimitsModel); PeerResources peerResourcesModel = new PeerResources.Builder() .chaincodelauncher(resourceObjectFabV2Model) .couchdb(resourceObjectCouchDbModel) .statedb(resourceObjectModel) .dind(resourceObjectFabV1Model) .fluentd(resourceObjectFabV1Model) .peer(resourceObjectModel) .proxy(resourceObjectModel) .build(); assertEquals(peerResourcesModel.chaincodelauncher(), resourceObjectFabV2Model); assertEquals(peerResourcesModel.couchdb(), resourceObjectCouchDbModel); assertEquals(peerResourcesModel.statedb(), resourceObjectModel); assertEquals(peerResourcesModel.dind(), resourceObjectFabV1Model); assertEquals(peerResourcesModel.fluentd(), resourceObjectFabV1Model); assertEquals(peerResourcesModel.peer(), resourceObjectModel); assertEquals(peerResourcesModel.proxy(), resourceObjectModel); UpdatePeerOptions updatePeerOptionsModel = new UpdatePeerOptions.Builder() .id("testString") .adminCerts(new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))) .configOverride(configPeerUpdateModel) .crypto(updatePeerBodyCryptoModel) .nodeOu(nodeOuModel) .replicas(Double.valueOf("1")) .resources(peerResourcesModel) .version("1.4.6-1") .zone("-") .build(); assertEquals(updatePeerOptionsModel.id(), "testString"); assertEquals(updatePeerOptionsModel.adminCerts(), new java.util.ArrayList<String>(java.util.Arrays.asList("LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCkNlcnQgZGF0YSB3b3VsZCBiZSBoZXJlIGlmIHRoaXMgd2FzIHJlYWwKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="))); assertEquals(updatePeerOptionsModel.configOverride(), configPeerUpdateModel); assertEquals(updatePeerOptionsModel.crypto(), updatePeerBodyCryptoModel); assertEquals(updatePeerOptionsModel.nodeOu(), nodeOuModel); assertEquals(updatePeerOptionsModel.replicas(), Double.valueOf("1")); assertEquals(updatePeerOptionsModel.resources(), peerResourcesModel); assertEquals(updatePeerOptionsModel.version(), "1.4.6-1"); assertEquals(updatePeerOptionsModel.zone(), "-"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testUpdatePeerOptionsError() throws Throwable { new UpdatePeerOptions.Builder().build(); } }
59.208113
256
0.792619
375928190a4d56ae9d1cb2aa937be5b6b3c19f22
2,029
package org.drools.eclipse.editors.rete.model; import org.drools.reteoo.BaseVertex; /** * A connection between two distinct vertices. */ public class Connection extends ModelElement { private boolean isConnected; private BaseVertex source; private BaseVertex target; /** * Creating a connection between two distinct vertices. * * @param source a source endpoint * @param target a target endpoint * @throws IllegalArgumentException if any of the parameters are null or source == target */ public Connection(BaseVertex source, BaseVertex target) { this.source = source; this.target = target; source.addConnection( this ); target.addConnection( this ); isConnected = true; } /** * Disconnect this connection from the vertices it is attached to. */ public void disconnect() { if ( isConnected ) { source.removeConnection( this ); target.removeConnection( this ); isConnected = false; } } /** * Returns the source endpoint of this connection. * * @return BaseVertex vertex */ public BaseVertex getSource() { return source; } /** * Returns the target endpoint of this connection. * * @return BaseVertex vertex */ public BaseVertex getTarget() { return target; } /** * Gets opposite of specified vertex. * * Returning <code>null</code> if specified not does not belong into this connection. * * @param vertex * @return opposite of vertex */ public BaseVertex getOpposite(BaseVertex vertex) { // If null or not part of this connection if ( vertex == null || (!vertex.equals( getSource() ) && !vertex.equals( getTarget() )) ) { return null; } if ( vertex.equals( getSource() ) ) { return getTarget(); } return getSource(); } }
25.3625
99
0.590439
5c0c35eaced144f72d2e47ae99e05770b5e6d88d
2,261
package me.stuarthicks.xquery.stubbing; import java.util.Arrays; import java.util.List; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.lib.ExtensionFunctionCall; import net.sf.saxon.om.Sequence; import net.sf.saxon.trans.XPathException; import net.sf.saxon.value.FloatValue; import net.sf.saxon.value.Int64Value; import net.sf.saxon.value.StringValue; import com.google.common.collect.Lists; public class XQueryFunctionCall extends ExtensionFunctionCall { private static final long serialVersionUID = -657472652323160853L; private XQueryFunctionStubBuilder XQueryFunctionStubBuilder; private List<Object> arguments = Lists.newArrayList(); public int numberOfInvocations = 0; public XQueryFunctionCall (XQueryFunctionStubBuilder XQueryFunctionStubBuilder) { this.XQueryFunctionStubBuilder = XQueryFunctionStubBuilder; } public List<Object> getArguments () { return this.arguments; } public int getNumberOfInvocations () { return this.numberOfInvocations; } @Override public Sequence call (XPathContext xPathContext, Sequence[] sequences) throws XPathException { this.arguments = sanitise(Arrays.asList(sequences)); this.numberOfInvocations++; return getNextResult(); } private Sequence getNextResult () { List<Sequence> values = this.XQueryFunctionStubBuilder.getResultValues(); Sequence nextValue = null; if (values.size() > 1) { nextValue = values.get(0); values.remove(0); return nextValue; } return values.get(0); } private static List<Object> sanitise (List<Sequence> sequences) { List<Object> items = Lists.newArrayList(); for (Sequence s : sequences) { if (s instanceof StringValue) { items.add(((StringValue) s).asString()); } else if (s instanceof Int64Value) { items.add(((Int64Value) s).asBigInteger().intValue()); } else if (s instanceof FloatValue) { items.add(((FloatValue) s).getFloatValue()); } else { items.add(s); } } return items; } }
30.972603
98
0.651924
ed16553ef984d134219a8b5b3529d7ad57cd7351
438
package hw04.model; import hw04.model.IViewUpdateAdapter; /** * Interface that goes from the model to the view that enables the model conduct update tasks to view */ public interface IViewUpdateAdapter { /** * The method that tells the view to update */ public void update(); /** * No-op "null" adapter */ public static final IViewUpdateAdapter NULL_OBJECT = new IViewUpdateAdapter() { public void update() { } }; }
19.909091
101
0.707763
d3e6fae58a668384e629f4e9281671009883a23b
971
package layer.conv.block; import layer.conv.InputLayer; public class InputBlock extends Block{ public InputBlock(int numFilters, int width, int height, Block prevBlock) { super(numFilters, width, height, prevBlock); // TODO Auto-generated constructor stub System.out.println("Creating IPL " + numBlocks + ": " + "(" + this.getWidth() + ", " + this.getHeight() + ", " + this.getDepth() + ")"); this.block = new InputLayer[this.getDepth()]; numBlocks++; initialize(); } private void initialize() { // TODO Auto-generated method stub for(int i = 0; i < this.getDepth(); i++) { this.block[i] = new InputLayer(this.getWidth(), this.getHeight()); this.addAllNeurons(((InputLayer)this.block[i]).getAllNeurons()); System.out.println("Neuron Count: " + this.getAllNeurons().size()); } } public String toString() { return "IPL: " + "(" + this.getWidth() + ", " + this.getHeight() + ", " + this.getDepth() + ")"; } }
25.552632
138
0.632338
e122dd7258d5213a83a3008e67bd4ce6ec5f39df
393
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.exoplayer2.metadata; // Referenced classes of package com.google.android.exoplayer2.metadata: // Metadata public interface MetadataOutput { public abstract void onMetadata(Metadata metadata); }
24.5625
72
0.773537
a9786ece72a34d1c06d86c8c73b82906c5c9dd07
2,878
package gameClient; import api.*; import gameClient.util.Point3D; import org.json.JSONObject; /** * This class representing an agent, containing helpful information that we "take" from the game server about the agent such as: * agent ID * agent speed * update the agent with new information as speed * and so on */ public class CL_Agent { private int _id; private int pokSrc; private geo_location _pos; private double _speed; private edge_data _curr_edge; private node_data _curr_node; private directed_weighted_graph _gg; private double _value; public CL_Agent(directed_weighted_graph g, int start_node) { _gg = g; setMoney(0); this._curr_node = _gg.getNode(start_node); _pos = _curr_node.getLocation(); _id = -1; setSpeed(0); } public void update(String json) { JSONObject line; try { line = new JSONObject(json); JSONObject ttt = line.getJSONObject("Agent"); int id = ttt.getInt("id"); if (id == this.getID() || this.getID() == -1) { if (this.getID() == -1) { _id = id; } double speed = ttt.getDouble("speed"); String p = ttt.getString("pos"); Point3D pp = new Point3D(p); int src = ttt.getInt("src"); int dest = ttt.getInt("dest"); double value = ttt.getDouble("value"); this._pos = pp; this.setCurrNode(src); this.setSpeed(speed); this.setNextNode(dest); this.setMoney(value); } } catch (Exception e) { e.printStackTrace(); } } //@Override public int getSrcNode() { return this._curr_node.getKey(); } public String toJSON() { int d = this.getNextNode(); String ans = "{\"Agent\":{" + "\"id\":" + this._id + "," + "\"value\":" + this._value + "," + "\"src\":" + this._curr_node.getKey() + "," + "\"dest\":" + d + "," + "\"speed\":" + this.getSpeed() + "," + "\"pos\":\"" + _pos.toString() + "\"" + "}" + "}"; return ans; } private void setMoney(double v) { _value = v; } public boolean setNextNode(int dest) { boolean ans = false; int src = this._curr_node.getKey(); this._curr_edge = _gg.getEdge(src, dest); if (_curr_edge != null) { ans = true; } else { _curr_edge = null; } return ans; } public void setCurrNode(int src) { this._curr_node = _gg.getNode(src); } public String toString() { return toJSON(); } public int getID() { return this._id; } public geo_location getLocation() { return _pos; } public int getNextNode() { int ans = -2; if (this._curr_edge == null) { ans = -1; } else { ans = this._curr_edge.getDest(); } return ans; } public double getSpeed() { return this._speed; } public void setSpeed(double v) { this._speed = v; } public void setPokSrc(int src) { this.pokSrc = src; } public int getPokSrc() { return this.pokSrc; } public String get_value() { return String.valueOf(this._value); } }
19.445946
128
0.622307
b4e51cef86468455a83ab994c6d7efa4bb0c00b7
4,525
package org.ofdrw.core.compositeObj; import org.dom4j.Element; import org.ofdrw.core.OFDElement; import org.ofdrw.core.basicStructure.pageObj.layer.PageBlockType; import org.ofdrw.core.basicStructure.pageObj.layer.block.CT_PageBlock; import org.ofdrw.core.basicType.ST_ID; import org.ofdrw.core.basicType.ST_RefID; import java.util.List; /** * 矢量图像 * <p> * 复合对象引用的资源时 Res 中的矢量图像(CompositeGraphUnit) * <p> * 13 图 72 表 50 * * @author 权观宇 * @since 2019-10-27 04:56:42 */ public class CT_VectorG extends OFDElement { public CT_VectorG(Element proxy) { super(proxy); } public CT_VectorG() { super("VectorG"); } protected CT_VectorG(String name) { super(name); } public ST_ID getID() { return this.getObjID(); } public CT_VectorG setID(ST_ID id) { this.setObjID(id); return this; } /** * 【必选 属性】 * 设置 矢量图像的宽度 * <p> * 超出部分做裁剪处理 * * @param width 矢量图像的宽度 * @return this */ public CT_VectorG setWidth(Double width) { if (width == null) { throw new IllegalArgumentException("矢量图像的宽度(Width)不能为空"); } this.addAttribute("Width", width.toString()); return this; } /** * 【必选 属性】 * 获取 矢量图像的宽度 * <p> * 超出部分做裁剪处理 * * @return 矢量图像的宽度 */ public Double getWidth() { String str = this.attributeValue("Width"); if (str == null || str.trim().length() == 0) { throw new IllegalArgumentException("格式非法无法获取到矢量图像的宽度(Width)"); } return Double.parseDouble(str); } /** * 【必选 属性】 * 设置 矢量图像的高度 * <p> * 超出部分做裁剪处理 * * @param height 矢量图像的高度 * @return this */ public CT_VectorG setHeight(Double height) { if (height == null) { throw new IllegalArgumentException("矢量图像的高度(Height)不能为空"); } this.addAttribute("Height", height.toString()); return this; } /** * 【必选 属性】 * 获取 矢量图像的高度 * <p> * 超出部分做裁剪处理 * * @return 矢量图像的高度 */ public Double getHeight() { String str = this.attributeValue("Height"); if (str == null || str.trim().length() == 0) { throw new IllegalArgumentException("格式非法无法获取到矢量图像的宽度(Height)"); } return Double.parseDouble(str); } /** * 【可选】 * 设置 缩略图 * <p> * 指向包内的图像文件 * * @param thumbnail 缩略图路径 * @return this */ public CT_VectorG setThumbnail(ST_RefID thumbnail) { this.setOFDEntity("Thumbnail", thumbnail.toString()); return this; } /** * 【可选】 * 获取 缩略图 * <p> * 指向包内的图像文件 * * @return 缩略图路径 */ public ST_RefID getThumbnail() { return ST_RefID.getInstance(this.getOFDElementText("Thumbnail")); } /** * 【可选】 * 设置 替换图像 * <p> * 用于高分辨率输出时将缩略图替换为此高分辨率的图像 * 指向包内的图像文件 * * @param substitution 替换图像 * @return this */ public CT_VectorG setSubstitution(ST_RefID substitution) { this.setOFDEntity("Substitution", substitution.toString()); return this; } /** * 【可选】 * 获取 替换图像 * <p> * 用于高分辨率输出时将缩略图替换为此高分辨率的图像 * 指向包内的图像文件 * * @return 替换图像 */ public ST_RefID getSubstitution() { return ST_RefID.getInstance(this.getOFDElementText("Substitution")); } /** * 【必选】 * 设置 内容的矢量描述 * * @param content 内容的矢量描述 * @return this */ public CT_VectorG setContent(Content content) { if (content == null) { throw new IllegalArgumentException("内容的矢量描述(Content)不能为空"); } this.set(content); return this; } /** * 【必选】 * 增加 内容的矢量描述 * * @param blockType 内容的矢量描述 * @return this */ public CT_VectorG addContent(PageBlockType blockType) { if (blockType == null) { return this; } Element e = this.getOFDElement("Content"); Content content = (e == null) ? new Content() : new Content(e); content.addPageBlock(blockType); this.set(content); return this; } /** * 【必选】 * 获取 内容的矢量描述 * * @return 内容的矢量描述 */ public Content getContent() { Element e = this.getOFDElement("Content"); if (e == null) { throw new IllegalArgumentException("没有找到Content元素"); } return new Content(e); } }
21.244131
76
0.548729
ef46c81996b64c7c915eb35b8849702f1d523979
4,801
package com.prestonlee; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayes; import weka.core.Attribute; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.StringToWordVector; /** * Based on the template provided with the lab assignment. * * @author Preston Lee <[email protected]> */ public class PartB { // TODO Increase this whenever you add a new attribute protected static int NUM_ATTRIBUTES = 2; private static final String ATTRIBUTE_UNIGRAM = "unigram"; // Number of folds for cross validation static int NUM_FOLDS = 5; protected NaiveBayes nbModel = new NaiveBayes(); protected Instances adrInstances; protected FastVector attributes; protected StringToWordVector string2VectorFilter = new StringToWordVector(); public static void main(final String[] args) throws Exception { if (args.length != 3) { System.err.println("The input files are missing: binaryannotations.tsv and texts.tsv"); } final String annotationFilePath = args[0]; final String textFilePath = args[1]; final String stopWordsPath = args[2]; final PartB classifier = new PartB(); classifier.initialize(); classifier.createInstances(annotationFilePath, textFilePath, stopWordsPath); classifier.crossValidate(); } public void initialize() throws Exception { attributes = new FastVector(NUM_ATTRIBUTES); // unigram feature attributes.addElement(new Attribute(ATTRIBUTE_UNIGRAM, (FastVector) null)); // TODO add new features here // Class labels FastVector classValues = new FastVector(2); classValues.addElement("noADR"); classValues.addElement("hasADR"); attributes.addElement(new Attribute("HasADR", classValues)); adrInstances = new Instances("instances", attributes, 0); // i.e. The last column holds the label adrInstances.setClassIndex(adrInstances.numAttributes() - 1); string2VectorFilter.setLowerCaseTokens(true); } public Instance addInstance(String klass, String text) throws Exception { Instance instance = new Instance(NUM_ATTRIBUTES); instance.setDataset(adrInstances); // Unigram as an example : Attribute unigramsAttribute = adrInstances.attribute(ATTRIBUTE_UNIGRAM); int unigramFeatureValue = unigramsAttribute.addStringValue(text); instance.setValue(unigramsAttribute, unigramFeatureValue); // TODO add call to your attribute calculators instance.setClassValue(klass); adrInstances.add(instance); return instance; } public void createInstances(final String trainAnnotationFile, final String trainTextFile, final String stopWordsPath) throws Exception { final List<String> stopWords = readFileLineByLine(new File(stopWordsPath)); final List<String> textLines = readFileLineByLine(new File(trainTextFile)); final HashMap<String, String> idToTextMap = new HashMap<String, String>(); String id; String s; for (String textLine : textLines) { String[] textParts = textLine.split("\t"); id = textParts[0]; s = textParts[1]; System.out.println("PRE\t" + s); for (String q : stopWords) { s = s.replace(' ' + q + ' ', " "); } System.out.println("POST\t" + s); idToTextMap.put(id, s); } final List<String> annotationLines = readFileLineByLine(new File(trainAnnotationFile)); for (String annotationLine : annotationLines) { String[] annotationParts = annotationLine.split("\t"); String relatedText = idToTextMap.get(annotationParts[0]); addInstance(annotationParts[1], relatedText); } } public void crossValidate() throws Exception { string2VectorFilter.setInputFormat(adrInstances); Instances filteredData = Filter.useFilter(adrInstances, string2VectorFilter); nbModel.buildClassifier(filteredData); Evaluation eval = new Evaluation(filteredData); eval.crossValidateModel(nbModel, filteredData, NUM_FOLDS, new Random(1)); System.out.println(eval.toSummaryString()); System.out.println(eval.toMatrixString()); System.out.println(eval.toClassDetailsString()); } /** * Code for reading a file line by line. you probably don't want to modify * anything here, **/ private static List<String> readFileLineByLine(File f) { try { List<String> contents = new ArrayList<String>(); BufferedReader input = new BufferedReader(new FileReader(f)); for (String line = input.readLine(); line != null; line = input.readLine()) { contents.add(line); } input.close(); return contents; } catch (IOException e) { e.printStackTrace(); System.exit(1); return null; } } }
30.775641
137
0.746511
0f0714ec489aa9b0107e6f6adff3aa1d9cba87b5
8,556
/** * This class runs a Kennel * * @author Lynda Thomas and Chris Loftus * @version 1.2 (23rd February 2018) */ import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class KennelDemo { private String filename; // holds the name of the file private Kennel kennel; // holds the kennel private Scanner scan; // so we can read from keyboard private KennelDemo() { scan = new Scanner(System.in); System.out.print("Please enter the filename of kennel information: "); filename = scan.nextLine(); kennel = new Kennel(); } /*-------------------------------------------------- MAIN MENU --------------------------------------------------*/ private void runMenu() { String response; do { printMenu(); System.out.println("What would you like to do:"); scan = new Scanner(System.in); response = scan.nextLine().toUpperCase(); switch (response) { case "1": admitAnimal(); break; case "2": removeAnimal(); break; case "3": changeKennelName(); break; case "4": searchForAnimal(); break; case "5": setKennelCapacity(); break; case "6": printAll(); break; case "Q": break; default: System.out.println("Try again"); } } while (!(response.equals("Q"))); } private void printMenu() { System.out.println("1 - add a new animal"); System.out.println("2 - remove an animal"); System.out.println("3 - changing the Kennel name"); System.out.println("4 - search for a animal"); System.out.println("5 - set kennel capacity"); System.out.println("6 - display all inmates"); System.out.println("q - Quit"); } private void admitAnimal() { boolean lb = false; boolean wo = false; System.out.println("Do you want to admit dog or cat"); String animalType = scan.nextLine().toLowerCase(); if (animalType.equals("dog") || animalType.equals("cat")) { System.out.println("What is the name of the animal? "); String name = scan.nextLine().toLowerCase(); System.out.println("How many runs a day do he/she needs? (as a number)"); int runs = scan.nextInt(); scan.nextLine(); if (animalType == "dog") { System.out.println("Does he/she like bones? (Y/N)"); String likeBones = scan.nextLine().toUpperCase(); if (likeBones.equals("Y")) { lb = true; } } else if (animalType == "cat"){ System.out.println("Does he/she goes along with other? (Y/N)"); String withOthers = scan.nextLine(); if (withOthers.equals("Y")) { wo = true; } } System.out.println("What is his/her favourite food?"); String fav; fav = scan.nextLine().toLowerCase(); System.out.println("How many times is he/she fed a day? (as a number)"); int numTimes; numTimes = scan.nextInt(); // This can be improved (InputMismatchException?) scan.nextLine(); // Clear the end of line characters because I didn't use a delimiter switch (animalType) { case "dog": Dog newDog = new Dog(name, runs, lb, fav, numTimes); ArrayList<Owner> ownersDog = getOwners(); for (Owner o : ownersDog) { newDog.addOriginalOwner(o); } kennel.addDog(newDog); break; case "cat": Cat newCat = new Cat(name, wo, fav, numTimes); ArrayList<Owner> ownersCat = getOwners(); for (Owner o : ownersCat) { newCat.addOriginalOwner(o); } kennel.addCat(newCat); break; default: System.err.println("Invalid entry"); } } else System.err.println("Can't add that animal"); }//Option 1 private void removeAnimal() { System.out.println("what animal do you want to remove? cat or dog"); String animal = scan.nextLine().toLowerCase(); System.out.println("what is the name of the animal?"); String animalToBeRemoved = scan.nextLine(); kennel.removeAnimal(animal, animalToBeRemoved); }//Option 2 private void changeKennelName() { System.out.println("What is the new name of the kennel? "); String name = scan.nextLine(); kennel.setName(name); }//Option 3 private void searchForAnimal() { System.out.println("what is the name of the animal?"); String aniamlName = scan.nextLine().toLowerCase(); System.out.println(kennel.searchForAnimal(aniamlName)); }//Option 4 private void setKennelCapacity() { System.out.print("Enter max number of animals: "); int max = scan.nextInt(); scan.nextLine(); kennel.setCapacity(max); }//Option 5 /** * printAll() method runs from the main and prints status */ private void printAll() { ArrayList<Object> sortedList = kennel.sortAnimals(); for (Object o : sortedList){ System.out.println(o.toString()); } }//Option 6 /*---------------------------------------------------------------------------------------------------------------*/ private ArrayList<Owner> getOwners() { ArrayList<Owner> owners = new ArrayList<>(); String answer; do { System.out .println("Enter on separate lines: owner-name owner-phone"); String ownName = scan.nextLine(); String ownPhone = scan.nextLine(); Owner own = new Owner(ownName, ownPhone); owners.add(own); System.out.println("Another owner (Y/N)?"); answer = scan.nextLine().toUpperCase(); } while (!answer.equals("N")); return owners; } /*------------------------------------------------ SAVE AND LOAD ------------------------------------------------*/ /** * save() method runs from the main and writes back to file */ private void save() { try { kennel.save(filename); } catch (IOException e) { System.err.println("Problem when trying to write to file: " + filename); } } private void initialise() { System.out.println("Using file " + filename); try { kennel.load(filename); } catch (FileNotFoundException e) { System.err.println("The file: " + filename + " does not exist. Assuming first use and an empty file." + " If this is not the first use then have you accidentally deleted the file?"); } catch (IOException e) { System.err.println("An unexpected error occurred when trying to open the file " + filename); System.err.println(e.getMessage()); } } /*---------------------------------------------------------------------------------------------------------------*/ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String args[]) { System.out.println("************HELLO*************"); KennelDemo demo = new KennelDemo(); demo.initialise(); demo.runMenu(); System.out.println("********Saving to file********"); // MAKE A BACKUP COPY OF dogsrus.txt JUST IN CASE YOU CORRUPT IT demo.save(); System.out.println(" **********GOODBYE***********"); } }
38.890909
120
0.472534
372b04ec4672c1d346a77b6f56bec4d17a585fa7
2,903
package ecfv5.gov.niem.release.niem.codes.fbi_ncic._4; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the ecfv5.gov.niem.release.niem.codes.fbi_ncic._4 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ecfv5.gov.niem.release.niem.codes.fbi_ncic._4 * */ public ObjectFactory() { } /** * Create an instance of {@link VCOCodeType } * */ public VCOCodeType createVCOCodeType() { return new VCOCodeType(); } /** * Create an instance of {@link CountryCodeType } * */ public CountryCodeType createCountryCodeType() { return new CountryCodeType(); } /** * Create an instance of {@link EYECodeType } * */ public EYECodeType createEYECodeType() { return new EYECodeType(); } /** * Create an instance of {@link HAIRCodeType } * */ public HAIRCodeType createHAIRCodeType() { return new HAIRCodeType(); } /** * Create an instance of {@link RACECodeType } * */ public RACECodeType createRACECodeType() { return new RACECodeType(); } /** * Create an instance of {@link SEXCodeType } * */ public SEXCodeType createSEXCodeType() { return new SEXCodeType(); } /** * Create an instance of {@link SMTCodeType } * */ public SMTCodeType createSMTCodeType() { return new SMTCodeType(); } /** * Create an instance of {@link PCOCodeType } * */ public PCOCodeType createPCOCodeType() { return new PCOCodeType(); } /** * Create an instance of {@link VMACodeType } * */ public VMACodeType createVMACodeType() { return new VMACodeType(); } /** * Create an instance of {@link VMOCodeType } * */ public VMOCodeType createVMOCodeType() { return new VMOCodeType(); } /** * Create an instance of {@link VSTCodeType } * */ public VSTCodeType createVSTCodeType() { return new VSTCodeType(); } /** * Create an instance of {@link EXLCodeType } * */ public EXLCodeType createEXLCodeType() { return new EXLCodeType(); } }
22.503876
159
0.61247
da0c113b1bd73244ea95705a50d0043ae3caa736
3,674
package com.example.providertest; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; /** * Created by DysaniazzZ on 2016/01/24. * 第七章:测试内容提供者共享的数据 */ public class ProviderTestActivity extends AppCompatActivity implements View.OnClickListener { private String mNewId; private TextView mTvProviderInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_provider_test); initView(); } private void initView() { mTvProviderInfo = (TextView) findViewById(R.id.tv_provider_info); findViewById(R.id.btn_provider_insert_data).setOnClickListener(this); findViewById(R.id.btn_provider_update_data).setOnClickListener(this); findViewById(R.id.btn_provider_delete_data).setOnClickListener(this); findViewById(R.id.btn_provider_query_data).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_provider_insert_data: //添加数据 Uri insertUri = Uri.parse("content://com.example.dysaniazzz.provider/book"); ContentValues insertValues = new ContentValues(); insertValues.put("name", "A Clash Of Kings"); insertValues.put("author", "George Martin"); insertValues.put("pages", 1040); insertValues.put("price", 22.85); Uri newInsertUri = getContentResolver().insert(insertUri, insertValues); mNewId = newInsertUri.getPathSegments().get(1); break; case R.id.btn_provider_update_data: //更新数据 Uri updateUri = Uri.parse("content://com.example.dysaniazzz.provider/book/" + mNewId); ContentValues updateValues = new ContentValues(); updateValues.put("name", "A Storm Of Swards"); updateValues.put("pages", 1216); updateValues.put("price", 24.95); getContentResolver().update(updateUri, updateValues, null, null); break; case R.id.btn_provider_delete_data: //删除数据 Uri deleteUri = Uri.parse("content://com.example.dysaniazzz.provider/book/" + mNewId); getContentResolver().delete(deleteUri, null, null); break; case R.id.btn_provider_query_data: //查询数据 Uri queryUri = Uri.parse("content://com.example.dysaniazzz.provider/book"); Cursor cursor = getContentResolver().query(queryUri, null, null, null, null); StringBuilder sb = new StringBuilder(); if (cursor != null) { while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); String author = cursor.getString(cursor.getColumnIndex("author")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); double price = cursor.getDouble(cursor.getColumnIndex("price")); sb.append("book name is " + name + "\nbook author is " + author + "\nbook pages is " + pages + "\nbook price is " + price + "\n\n"); } mTvProviderInfo.setText(sb.toString()); cursor.close(); } break; } } }
44.26506
156
0.599619
8d77de15fda0b1dea9fdf7038bdcce95590ca4c7
7,461
package com.example.latte_core.fragments; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.Button; import com.example.latte_core.activities.ProxyActivity; import com.example.latte_core.fragments.bottom.BaseBottomFragment; import butterknife.ButterKnife; import butterknife.Unbinder; import me.yokeyword.fragmentation.ExtraTransaction; import me.yokeyword.fragmentation.ISupportFragment; import me.yokeyword.fragmentation.SupportFragmentDelegate; import me.yokeyword.fragmentation.SupportHelper; import me.yokeyword.fragmentation.anim.FragmentAnimator; /** * Created by 杨淋 on 2018/4/30. * Describe: */ public abstract class BaseFragment extends Fragment implements ISupportFragment { private final SupportFragmentDelegate DELEGATE = new SupportFragmentDelegate(this); protected FragmentActivity _mActivity = null; private static final String TAG = "BaseFragment"; @SuppressWarnings("SpellCheckingInspection") private Unbinder mUnbinder = null; @Override public void onAttach(Context context) { super.onAttach(context); DELEGATE.onAttach((Activity) context); _mActivity = DELEGATE.getActivity(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); DELEGATE.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = null; if (setLayout() instanceof Integer){ rootView = inflater.inflate((Integer) setLayout(),container,false); }else if (setLayout() instanceof View){ rootView = (View) setLayout(); }else { throw new ClassCastException("setLayout 转换异常"); } if (rootView != null){ mUnbinder = ButterKnife.bind(this,rootView); onBindView(savedInstanceState,rootView); } return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); DELEGATE.onActivityCreated(savedInstanceState); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); DELEGATE.onResume(); } @Override public void onPause() { super.onPause(); DELEGATE.onPause(); } @Override public void onDestroyView() { DELEGATE.onDestroyView(); super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); if (mUnbinder != null){ mUnbinder.unbind(); } DELEGATE.onDestroy(); } public abstract Object setLayout(); protected abstract void onBindView(Bundle savedInstanceState, View rootView); public final ProxyActivity getProxyActivity(){ return (ProxyActivity) _mActivity; } @Override public SupportFragmentDelegate getSupportDelegate() { return DELEGATE; } @Override public ExtraTransaction extraTransaction() { return DELEGATE.extraTransaction(); } @Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { return DELEGATE.onCreateAnimation(transit, enter, nextAnim); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); DELEGATE.onSaveInstanceState(outState); } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); DELEGATE.onHiddenChanged(hidden); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); DELEGATE.setUserVisibleHint(isVisibleToUser); } @Override public void enqueueAction(Runnable runnable) { DELEGATE.enqueueAction(runnable); } @Override public void post(Runnable runnable) { DELEGATE.post(runnable); } @Override public void onEnterAnimationEnd(Bundle savedInstanceState) { DELEGATE.onEnterAnimationEnd(savedInstanceState); } @Override public void onLazyInitView(@Nullable Bundle savedInstanceState) { DELEGATE.onLazyInitView(savedInstanceState); } @Override public void onSupportVisible() { DELEGATE.onSupportVisible(); } @Override public void onSupportInvisible() { DELEGATE.onSupportInvisible(); } @Override final public boolean isSupportVisible() { return DELEGATE.isSupportVisible(); } @Override public FragmentAnimator onCreateFragmentAnimator() { return DELEGATE.onCreateFragmentAnimator(); } @Override public FragmentAnimator getFragmentAnimator() { return DELEGATE.getFragmentAnimator(); } @Override public void setFragmentAnimator(FragmentAnimator fragmentAnimator) { DELEGATE.setFragmentAnimator(fragmentAnimator); } @Override public boolean onBackPressedSupport() { Log.e("测试", "onBackPressedSupport: 1111" ); return DELEGATE.onBackPressedSupport(); } @Override public void setFragmentResult(int resultCode, Bundle bundle) { DELEGATE.setFragmentResult(resultCode, bundle); } @Override public void onFragmentResult(int requestCode, int resultCode, Bundle data) { DELEGATE.onFragmentResult(requestCode, resultCode, data); } public void start(ISupportFragment toFragment) { DELEGATE.start(toFragment); } @Override public void onNewBundle(Bundle args) { DELEGATE.onNewBundle(args); } @Override public void putNewBundle(Bundle newBundle) { DELEGATE.putNewBundle(newBundle); } public void start(final ISupportFragment toFragment, @LaunchMode int launchMode) { DELEGATE.start(toFragment, launchMode); } /** * 得到位于栈顶Fragment */ public ISupportFragment getTopFragment() { return SupportHelper.getTopFragment(getFragmentManager()); } public ISupportFragment getTopChildFragment() { return SupportHelper.getTopFragment(getChildFragmentManager()); } /** * @return 位于当前Fragment的前一个Fragment */ public ISupportFragment getPreFragment() { return SupportHelper.getPreFragment(this); } /** * 获取栈内的fragment对象 */ public <T extends ISupportFragment> T findFragment(Class<T> fragmentClass) { return SupportHelper.findFragment(getFragmentManager(), fragmentClass); } /** * 获取栈内的fragment对象 */ public <T extends ISupportFragment> T findChildFragment(Class<T> fragmentClass) { return SupportHelper.findFragment(getChildFragmentManager(), fragmentClass); } }
25.90625
122
0.692132
d5d9f70750587ea20b61a8028e8e7d38a538d755
430
package se.natusoft.osgi.aps.util; /** * Utility to make a value thread synchronized. * * @param <T> Value type. */ public class SyncedValue<T> { private T value; public SyncedValue() {} public SyncedValue(T value) { this.value = value; } public synchronized void setValue(T value) { this.value = value; } public synchronized T getValue() { return this.value; } }
16.538462
48
0.609302
f428ab62ac5686808cfca2ba9421aa81467b1882
7,941
package com.quorum.tessera.config.migration; import com.quorum.tessera.cli.CliAdapter; import com.quorum.tessera.cli.CliResult; import com.quorum.tessera.cli.CliType; import com.quorum.tessera.config.Config; import com.quorum.tessera.config.KeyConfiguration; import com.quorum.tessera.config.builder.ConfigBuilder; import com.quorum.tessera.config.builder.JdbcConfigFactory; import com.quorum.tessera.config.builder.KeyDataBuilder; import com.quorum.tessera.config.util.JaxbUtil; import com.quorum.tessera.io.FilesDelegate; import com.quorum.tessera.io.SystemAdapter; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Mixin; import javax.validation.ConstraintViolationException; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.concurrent.Callable; @Command( headerHeading = "Usage:%n%n", synopsisHeading = "%n", descriptionHeading = "%nDescription:%n%n", parameterListHeading = "%nParameters:%n", optionListHeading = "%nOptions:%n", header = "Generate Tessera JSON config file from a Constellation TOML config file") public class LegacyCliAdapter implements CliAdapter, Callable<CliResult> { private final FilesDelegate fileDelegate; private final TomlConfigFactory configFactory; @Option(names = "help", usageHelp = true, description = "display this help message") private boolean isHelpRequested; @Option(names = "--outputfile", arity = "1", description = "the path to write the configuration to") private Path outputPath = Paths.get("tessera-config.json"); @Option(names = "--tomlfile", arity = "1", description = "the path to the existing TOML configuration") private Path tomlfile; @Mixin private LegacyOverridesMixin overrides = new LegacyOverridesMixin(); public LegacyCliAdapter() { this.configFactory = new TomlConfigFactory(); this.fileDelegate = FilesDelegate.create(); } @Override public CliType getType() { return CliType.CONFIG_MIGRATION; } @Override public CliResult call() throws Exception { return this.execute(); } @Override public CliResult execute(String... args) throws Exception { final ConfigBuilder configBuilder = Optional.ofNullable(tomlfile) .map(fileDelegate::newInputStream) .map(stream -> this.configFactory.create(stream, null)) .orElse(ConfigBuilder.create()); final KeyDataBuilder keyDataBuilder = Optional.ofNullable(tomlfile) .map(fileDelegate::newInputStream) .map(configFactory::createKeyDataBuilder) .orElse(KeyDataBuilder.create()); ConfigBuilder adjustedConfig = applyOverrides(configBuilder, keyDataBuilder); Config config = adjustedConfig.build(); return writeToOutputFile(config, outputPath); } static CliResult writeToOutputFile(Config config, Path outputPath) throws IOException { SystemAdapter systemAdapter = SystemAdapter.INSTANCE; systemAdapter.out().printf("Saving config to %s", outputPath); systemAdapter.out().println(); JaxbUtil.marshalWithNoValidation(config, systemAdapter.out()); systemAdapter.out().println(); try (OutputStream outputStream = Files.newOutputStream(outputPath)) { JaxbUtil.marshal(config, outputStream); systemAdapter.out().printf("Saved config to %s", outputPath); systemAdapter.out().println(); return new CliResult(0, false, config); } catch (ConstraintViolationException validationException) { validationException.getConstraintViolations().stream() .map(cv -> "Warning: " + cv.getMessage() + " on property " + cv.getPropertyPath()) .forEach(systemAdapter.err()::println); Files.write(outputPath, JaxbUtil.marshalToStringNoValidation(config).getBytes()); systemAdapter.out().printf("Saved config to %s", outputPath); systemAdapter.out().println(); return new CliResult(2, false, config); } } ConfigBuilder applyOverrides(ConfigBuilder configBuilder, KeyDataBuilder keyDataBuilder) { Optional.ofNullable(overrides.workdir).ifPresent(configBuilder::workdir); Optional.ofNullable(overrides.workdir).ifPresent(keyDataBuilder::withWorkingDirectory); Optional.ofNullable(overrides.url) .map( url -> { try { return new URL(url); } catch (MalformedURLException e) { throw new RuntimeException("Bad server url given: " + e.getMessage()); } }) .map(uri -> uri.getProtocol() + "://" + uri.getHost()) .ifPresent(configBuilder::serverHostname); Optional.ofNullable(overrides.port).ifPresent(configBuilder::serverPort); Optional.ofNullable(overrides.socket).ifPresent(configBuilder::unixSocketFile); Optional.ofNullable(overrides.othernodes).ifPresent(configBuilder::peers); Optional.ofNullable(overrides.publickeys).ifPresent(keyDataBuilder::withPublicKeys); Optional.ofNullable(overrides.privatekeys).ifPresent(keyDataBuilder::withPrivateKeys); Optional.ofNullable(overrides.alwayssendto).ifPresent(configBuilder::alwaysSendTo); Optional.ofNullable(overrides.passwords).ifPresent(keyDataBuilder::withPrivateKeyPasswordFile); Optional.ofNullable(overrides.storage) .map(JdbcConfigFactory::fromLegacyStorageString) .ifPresent(configBuilder::jdbcConfig); if (overrides.whitelist) { configBuilder.useWhiteList(true); } Optional.ofNullable(overrides.tls).ifPresent(configBuilder::sslAuthenticationMode); Optional.ofNullable(overrides.tlsservertrust).ifPresent(configBuilder::sslServerTrustMode); Optional.ofNullable(overrides.tlsclienttrust).ifPresent(configBuilder::sslClientTrustMode); Optional.ofNullable(overrides.tlsservercert).ifPresent(configBuilder::sslServerTlsCertificatePath); Optional.ofNullable(overrides.tlsclientcert).ifPresent(configBuilder::sslClientTlsCertificatePath); Optional.ofNullable(overrides.tlsserverchain).ifPresent(configBuilder::sslServerTrustCertificates); Optional.ofNullable(overrides.tlsclientchain).ifPresent(configBuilder::sslClientTrustCertificates); Optional.ofNullable(overrides.tlsserverkey).ifPresent(configBuilder::sslServerTlsKeyPath); Optional.ofNullable(overrides.tlsclientkey).ifPresent(configBuilder::sslClientTlsKeyPath); Optional.ofNullable(overrides.tlsknownservers).ifPresent(configBuilder::sslKnownServersFile); Optional.ofNullable(overrides.tlsknownclients).ifPresent(configBuilder::sslKnownClientsFile); final KeyConfiguration keyConfiguration = keyDataBuilder.build(); if (!keyConfiguration.getKeyData().isEmpty()) { configBuilder.keyData(keyConfiguration); } else if (overrides.passwords != null) { SystemAdapter.INSTANCE .err() .println( "Info: Public/Private key data not provided in overrides. Overriden password file has not been added to config."); } return configBuilder; } // TODO: remove. Here for testing public void setOverrides(final LegacyOverridesMixin overrides) { this.overrides = overrides; } }
44.61236
142
0.68606
57248c7ba922359204a9f0574b224433c8255627
3,921
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.psd2.sandbox.tpp.rest.server.auth; import de.adorsys.psd2.sandbox.tpp.rest.api.resource.TppRestApi; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.env.Environment; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.context.SecurityContextHolder; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class DisableEndpointFilterTest { @InjectMocks private DisableEndpointFilter filter; @Mock private HttpServletRequest request = new MockHttpServletRequest(); @Mock private HttpServletResponse response = new MockHttpServletResponse(); @Mock private FilterChain chain; @Mock private Environment env; @Test void doFilterInternal_uri_not_present_in_map() throws IOException, ServletException { // Given SecurityContextHolder.clearContext(); when(request.getServletPath()).thenReturn(TppRestApi.BASE_PATH + "/login"); // When filter.doFilter(request, response, chain); // Then verify(chain, times(1)).doFilter(any(), any()); } @Test void doFilterInternal_uri_is_in_map_not_in_profile() throws IOException, ServletException { // Given SecurityContextHolder.clearContext(); when(request.getServletPath()).thenReturn(TppRestApi.BASE_PATH + "/register"); // When filter.doFilter(request, response, chain); // Then verify(chain, times(1)).doFilter(any(), any()); } @Test void doFilterInternal_uri_is_in_map_and_in_profile_false() throws IOException, ServletException { // Given SecurityContextHolder.clearContext(); when(request.getServletPath()).thenReturn(TppRestApi.BASE_PATH + "/register"); when(env.getProperty(anyString(),eq(Boolean.class))).thenReturn(false); // When filter.doFilter(request, response, chain); // Then verify(chain, times(1)).doFilter(any(), any()); } @Test void doFilterInternal_uri_is_in_map_and_in_profile_true() throws IOException, ServletException { // Given SecurityContextHolder.clearContext(); when(request.getServletPath()).thenReturn(TppRestApi.BASE_PATH + "/register"); when(env.getProperty(anyString(),eq(Boolean.class))).thenReturn(true); // When filter.doFilter(request, response, chain); // Then verify(chain, times(0)).doFilter(any(), any()); } }
35.008929
101
0.7266
a67f8fc58113e307e897578fc7d2f971a3668a77
4,847
package asl.sensor.gui; import asl.sensor.ExperimentFactory; import asl.sensor.experiment.SpectralAnalysisExperiment; import asl.sensor.input.DataStore; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import javax.swing.JCheckBox; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class NoiseModelPanel extends SpectralAnalysisPanel { final JCheckBox freqSpaceBox; private final NumberAxis freqAxis; /** * Construct a new panel, using a backend defined by the passed-in enum * * @param experiment Experiment enum with corresponding backend for factory instantiation */ public NoiseModelPanel(ExperimentFactory experiment) { super(experiment); for (int i = 0; i < 3; ++i) { channelType[i] = "Input data (RESP required)"; } plotTheseInBold = new String[]{"NLNM", "NHNM"}; xAxis = new LogarithmicAxis("Period (s)"); freqAxis = new LogarithmicAxis("Frequency (Hz)"); yAxis = new NumberAxis("Power (rel. 1 (m/s^2)^2/Hz)"); yAxis.setAutoRange(true); ((NumberAxis) yAxis).setAutoRangeIncludesZero(false); Font bold = xAxis.getLabelFont(); bold = bold.deriveFont(Font.BOLD, bold.getSize() + 2); xAxis.setLabelFont(bold); yAxis.setLabelFont(bold); freqAxis.setLabelFont(bold); freqSpaceBox = new JCheckBox("Use Hz units"); freqSpaceBox.setSelected(false); freqSpaceBox.addActionListener(this); applyAxesToChart(); // now that we've got axes defined // set the GUI components this.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.CENTER; this.add(chartPanel, constraints); // place the other UI elements in a single row below the chart constraints.gridwidth = 1; constraints.weighty = 0.0; constraints.weightx = 0.0; constraints.anchor = GridBagConstraints.WEST; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridy += 1; constraints.gridx = 0; freqSpaceBox.setPreferredSize(noiseModelButton.getPreferredSize()); freqSpaceBox.setMaximumSize(noiseModelButton.getMaximumSize()); freqSpaceBox.setMinimumSize(noiseModelButton.getMinimumSize()); freqSpaceBox.setSize(noiseModelButton.getSize()); this.add(freqSpaceBox, constraints); constraints.gridx += 1; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.CENTER; this.add(save, constraints); // add an empty panel as a spacer to keep the save button in the center constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx += 1; constraints.weightx = 0; constraints.anchor = GridBagConstraints.EAST; this.add(noiseModelButton, constraints); } @Override protected void drawCharts() { XYSeriesCollection data = new XYSeriesCollection(); { SpectralAnalysisExperiment spectExp = (SpectralAnalysisExperiment) expResult; if (spectExp.noiseModelLoaded()) { XYSeries series = spectExp.getPlottableNoiseModelData(freqSpaceBox.isSelected()); for (int i = 0; i < series.getItemCount(); ++i) { System.out.println(series.getDataItem(i)); } seriesColorMap.put((String) series.getKey(), Color.BLACK); data.addSeries(spectExp.getPlottableNoiseModelData(freqSpaceBox.isSelected())); } } setChart(data); chartPanel.setChart(chart); chartPanel.setMouseZoomable(true); } @Override public int panelsNeeded() { return 0; } @Override protected void updateData(DataStore dataStore) { // this also does nothing, as no data beyond the noise model is needed } /** * Gets the x-axis for this panel based on whether or not the * selection box to plot in units of Hz is selected. If it is, this * plot will have frequency units of Hz in the x-axis, otherwise it will have * interval units of seconds in it */ @Override public ValueAxis getXAxis() { // true if using Hz units if (freqSpaceBox.isSelected()) { return freqAxis; } return xAxis; } @Override public void actionPerformed(ActionEvent event) { super.actionPerformed(event); // override because this way we draw the charts anyway if (event.getSource() == noiseModelButton || event.getSource() == freqSpaceBox) { drawCharts(); } } }
32.099338
91
0.711574
815e977b69b35882c6b61a45f55adc81a07a639e
8,063
package com.yugabyte.hibernatedemo.server; import com.google.gson.Gson; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import com.yugabyte.hibernatedemo.Exceptions.ResourceNotFoundException; import com.yugabyte.hibernatedemo.model.Product; import com.yugabyte.hibernatedemo.model.User; import com.yugabyte.hibernatedemo.model.requests.CreateOrderRequest; import com.yugabyte.hibernatedemo.model.requests.UserIdClass; import com.yugabyte.hibernatedemo.model.response.CreateOrderResponse; import com.yugabyte.hibernatedemo.service.DemoService; import org.apache.log4j.Logger; import java.io.*; import java.net.InetSocketAddress; import java.util.List; import java.util.Properties; public class BasicHttpServer { final static Logger logger = Logger.getLogger(BasicHttpServer.class); private static DemoService service = new DemoService(); private static Properties applicationProperties; private static void readProperties() { try (InputStream in = BasicHttpServer.class.getClassLoader().getResourceAsStream("config.properties")) { applicationProperties = new Properties(); assert in != null; applicationProperties.load(in); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { readProperties(); int port = Integer.parseInt(applicationProperties.getProperty("server.port", "8080")); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); logger.info("Listening on port: " + port); server.createContext("/users") .setHandler(BasicHttpServer::handleUsersRequest); server.createContext("/products") .setHandler(BasicHttpServer::handleProductRequest); server.createContext("/orders") .setHandler(BasicHttpServer::handleCreateOrder); server.createContext("/list-orders") .setHandler(BasicHttpServer::handleListOrders); server.createContext("/") .setHandler(BasicHttpServer::handleRootRequest); server.start(); } private static void handleRootRequest(final HttpExchange exchange) throws IOException { exchange.sendResponseHeaders(404, 0); exchange.close(); } private static void handleProductRequest(final HttpExchange exchange) throws IOException { if (exchange.getRequestMethod().equals("POST")) { handleCreateProduct(exchange); } else { handleListProducts(exchange); } } private static void handleUsersRequest(final HttpExchange exchange) throws IOException { if (exchange.getRequestMethod().equals("POST")) { handleUserPostRequest(exchange); } else { handleUserGetRequest(exchange); } } private static void handleUserPostRequest(final HttpExchange exchange) throws IOException { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); User user = gson.fromJson(reader, User.class); try { service.create(user); sendJsonResponse(exchange, gson.toJson(user)); } catch( ResourceNotFoundException rnfe ) { sendErrorResponse(exchange, 400, rnfe.getMessage()); rnfe.printStackTrace(); } catch( RuntimeException rte) { sendErrorResponse(exchange, 500, "Internal Server error"); rte.printStackTrace(); } } private static void handleUserGetRequest(final HttpExchange exchange) throws IOException { final Gson gson = new Gson(); try { List<User> allUsers = service.getAllUsers(); sendJsonResponse(exchange, gson.toJson(allUsers)); } catch( ResourceNotFoundException rnfe ) { sendErrorResponse(exchange, 400, rnfe.getMessage()); rnfe.printStackTrace(); } catch( RuntimeException rte) { sendErrorResponse(exchange, 500, "Internal Server error"); rte.printStackTrace(); } } private static void handleCreateProduct(final HttpExchange exchange) throws IOException { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); Product product = gson.fromJson(reader, Product.class); try { service.create(product); sendJsonResponse(exchange, gson.toJson(product)); } catch( ResourceNotFoundException rnfe ) { sendErrorResponse(exchange, 400, rnfe.getMessage()); rnfe.printStackTrace(); } catch( RuntimeException rte) { sendErrorResponse(exchange, 500, "Internal Server error"); rte.printStackTrace(); } } private static void sendJsonResponse(final HttpExchange exchange, final String json) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, json.length()); try (OutputStream os = exchange.getResponseBody()) { os.write(json.getBytes()); } } private static void sendErrorResponse(final HttpExchange exchange, final int errorCode, final String message) throws IOException { Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "application/text"); exchange.sendResponseHeaders(errorCode, message.length()); try (OutputStream os = exchange.getResponseBody()) { os.write(message.getBytes()); } } private static void handleListProducts(final HttpExchange exchange) throws IOException { final Gson gson = new Gson(); try { List<Product> allProducts = service.getAllProducts(); sendJsonResponse(exchange, gson.toJson(allProducts)); } catch( ResourceNotFoundException rnfe ) { sendErrorResponse(exchange, 400, rnfe.getMessage()); rnfe.printStackTrace(); } catch( RuntimeException rte) { sendErrorResponse(exchange, 500, "Internal Server error"); rte.printStackTrace(); } } private static void handleCreateOrder(final HttpExchange exchange) throws IOException { try { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); CreateOrderRequest request = gson.fromJson(reader, CreateOrderRequest.class); CreateOrderResponse response = service.create(request); sendJsonResponse(exchange, gson.toJson(response)); } catch( ResourceNotFoundException rnfe ) { sendErrorResponse(exchange, 400, rnfe.getMessage()); rnfe.printStackTrace(); } catch( RuntimeException rte) { sendErrorResponse(exchange, 500, "Internal Server error"); rte.printStackTrace(); } } private static void handleListOrders(final HttpExchange exchange) throws IOException { try { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); UserIdClass request = gson.fromJson(reader, UserIdClass.class); sendJsonResponse(exchange, gson.toJson(service.listOrders(request.userId))); } catch( ResourceNotFoundException rnfe ) { sendErrorResponse(exchange, 400, rnfe.getMessage()); rnfe.printStackTrace(); } catch( RuntimeException rte) { sendErrorResponse(exchange, 500, "Internal Server error"); rte.printStackTrace(); } } }
40.114428
134
0.661912
d8835c0ce73c896b43f75e8986520ed588fbc207
1,106
package com.zzjson.order.repository; import com.zzjson.order.dataobject.OrderMaster; import com.zzjson.order.enums.OrderStatus; import com.zzjson.order.enums.PayStatus; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.math.BigDecimal; import java.sql.Date; public class OrderMasterRepositoryTest extends BaseTest { @Autowired private OrderMasterRepository repository; @Test public void save() { OrderMaster orderMaster = new OrderMaster(); orderMaster.setOrderId("32"); orderMaster.setBuyerName("21"); orderMaster.setBuyerPhone("2"); orderMaster.setBuyerAddress("33"); orderMaster.setBuyerOpenid("321"); orderMaster.setOrderAmount(new BigDecimal("0")); orderMaster.setOrderStatus(OrderStatus.CANCLE.getCode()); orderMaster.setPayStatus(PayStatus.SUCCESS.getCode()); orderMaster.setCreateTime(new Date(new java.util.Date().getTime())); orderMaster.setUpdateTime(new Date(new java.util.Date().getTime())); repository.save(orderMaster); } }
35.677419
76
0.725136
0c8b84a459954ff320a6ea0a7dc6e3a84e81881a
848
package kdu_jni; public class Jp2_locator { static { System.loadLibrary("kdu_jni"); Native_init_class(); } private static native void Native_init_class(); protected long _native_ptr = 0; protected Jp2_locator(long ptr) { _native_ptr = ptr; } public native void Native_destroy(); public void finalize() { if ((_native_ptr & 1) != 0) { // Resource created and not donated Native_destroy(); } } private static native long Native_create(); public Jp2_locator() { this(Native_create()); } public native boolean Is_null() throws KduException; public native long Get_file_pos() throws KduException; public native void Set_file_pos(long _pos) throws KduException; public native long Get_databin_id() throws KduException; public native long Get_databin_pos() throws KduException; }
28.266667
65
0.713443
f25cba2829f034dedb0ba2b7144f1108ecd6ddf2
2,594
/* * 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.apache.cassandra.db.guardrails; import org.junit.Test; import org.apache.cassandra.schema.SchemaConstants; import org.apache.cassandra.schema.SchemaKeyspaceTables; public class GuardrailGroupByTest extends GuardrailTester { private static final String query = String.format("SELECT * FROM %s.%s WHERE keyspace_name='%s' GROUP BY table_name", SchemaConstants.SCHEMA_KEYSPACE_NAME, SchemaKeyspaceTables.TABLES, KEYSPACE); private void setGuardrail(boolean enabled) { Guardrails.instance.setGroupByEnabled(enabled); } @Test public void checkExplicitlyDisabled() throws Throwable { setGuardrail(false); assertFails(query, "GROUP BY functionality is not allowed"); } @Test public void testExcludedUsers() throws Throwable { setGuardrail(false); testExcludedUsers(() -> query); } @Test public void checkEnabled() throws Throwable { setGuardrail(true); assertValid(query); } @Test public void checkView() throws Throwable { setGuardrail(false); createTable( "CREATE TABLE %s(pk int, ck int, v int, PRIMARY KEY(pk, ck))"); String viewName = createView("CREATE MATERIALIZED VIEW %s AS " + "SELECT * FROM %s WHERE pk IS NOT null and ck IS NOT null " + "PRIMARY KEY(ck, pk)"); String viewQuery = "SELECT * FROM " + viewName + " WHERE ck=0 GROUP BY pk"; assertFails(viewQuery, "GROUP BY functionality is not allowed"); testExcludedUsers(() -> viewQuery); } }
36.027778
121
0.639938
2e1b33f0f9a88b28c072b57342e561e140aa92a3
348
/* * 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 Main; import Components.Cell; /** * * @author Sandun Rajitha */ public class GanttChart { public GanttChart(Cell cell) { } }
15.130435
79
0.666667
a0fed16aeb6a03cb2ae7c0c3061786ba8644c698
382
package cana.codelessautomation.api.resources.notification.service.mappers; import cana.codelessautomation.api.resources.notification.service.repositories.daos.NotificationDao; import cana.codelessautomation.api.resources.schedule.service.dtos.CreateScheduleDto; public interface NotificationMapper { NotificationDao mapNotificationDao(CreateScheduleDto createScheduleDto); }
42.444444
100
0.871728
70064b8b71a3287e4c4e6cd8926cda51c081d9e2
1,763
package com.lgy.common.utils.xml; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; /** * Jaxb2工具类 * * @author LGy * @create 2017年10月23日 */ public class JaxbUtil { /** * JavaBean转换成xml * 默认编码UTF-8 * * @param obj * @return */ public static String convertToXml(Object obj) { return convertToXml(obj, "UTF-8"); } /** * JavaBean转换成xml * * @param obj * @param encoding * @return */ public static String convertToXml(Object obj, String encoding) { String result = null; try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); result = writer.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * xml转换成JavaBean * * @param xml * @param c * @return */ @SuppressWarnings("unchecked") public static <T> T converyToJavaBean(String xml, Class<T> c) { T t = null; try { JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); t = (T) unmarshaller.unmarshal(new StringReader(xml)); } catch (Exception e) { e.printStackTrace(); } return t; } }
23.824324
75
0.587635
f9525e2772801047a8a1eda2c72678b0345097ef
951
package ch.heigvd.res.chill.domain.RobelT; import ch.heigvd.res.chill.domain.Bartender; import ch.heigvd.res.chill.protocol.OrderRequest; import ch.heigvd.res.chill.protocol.OrderResponse; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; class DespeTest { @Test void thePriceAndNameForDespeShouldBeCorrect() { Despe beer = new Despe(); assertEquals(beer.getName(), Despe.NAME); assertEquals(beer.getPrice(), Despe.PRICE); } @Test void aBartenderShouldAcceptAnOrderForDespe() { Bartender Jeffrey = new Bartender(); String productName = "ch.heigvd.res.chill.domain.RobelT.Despe"; OrderRequest request = new OrderRequest(3, productName); OrderResponse response = Jeffrey.order(request); BigDecimal expectedTotalPrice = Despe.PRICE.multiply(new BigDecimal(3)); assertEquals(expectedTotalPrice, response.getTotalPrice()); } }
30.677419
76
0.761304
64984fed5ba92d86b127fe974bcc0ad513576167
4,882
/* * 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.apache.jackrabbit.oak.segment.spi.monitor; import static org.junit.Assert.assertEquals; import java.io.File; import com.google.common.collect.ImmutableList; import org.apache.jackrabbit.oak.spi.whiteboard.Registration; import org.junit.Test; public class CompositeIOMonitorTest { private static final File FILE = new File(""); @Test public void testComposition() { ImmutableList<IOMonitorAssertion> ioMonitors = ImmutableList.of(new IOMonitorAssertion(), new IOMonitorAssertion()); IOMonitor ioMonitor = new CompositeIOMonitor(ioMonitors); ioMonitor.beforeSegmentRead(FILE, 0, 0, 0); ioMonitor.afterSegmentRead(FILE, 0, 0, 1, 0); ioMonitor.beforeSegmentWrite(FILE, 0, 0, 2); ioMonitor.afterSegmentWrite(FILE, 0, 0, 3, 0); ioMonitors.forEach(ioMonitorAssertion -> { ioMonitorAssertion.assertBeforeReadLength(0); ioMonitorAssertion.assertAfterReadLength(1); ioMonitorAssertion.assertBeforeWriteLength(2); ioMonitorAssertion.assertAfterWriteLength(3); }); } @Test public void testUnregisterComposition() { ImmutableList<IOMonitorAssertion> ioMonitors = ImmutableList.of(new IOMonitorAssertion(), new IOMonitorAssertion()); CompositeIOMonitor ioMonitor = new CompositeIOMonitor(); ioMonitor.registerIOMonitor(ioMonitors.get(0)); Registration registration = ioMonitor.registerIOMonitor(ioMonitors.get(1)); ioMonitor.beforeSegmentRead(FILE, 0, 0, 0); ioMonitor.afterSegmentRead(FILE, 0, 0, 1, 0); ioMonitor.beforeSegmentWrite(FILE, 0, 0, 2); ioMonitor.afterSegmentWrite(FILE, 0, 0, 3, 0); ioMonitors.forEach(ioMonitorAssertion -> { ioMonitorAssertion.assertBeforeReadLength(0); ioMonitorAssertion.assertAfterReadLength(1); ioMonitorAssertion.assertBeforeWriteLength(2); ioMonitorAssertion.assertAfterWriteLength(3); }); registration.unregister(); ioMonitor.beforeSegmentRead(FILE, 0, 0, 4); ioMonitor.afterSegmentRead(FILE, 0, 0, 5, 0); ioMonitor.beforeSegmentWrite(FILE, 0, 0, 6); ioMonitor.afterSegmentWrite(FILE, 0, 0, 7, 0); ioMonitors.get(0).assertBeforeReadLength(4); ioMonitors.get(0).assertAfterReadLength(5); ioMonitors.get(0).assertBeforeWriteLength(6); ioMonitors.get(0).assertAfterWriteLength(7); ioMonitors.get(1).assertBeforeReadLength(0); ioMonitors.get(1).assertAfterReadLength(1); ioMonitors.get(1).assertBeforeWriteLength(2); ioMonitors.get(1).assertAfterWriteLength(3); } private static class IOMonitorAssertion implements IOMonitor { private int beforeReadLength = -1; private int afterReadLength = -1; private int beforeWriteLength = -1; private int afterWriteLength = -1; @Override public void beforeSegmentRead(File file, long msb, long lsb, int length) { beforeReadLength = length; } @Override public void afterSegmentRead(File file, long msb, long lsb, int length, long elapsed) { afterReadLength = length; } @Override public void beforeSegmentWrite(File file, long msb, long lsb, int length) { beforeWriteLength = length; } @Override public void afterSegmentWrite(File file, long msb, long lsb, int length, long elapsed) { afterWriteLength = length; } public void assertBeforeReadLength(int length) { assertEquals(length, beforeReadLength); } public void assertAfterReadLength(int length) { assertEquals(length, afterReadLength); } public void assertBeforeWriteLength(int length) { assertEquals(length, beforeWriteLength); } public void assertAfterWriteLength(int length) { assertEquals(length, afterWriteLength); } } }
36.984848
96
0.676977
f6c38cb69e5e9f49735bc1553d1073641ee0a53f
818
package com.alibaba.alink.params.dataproc.format; import org.apache.flink.ml.api.misc.param.ParamInfo; import org.apache.flink.ml.api.misc.param.ParamInfoFactory; import org.apache.flink.ml.api.misc.param.WithParams; public interface HasKvValDelimiterDefaultAsColon<T> extends WithParams<T> { /** * @cn-name 分隔符 * @cn 当输入数据为稀疏格式时,key和value的分割符 */ ParamInfo <String> KV_VAL_DELIMITER = ParamInfoFactory .createParamInfo("kvValDelimiter", String.class) .setDescription("Delimiter used between keys and values when data in the input table is in sparse format") .setAlias(new String[]{"valDelimiter"}) .setHasDefaultValue(":") .build(); default String getKvValDelimiter() { return get(KV_VAL_DELIMITER); } default T setKvValDelimiter(String value) { return set(KV_VAL_DELIMITER, value); } }
30.296296
108
0.764059
e352ca1203da34ffee743b7996e36b95db858e1f
1,339
/* * Copyright 2015 XXX * * 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 xxx.web.comments.clustering.embeddings; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * (c) 2015 XXX */ public class WholeDocumentEmbeddingsAnnotator extends EmbeddingsAnnotator { @Override protected Collection<? extends Annotation> selectAnnotationsForEmbeddings(JCas aJCas) { // create dummy annotation Paragraph p = new Paragraph(aJCas, 0, aJCas.getDocumentText().length()); p.addToIndexes(); List<Annotation> result = new ArrayList<>(); result.add(p); return result; } }
28.489362
89
0.719193
8f45de5bf9c9313c5fb1efe076b51065bf205954
1,192
package interpreter.ast; import interpreter.ast.visitor.NodeVisitor; import interpreter.lexer.Token; /** * Created by Thomas on 2-3-2015. */ public class Literal extends Expression { private final int literalType; private final Object value; public Literal(int lineIndex, int columnIndex, int literalType, Object value) { super(lineIndex, columnIndex); this.literalType = literalType; this.value = value; } public boolean getBooleanValue(){ return (Boolean)value; } public int getLiteralType() { return literalType; } public Object getValue() { return value; } public double getDoubleValue(){ return (Double)value; } public int getIntValue(){ return (Integer)value; } public String getStringValue(){ return (String)value; } @Override public String toString() { return "Literal{" + "literalType=" + Token.toString(literalType) + ", value=" + value + '}'; } @Override public void visit(NodeVisitor visitor) { visitor.visitLiteral(value, literalType); } }
20.551724
83
0.608221
dc14acef7a99d18d2743ec886591789a5e6d7277
1,941
/* * Copyright © 2017 M.E Xezonaki in the context of her MSc Thesis, * Department of Informatics and Telecommunications, UoA. * All rights reserved. */ package sqmf.impl; /** * The class modelling a node of the domain. * * @author Marievi Xezonaki */ public class DomainNode { private int nodeID = -1; private int parentGraphID = -1; private String ODLNodeID; private static int nodeIDCnt = 0; /** * The method which returns the number of inserted nodes. * * @return The number of inserted nodes. */ public static int getNodeIDCnt(){ return ++nodeIDCnt; } /** * The method which returns the ID of the node. * * @return The ID of the node. */ public int getNodeID() { return nodeID; } /** * The method which sets the ID of the node. * * @param nodeID The ID to be set to the node. */ public void setNodeID(int nodeID) { this.nodeID = nodeID; } /** * The method which returns the ODL ID of the node. * * @return The ODL ID of the node. */ public String getODLNodeID() { return ODLNodeID; } /** * The method which sets the ODL ID of the node. * * @param ODLNodeID The ODL ID to be set to the node. */ public void setODLNodeID(String ODLNodeID) { this.ODLNodeID = ODLNodeID; } /** * The method which sets the ID of the graph where the node belongs. * * @param parentGraphID The ID of the graph where the node belongs. */ public void setParentGraphID(int parentGraphID) { this.parentGraphID = parentGraphID; } /** * The method which returns ID of the graph where the node belongs. * * @return parentGraphID The ID of the graph where the node belongs. */ public int getParentGraphID() { return parentGraphID; } }
21.32967
76
0.597115
24bcbfc04154fd660ee37809fa49fc66c55c5979
4,108
package rsb.service; import lombok.extern.slf4j.Slf4j; import rsb.script.Script; import rsb.script.ScriptManifest; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Logger; /** * @author GigiaJ */ @Slf4j public class FileScriptSource implements ScriptSource { //private final Logger log = Logger.getLogger(getClass().getSimpleName()); private File file; public FileScriptSource(File file) { this.file = file; } public List<ScriptDefinition> list() { LinkedList<ScriptDefinition> defs = new LinkedList<ScriptDefinition>(); if (file != null) { if (file.isDirectory()) { try { ClassLoader ldr = new ScriptClassLoader(file.toURI().toURL()); for (File f : file.listFiles()) { if (isJar(f)) { load(new ScriptClassLoader(getJarUrl(f)), defs, new JarFile(f)); } else { load(ldr, defs, f, ""); } } } catch (IOException ignored) { log.debug("Failed to list files", ignored); } } else if (isJar(file)) { try { ClassLoader ldr = new ScriptClassLoader(getJarUrl(file)); load(ldr, defs, new JarFile(file)); } catch (IOException ignored) { log.debug("Failed to list files", ignored); } } } return defs; } public Script load(ScriptDefinition def) throws ServiceException { if (!(def instanceof FileScriptDefinition)) { throw new IllegalArgumentException("Invalid definition!"); } FileScriptDefinition fsd = (FileScriptDefinition) def; try { return fsd.clazz.asSubclass(Script.class).newInstance(); } catch (Exception ex) { throw new ServiceException(ex.toString()); } } private void load(ClassLoader loader, LinkedList<ScriptDefinition> scripts, JarFile jar) { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry e = entries.nextElement(); String name = e.getName().replace('/', '.'); String ext = ".class"; if (name.endsWith(ext) && !name.contains("$")) { load(loader, scripts, name.substring(0, name.length() - ext.length())); } } } private void load(ClassLoader loader, LinkedList<ScriptDefinition> scripts, File file, String prefix) { if (file.isDirectory()) { if (!file.getName().startsWith(".")) { for (File f : file.listFiles()) { load(loader, scripts, f, prefix + file.getName() + "."); } } } else { String name = prefix + file.getName(); String ext = ".class"; if (name.endsWith(ext) && !name.startsWith(".") && !name.contains("!") && !name.contains("$")) { name = name.substring(0, name.length() - ext.length()); load(loader, scripts, name); } } } private void load(ClassLoader loader, LinkedList<ScriptDefinition> scripts, String name) { Class<?> clazz; try { clazz = loader.loadClass(name); } catch (Exception e) { log.warn(name + " is not a valid script and was ignored!", e); return; } catch (VerifyError e) { log.warn(name + " is not a valid script and was ignored!", e); return; } if (clazz.isAnnotationPresent(ScriptManifest.class)) { FileScriptDefinition def = new FileScriptDefinition(); ScriptManifest manifest = clazz.getAnnotation(ScriptManifest.class); def.id = 0; def.name = manifest.name(); def.authors = manifest.authors(); def.version = manifest.version(); def.keywords = manifest.keywords(); def.description = manifest.description(); def.website = manifest.website(); def.clazz = clazz; def.source = this; scripts.add(def); } } private boolean isJar(File file) { return file.getName().endsWith(".jar") || file.getName().endsWith(".dat"); } private URL getJarUrl(File file) throws IOException { URL url = file.toURI().toURL(); url = new URL("jar:" + url.toExternalForm() + "!/"); return url; } private static class FileScriptDefinition extends ScriptDefinition { Class<?> clazz; } public String toString() { return this.file.getAbsolutePath(); } }
27.57047
104
0.666991
b6aaff4adaec90426aac31eead67eb888b2a80ae
316
package se.foodload.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import se.foodload.domain.ItemCategory; public interface ItemCategoryRepository extends JpaRepository<ItemCategory, Long> { public Optional<ItemCategory> findByName(String itemCategory); }
24.307692
83
0.835443
53720b348a12c8ca65c0d27b9a0a5e91b4e3eb30
4,724
package com.mygdx.game.Modele; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.utils.Array; import com.mygdx.game.Controleur.MTCGame; public class DecorDecharge implements DecorDef { private Texture sky; private Texture background; private Texture midBackground; private Texture exitScreenTexture; private Texture solDepart; private TiledMap tiledMap; private Music music; private Array<String> solTexturesReferences = new Array<String>(); private Array<String> assetsReferences = new Array<String>(); private String exitBackGroundRef = "textures DecorDecharge/exitScreenBackground-Decharge.png"; public DecorDecharge(MTCGame mtcGame) { music = mtcGame.getAssetManager().get("Decharge-Flute-Music.mp3",Music.class); tiledMap = mtcGame.getAssetManager().get("textures DecorDecharge/mapDecharge.tmx",TiledMap.class); background = mtcGame.getAssetManager().get("textures DecorDecharge/Paysage-Decharge.png",Texture.class); midBackground = mtcGame.getAssetManager().get("textures DecorDecharge/AP-MTC-Decharge.png",Texture.class); exitScreenTexture = mtcGame.getAssetManager().get("textures DecorDecharge/exitScreenBackground-Decharge.png",Texture.class); sky = mtcGame.getAssetManager().get("textures DecorDecharge/sky.png",Texture.class); solDepart = mtcGame.getAssetManager().get("textures DecorDecharge/SolDepart.png",Texture.class); assetsReferences.add("Decharge-Flute-Music.mp3");assetsReferences.add("textures DecorDecharge/mapDecharge.tmx"); assetsReferences.add("textures DecorDecharge/Paysage-Decharge.png");assetsReferences.add("textures DecorDecharge/AP-MTC-Decharge.png"); assetsReferences.add("textures DecorDecharge/sky.png"); assetsReferences.add("textures DecorDecharge/SolDepart.png"); solTexturesReferences.add("textures DecorDecharge/Sol1.png");solTexturesReferences.add("textures DecorDecharge/Sol2.png"); solTexturesReferences.add("textures DecorDecharge/Sol3.png");solTexturesReferences.add("textures DecorDecharge/Sol4.png"); solTexturesReferences.add("textures DecorDecharge/Sol5.png");solTexturesReferences.add("textures DecorDecharge/Sol6.png"); solTexturesReferences.add("textures DecorDecharge/Sol7.png");solTexturesReferences.add("textures DecorDecharge/Sol8.png"); solTexturesReferences.add("textures DecorDecharge/Sol9.png");solTexturesReferences.add("textures DecorDecharge/Sol10.png"); solTexturesReferences.add("textures DecorDecharge/Sol11.png");solTexturesReferences.add("textures DecorDecharge/Sol12.png"); solTexturesReferences.add("textures DecorDecharge/Sol13.png");solTexturesReferences.add("textures DecorDecharge/Sol14.png"); solTexturesReferences.add("textures DecorDecharge/Sol15.png");solTexturesReferences.add("textures DecorDecharge/Sol16.png"); solTexturesReferences.add("textures DecorDecharge/Sol17.png");solTexturesReferences.add("textures DecorDecharge/Sol18.png"); solTexturesReferences.add("textures DecorDecharge/Sol19.png");solTexturesReferences.add("textures DecorDecharge/Sol20.png"); solTexturesReferences.add("textures DecorDecharge/Sol21.png");solTexturesReferences.add("textures DecorDecharge/Sol22.png"); solTexturesReferences.add("textures DecorDecharge/Sol23.png");solTexturesReferences.add("textures DecorDecharge/Sol24.png"); solTexturesReferences.add("textures DecorDecharge/Sol25.png");solTexturesReferences.add("textures DecorDecharge/Sol26.png"); solTexturesReferences.add("textures DecorDecharge/Sol27.png");solTexturesReferences.add("textures DecorDecharge/Sol28.png"); solTexturesReferences.add("textures DecorDecharge/Sol29.png");solTexturesReferences.add("textures DecorDecharge/Sol30.png"); } public Array<String> getSolTexturesReferences() { return solTexturesReferences; } public Array<String> getAssetsReferences() { return assetsReferences; } public Texture getSky() { return sky; } public Texture getBackground() { return background; } public Texture getMidBackground() { return midBackground; } @Override public Texture getExitScreenTexture() { return exitScreenTexture; } public float getLevelWidth() { return 28800; } public Texture getSolDepart() { return solDepart; } public Music getMusic() { return music; } public TiledMap getTiledMap() { return tiledMap; } public String getExitBackGroundRef() { return exitBackGroundRef; } }
50.795699
143
0.756351
741096681877ecde866bd1854ff7e52e4fe871b4
200
package se.liu.ida.hefquin.engine.queryproc.impl.optimizer.randomized; public interface EquilibriumConditionForSimulatedAnnealing { boolean isEquilibrium(int currentGeneration, int subplanCount); }
28.571429
70
0.855
ced8072c369761f4b0c449dc755b991c0ca5c7a4
2,913
/* * Copyright 2021, Yahoo Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE file in project root for terms. */ package com.yahoo.elide.datastores.aggregation.metadata; import static org.apache.commons.lang3.StringUtils.isBlank; import com.yahoo.elide.core.request.Argument; import com.yahoo.elide.datastores.aggregation.query.ColumnProjection; import com.yahoo.elide.datastores.aggregation.query.Queryable; import com.yahoo.elide.datastores.aggregation.queryengines.sql.metadata.SQLJoin; import lombok.Builder; import lombok.Getter; import lombok.ToString; import java.util.Map; /** * Context for resolving all handlebars in provided expression except physical references. Keeps physical references as * is. */ @Getter @ToString public class PhysicalRefColumnContext extends ColumnContext { private static final String HANDLEBAR_PREFIX = "{{"; private static final String HANDLEBAR_SUFFIX = "}}"; @Builder(builderMethodName = "physicalRefContextBuilder") public PhysicalRefColumnContext(MetaDataStore metaDataStore, Queryable queryable, String alias, ColumnProjection column, Map<String, Argument> tableArguments) { super(metaDataStore, queryable, alias, column, tableArguments); } @Override protected ColumnContext getNewContext(ColumnContext context, ColumnProjection newColumn) { return PhysicalRefColumnContext.physicalRefContextBuilder() .queryable(context.getQueryable()) .alias(context.getAlias()) .metaDataStore(context.getMetaDataStore()) .column(newColumn) .tableArguments(context.getTableArguments()) .build(); } @Override protected ColumnContext getJoinContext(String key) { SQLJoin sqlJoin = this.queryable.getJoin(key); Queryable joinQueryable = metaDataStore.getTable(sqlJoin.getJoinTableType()); String joinPath = isBlank(this.alias) ? key : this.alias + PERIOD + key; PhysicalRefColumnContext joinCtx = PhysicalRefColumnContext.physicalRefContextBuilder() .queryable(joinQueryable) .alias(joinPath) .metaDataStore(this.metaDataStore) .column(this.column) .tableArguments(mergedArgumentMap(joinQueryable.getArguments(), this.getTableArguments())) .build(); return joinCtx; } @Override protected String resolvePhysicalReference(ColumnContext context, String keyStr) { return isBlank(context.getAlias()) ? HANDLEBAR_PREFIX + keyStr + HANDLEBAR_SUFFIX : HANDLEBAR_PREFIX + context.getAlias() + PERIOD + keyStr + HANDLEBAR_SUFFIX; } }
40.458333
120
0.66392
c2be52b36ec52366c4cdce1e260227cdc34bd6f4
668
package com.onthegomap.flatmap.worker; import static org.junit.jupiter.api.Assertions.assertThrows; import com.onthegomap.flatmap.stats.Stats; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; public class WorkerTest { @Test @Timeout(10) public void testExceptionHandled() { AtomicInteger counter = new AtomicInteger(0); var worker = new Worker("prefix", Stats.inMemory(), 4, () -> { if (counter.incrementAndGet() == 1) { throw new Error(); } else { Thread.sleep(5000); } }); assertThrows(RuntimeException.class, worker::await); } }
25.692308
66
0.693114
bcfb96d04bf42fac3a142fb6de4ae73e67af2b7a
1,287
package sg.edu.nus.comp.cs3219.viz.common.util.Serializer; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; import sg.edu.nus.comp.cs3219.viz.common.entity.record.Conference; public class ConferenceSerializer extends StdSerializer<Conference> { public ConferenceSerializer() {this(null);} protected ConferenceSerializer(Class<Conference> t) { super(t); } @Override public void serialize(Conference value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); gen.writeNumberField("numAuthorRecord", value.getNumAuthorRecord()); gen.writeNumberField("numReviewRecord", value.getNumReviewRecord()); gen.writeNumberField("numSubmissionRecord", value.getNumSubmissionRecord()); gen.writeStringField("name", value.getName()); if(value.getDate() != null) { gen.writeStringField("date", value.getDate().toString()); } gen.writeStringField("description", value.getDescription()); gen.writeStringField("creator_identifier", value.getCreatorIdentifier()); gen.writeEndObject(); } }
40.21875
112
0.730381
04f5d59dc27b15a5a8cc6efe5a195218868530c1
12,449
/** * * Copyright (c) 2014 CoderKiss * * CoderKiss[AT]gmail.com * */ package com.kisstools.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.security.MessageDigest; import org.apache.http.util.ByteArrayBuffer; import android.text.TextUtils; import android.webkit.MimeTypeMap; public class FileUtil { public static final String TAG = "FileUtil"; private static final int IO_BUFFER_SIZE = 16384; public static boolean create(String absPath) { return create(absPath, false); } public static boolean create(String absPath, boolean force) { if (TextUtils.isEmpty(absPath)) { return false; } if (exists(absPath)) { return true; } String parentPath = getParent(absPath); mkdirs(parentPath, force); try { File file = new File(absPath); return file.createNewFile(); } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean mkdirs(String absPath) { return mkdirs(absPath, false); } public static boolean mkdirs(String absPath, boolean force) { File file = new File(absPath); if (exists(absPath) && !isFolder(absPath)) { if (!force) { return false; } else { delete(file); } } try { file.mkdirs(); } catch (Exception e) { e.printStackTrace(); } return exists(file); } public static boolean move(String srcPath, String dstPath) { return move(srcPath, dstPath, false); } public static boolean move(String srcPath, String dstPath, boolean force) { if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) { return false; } if (!exists(srcPath)) { return false; } if (exists(dstPath)) { if (!force) { return false; } else { delete(dstPath); } } try { File srcFile = new File(srcPath); File dstFile = new File(dstPath); return srcFile.renameTo(dstFile); } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean delete(String absPath) { if (TextUtils.isEmpty(absPath)) { return false; } File file = new File(absPath); return delete(file); } public static boolean delete(File file) { if (!exists(file)) { return true; } if (file.isFile()) { return file.delete(); } boolean result = true; File files[] = file.listFiles(); for (int index = 0; index < files.length; index++) { result |= delete(files[index]); } result |= file.delete(); return result; } public static boolean exists(String absPath) { if (TextUtils.isEmpty(absPath)) { return false; } File file = new File(absPath); return exists(file); } public static boolean exists(File file) { return file == null ? false : file.exists(); } public static boolean childOf(String childPath, String parentPath) { if (TextUtils.isEmpty(childPath) || TextUtils.isEmpty(parentPath)) { return false; } childPath = cleanPath(childPath); parentPath = cleanPath(parentPath); if (childPath.startsWith(parentPath + File.separator)) { return true; } return false; } public static int childCount(String absPath) { if (!exists(absPath)) { return 0; } File file = new File(absPath); File[] children = file.listFiles(); if (children == null || children.length == 0) { return 0; } return children.length; } public static String cleanPath(String absPath) { if (TextUtils.isEmpty(absPath)) { return absPath; } try { File file = new File(absPath); absPath = file.getCanonicalPath(); } catch (Exception e) { } return absPath; } public static long size(String absPath) { if (absPath == null) { return 0; } File file = new File(absPath); return size(file); } public static long size(File file) { if (!exists(file)) { return 0; } long length = 0; if (isFile(file)) { length = file.length(); return length; } File files[] = file.listFiles(); if (files == null || files.length == 0) { return length; } int size = files.length; for (int index = 0; index < size; index++) { File child = files[index]; length += size(child); } return length; } public static boolean copy(String srcPath, String dstPath) { return copy(srcPath, dstPath, false); } public static boolean copy(String srcPath, String dstPath, boolean force) { if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) { return false; } // check if copy source equals destination if (srcPath.equals(dstPath)) { return true; } // check if source file exists or is a directory if (!exists(srcPath) || !isFile(srcPath)) { return false; } // delete old content if (exists(dstPath)) { if (!force) { return false; } else { delete(dstPath); } } if (!create(dstPath)) { return false; } FileInputStream in = null; FileOutputStream out = null; // get streams try { in = new FileInputStream(srcPath); out = new FileOutputStream(dstPath); } catch (Exception e) { e.printStackTrace(); return false; } return copy(in, out); } public static boolean copy(InputStream is, OutputStream os) { if (is == null || os == null) { return false; } try { byte[] buffer = new byte[IO_BUFFER_SIZE]; int length; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } os.flush(); } catch (Exception e) { e.printStackTrace(); return false; } finally { try { is.close(); } catch (Exception ignore) { } try { os.close(); } catch (Exception ignore) { } } return true; } public final static boolean isFile(String absPath) { boolean exists = exists(absPath); if (!exists) { return false; } File file = new File(absPath); return isFile(file); } public final static boolean isFile(File file) { return file == null ? false : file.isFile(); } public final static boolean isFolder(String absPath) { boolean exists = exists(absPath); if (!exists) { return false; } File file = new File(absPath); return file.isDirectory(); } public static boolean isSymlink(File file) { if (file == null) { return false; } boolean isSymlink = false; try { File canon = null; if (file.getParent() == null) { canon = file; } else { File canonDir = file.getParentFile().getCanonicalFile(); canon = new File(canonDir, file.getName()); } isSymlink = !canon.getCanonicalFile().equals( canon.getAbsoluteFile()); } catch (Exception e) { } return isSymlink; } public final static String getName(File file) { return file == null ? null : getName(file.getAbsolutePath()); } public final static String getName(String absPath) { if (TextUtils.isEmpty(absPath)) { return absPath; } String fileName = null; int index = absPath.lastIndexOf("/"); if (index >= 0 && index < (absPath.length() - 1)) { fileName = absPath.substring(index + 1, absPath.length()); } return fileName; } public final static String getParent(File file) { return file == null ? null : file.getParent(); } public final static String getParent(String absPath) { if (TextUtils.isEmpty(absPath)) { return null; } absPath = cleanPath(absPath); File file = new File(absPath); return getParent(file); } public static String getStem(File file) { return file == null ? null : getStem(file.getName()); } public final static String getStem(String fileName) { if (TextUtils.isEmpty(fileName)) { return null; } int index = fileName.lastIndexOf("."); if (index > 0) { return fileName.substring(0, index); } else { return ""; } } public static String getExtension(File file) { return file == null ? null : getExtension(file.getName()); } public static String getExtension(String fileName) { if (TextUtils.isEmpty(fileName)) { return ""; } int index = fileName.lastIndexOf('.'); if (index < 0 || index >= (fileName.length() - 1)) { return ""; } return fileName.substring(index + 1); } public static String getMimeType(File file) { if (file == null) { return "*/*"; } String fileName = file.getName(); return getMimeType(fileName); } public static String getMimeType(String fileName) { if (TextUtils.isEmpty(fileName)) { return "*/*"; } String extension = getExtension(fileName); MimeTypeMap map = MimeTypeMap.getSingleton(); String type = map.getMimeTypeFromExtension(extension); if (TextUtils.isEmpty(type)) { return "*/*"; } else { return type; } } public static String fileSHA1(String absPath) { if (TextUtils.isEmpty(absPath)) { return null; } File file = new File(absPath); if (!file.exists() || file.isDirectory()) { return null; } String fileSHA1 = null; FileInputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); return null; } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA-1"); byte[] buffer = new byte[IO_BUFFER_SIZE]; int length = 0; while ((length = fis.read(buffer)) > 0) { messageDigest.update(buffer, 0, length); } fis.close(); fileSHA1 = SecurityUtil.bytes2Hex(messageDigest.digest()); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (!TextUtils.isEmpty(fileSHA1)) { fileSHA1 = fileSHA1.trim(); } return fileSHA1; } public static String fileMD5(String absPath) { if (TextUtils.isEmpty(absPath)) { return null; } File file = new File(absPath); if (!file.exists() || file.isDirectory()) { return null; } String fileMD5 = null; FileInputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); return null; } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[IO_BUFFER_SIZE]; int length = 0; while ((length = fis.read(buffer)) > 0) { messageDigest.update(buffer, 0, length); } fis.close(); fileMD5 = SecurityUtil.bytes2Hex(messageDigest.digest()); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (!TextUtils.isEmpty(fileMD5)) { fileMD5 = fileMD5.trim(); } return fileMD5; } public static final boolean write(String absPath, String text) { if (!create(absPath, true)) { return false; } FileOutputStream fos = null; PrintWriter pw = null; try { fos = new FileOutputStream(absPath); pw = new PrintWriter(fos); pw.write(text); pw.flush(); } catch (Exception e) { } finally { CloseUtil.close(pw); CloseUtil.close(fos); } return true; } public static final boolean write(String absPath, InputStream ips) { if (!create(absPath, true)) { return false; } FileOutputStream fos = null; try { fos = new FileOutputStream(absPath); byte buffer[] = new byte[IO_BUFFER_SIZE]; int count = ips.read(buffer); for (; count != -1;) { fos.write(buffer, 0, count); count = ips.read(buffer); } fos.flush(); } catch (Exception e) { // return false; } finally { CloseUtil.close(fos); } return true; } public static final String read(String absPath) { String text = null; InputStream ips = null; try { ips = new FileInputStream(absPath); text = read(ips); } catch (Exception e) { } finally { CloseUtil.close(ips); } return text; } public static final String read(InputStream inputStream) { if (inputStream == null) { return null; } ByteArrayBuffer baf = new ByteArrayBuffer(IO_BUFFER_SIZE); byte buffer[] = new byte[IO_BUFFER_SIZE]; try { int count = inputStream.read(buffer); for (; count != -1;) { baf.append(buffer, 0, count); count = inputStream.read(buffer); } } catch (Exception e) { } String text = new String(baf.toByteArray()); return text; } public static final InputStream getStream(String absPath) { InputStream inputStream = null; try { inputStream = new FileInputStream(absPath); } catch (Exception e) { e.printStackTrace(); } return inputStream; } }
20.852596
76
0.649289
b4dc0acfad2ff79d139388eefb9c50e70c22d199
879
package me.mattstudios.msg.commonmark.node.triumph; import me.mattstudios.msg.commonmark.node.Node; import me.mattstudios.msg.commonmark.node.Visitor; import org.jetbrains.annotations.NotNull; public class Color extends Node { @NotNull private String literal; private final boolean legacy; public Color(@NotNull final String literal) { this(literal, false); } public Color(@NotNull final String literal, final boolean legacy) { this.literal = literal; this.legacy = legacy; } @Override public void accept(@NotNull final Visitor visitor) { visitor.visit(this); } @NotNull public String getColor() { return literal; } public void setLiteral(@NotNull final String literal) { this.literal = literal; } public boolean isLegacy() { return legacy; } }
21.439024
71
0.664391
69bd53d49532ceb440624493852d347d60933a7d
42,495
import java.util.ArrayList; /** * Write a description of class Main here. * * @author (your name) * @version (a version number or a date) */ public class CombatSim{ public static void main(String[] args){ SimSetup setup = new SimSetup(); endSetup(setup); ArrayList<Ship> shipTypeExample = new ArrayList<>(); ArrayList<ArrayList<Ship>> ship = new ArrayList<ArrayList<Ship>>(); ReportHolder reports = new ReportHolder(); for(int i = 0; i < 15; i++){ ship.add(new ArrayList<Ship>()); } shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Emperor-class Star Dreadnought")); shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Imperial Dreadnought Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Executor-class Star Dreadnought")); shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Eclipse-class Star Dreadnought")); shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Viscount-class Star Defender")); shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Sovereign-class Super Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Super Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Trade Federation Battleship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Reborn Sith Battle Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Revenge-class Heavy Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Mediator-class Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Festrian Super Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Allegiance-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Invincible-class Dreadnought")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Republic Class Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Reborn Sith Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Galaforian Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"United Galatic Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Pellaeon-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Imperial-class Star Destroyer Mk1")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Imperial-class Star Destroyer Mk2")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Quantum Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Viceroy-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Legacy-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Raptorian-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"MC90 Star Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Republic-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"MC80a Star Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Imperial Bulk Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Venator-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Trade Federation Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Nebula-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Endurance-class Fleet Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Scythe-class Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Galactic Class Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Harrow-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Shree-class Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Victory-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Bothan Assault Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Munificent-class Star Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Reborn Sith Heavy Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Banking Clan Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Republic Assault Ship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Defender-class Assault Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Shunan Assault Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Assault Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Majestic-class Heavy Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Dragon-class Heavy Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Dreadnought-class Heavy Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Vindicator-class Heavy Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Tartan-class Patrol Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Enforcer-class Patrol Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Immobilizer 418 Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Interdictor-class Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Commerce Guild Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"MC40a Light Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Hammerhead-class Heavy Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Gladiator-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Escort Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Republic Heavy Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Hapan Battle Dragon")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Strike Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Alliance Assault Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Reborn Sith Light Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Hapes Nova-class Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Belarus-class Medium Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Galactic Defense Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Ardent-class Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Sacheen-class Light Escort")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Republic Battle Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Imperial Battle Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Carrack-class Light Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Dogan Support Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Kaloth-class Battle Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Class 1000 Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Star Galleon-class Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Nebulon-B Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Corona-class Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Nebulon-B2 Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Lancer-class Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Armadia-class Thrustship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Bayonet-class Light Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Reborn Sith Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Federation Assault Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Marauder Corvette")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Warrior-class Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Agave-class Picket Ship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Shunan Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Corellian Corvette")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Imperial Assault Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Assassin-class Corvette")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Corellian Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Old Republic Light Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Braha'tok-class Gunship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"Fw'sen-class Picket Ship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"X-Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"Y-Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"A-Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"B-Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"E-Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"K-Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"ARC-170")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"UG Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"UG Interceptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"UG Bomber")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"TIE Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"TIE Interceptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"TIE Bomber")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"TIE Defender")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"TIE Raptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"TIE Phantom")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Reborn Sith Heavy Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Reborn Sith Light Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Reborn Sith Interceptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"Reborn Sith Bomber")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Victory II-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Secutor-class Star Destroyer")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Arquitens-class Light Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Bes'uliik")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Aleph-class Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Eta-2 Actis-class Interceptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Alpha-3 Nimbus-class V-wing Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Delta-7 Aethersprite-class Light Interceptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"A-9 Vigilance Interceptor")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Belbullab-22 Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Droid Tri-Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Z-95 Headhunter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"N-1 Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Vulture-class Droid Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Miy'til Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Nssis-class Clawcraft")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"Hyena-class Bomber")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"CloakShape Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"Miy'til Assault Bomber")); shipTypeExample.add(ShipFactory.makeShip(ShipType.CARRIER,"Quasar Fire-class Bulk Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Fang Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Aurek-class Tactical Strikefighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Rogue-class Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"V-19 Torrent Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"R-41 Starchaser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"StarViper-class Attack Platform")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Rihkxyrk Assault Fighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Ixiyen-class Fast Attack Craft")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"GAT-12 Skipray Blastboat")); shipTypeExample.add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"I-7 Howlrunner")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"VCX-100 Light Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-2400 Light Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-2000 Light Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-1300 Light Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-1250 Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"Stathas-class Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"MC-18 Light Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"Simiyiar-class Light Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"SS-54 Assault Ship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"Stalwart-class Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"RX4 Patrol Ship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"Mynock-class Assault Boat")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"Firespray-31-class Attack Craft")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"Pursuer-class Enforcement Ship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"UT-60D U-wing Starfighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"PB-950 Patrol Boat")); shipTypeExample.add(ShipFactory.makeShip(ShipType.PATROL,"Law-class Light Patrol Craft")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Beta-class ETR-3 Escort Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Delta-class DX-9 Stormtrooper Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Etti Lighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Gamma-class ATR-6 Assault Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"GR-75 Medium Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"ILH-KK Citadel-class Civilian Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Kom'rk-class Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Loronar Medium Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Mobquet Medium Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Seltiss-1 Caravel")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Shaadlar-type Troopship")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"VT-49 Decimator")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Wayfarer-class Medium Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"YZ-775 Medium Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Lambda-class T-4a Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Aegis-class Combat Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Delta-class JV-7 Escort Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Flarestar-class Attack Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Nu-class Attack Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Sentinel-class Landing Craft")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Upsilon-class Command Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Sheathipede-class Transport Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Sigma-class Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Low Altitude Assault Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"BR-23 Courier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Y-4 Raptor-class Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"CR25 Troop Carrier")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FREIGHTER,"YV-865 Aurore-class Freighter")); shipTypeExample.add(ShipFactory.makeShip(ShipType.FRIGATE,"Pelta-class Frigate")); shipTypeExample.add(ShipFactory.makeShip(ShipType.GUNSHIP,"Consular-class Cruiser")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Delta-class T-3c Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Imperial Armored Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Tra'kad-class Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.BOMBER,"Alpha-class Xg-1 Star Wing")); shipTypeExample.add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"TIE Avenger")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Amphibious Interstellar Assault Transport")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Kappa-class Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Grek-class Troop Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.SHUTTLE,"Crix-class Assault Shuttle")); shipTypeExample.add(ShipFactory.makeShip(ShipType.TRANSPORT,"Hardcell-class Interstellar Transport")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Emperor-class Star Dreadnought")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Imperial Dreadnought Cruiser")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Executor-class Star Dreadnought")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Eclipse-class Star Dreadnought")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Viscount-class Star Defender")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Sovereign-class Super Star Destroyer")); ship.get(0).add(ShipFactory.makeShip(ShipType.DREADNOUGHT,"Super Star Destroyer")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Trade Federation Battleship")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Reborn Sith Battle Carrier")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Revenge-class Heavy Carrier")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Mediator-class Battle Cruiser")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Festrian Super Carrier")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Allegiance-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Invincible-class Dreadnought")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Republic Class Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Reborn Sith Battle Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Galaforian Battle Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"United Galatic Battle Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Pellaeon-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Imperial-class Star Destroyer Mk1")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Imperial-class Star Destroyer Mk2")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Quantum Cruiser")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Viceroy-class Star Destroyer")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Legacy-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Raptorian-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"MC90 Star Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Republic-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"MC80a Star Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Imperial Bulk Cruiser")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Venator-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Trade Federation Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Nebula-class Star Destroyer")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Endurance-class Fleet Carrier")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Scythe-class Battle Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Galactic Class Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Harrow-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Shree-class Battle Cruiser")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Victory-class Star Destroyer")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Bothan Assault Cruiser")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Munificent-class Star Frigate")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Reborn Sith Heavy Cruiser")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Banking Clan Cruiser")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Republic Assault Ship")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Defender-class Assault Carrier")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Shunan Assault Destroyer")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Assault Frigate")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Majestic-class Heavy Cruiser")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Dragon-class Heavy Cruiser")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Dreadnought-class Heavy Cruiser")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Vindicator-class Heavy Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Tartan-class Patrol Cruiser")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Enforcer-class Patrol Cruiser")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Immobilizer 418 Cruiser")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Interdictor-class Cruiser")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Commerce Guild Destroyer")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"MC40a Light Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Hammerhead-class Heavy Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Gladiator-class Star Destroyer")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Escort Carrier")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Republic Heavy Destroyer")); ship.get(3).add(ShipFactory.makeShip(ShipType.HEAVYCRUISER,"Hapan Battle Dragon")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Strike Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Alliance Assault Frigate")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Reborn Sith Light Cruiser")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Hapes Nova-class Battle Cruiser")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Belarus-class Medium Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Galactic Defense Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Ardent-class Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Sacheen-class Light Escort")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Republic Battle Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Imperial Battle Frigate")); ship.get(4).add(ShipFactory.makeShip(ShipType.LIGHTCRUISER,"Carrack-class Light Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Dogan Support Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Kaloth-class Battle Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Class 1000 Cruiser")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Star Galleon-class Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Nebulon-B Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Corona-class Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Nebulon-B2 Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Lancer-class Frigate")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Armadia-class Thrustship")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Bayonet-class Light Cruiser")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Reborn Sith Gunship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Federation Assault Gunship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Marauder Corvette")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Warrior-class Gunship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Agave-class Picket Ship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Shunan Gunship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Corellian Corvette")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Imperial Assault Gunship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Assassin-class Corvette")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Corellian Gunship")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Old Republic Light Cruiser")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Braha'tok-class Gunship")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"Fw'sen-class Picket Ship")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"X-Wing")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"Y-Wing")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"A-Wing")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"B-Wing")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"E-Wing")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"K-Wing")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"ARC-170")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"UG Fighter")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"UG Interceptor")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"UG Bomber")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"TIE Fighter")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"TIE Interceptor")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"TIE Bomber")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"TIE Defender")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"TIE Raptor")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"TIE Phantom")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Reborn Sith Heavy Fighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Reborn Sith Light Fighter")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Reborn Sith Interceptor")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"Reborn Sith Bomber")); ship.get(2).add(ShipFactory.makeShip(ShipType.BATTLESHIP,"Victory II-class Star Destroyer")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Secutor-class Star Destroyer")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Arquitens-class Light Cruiser")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Bes'uliik")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Aleph-class Starfighter")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Eta-2 Actis-class Interceptor")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Alpha-3 Nimbus-class V-wing Starfighter")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"Delta-7 Aethersprite-class Light Interceptor")); ship.get(9).add(ShipFactory.makeShip(ShipType.INTERCEPTOR,"A-9 Vigilance Interceptor")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Belbullab-22 Starfighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Droid Tri-Fighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Z-95 Headhunter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"N-1 Starfighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Vulture-class Droid Starfighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Miy'til Starfighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Nssis-class Clawcraft")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"Hyena-class Bomber")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"CloakShape Fighter")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"Miy'til Assault Bomber")); ship.get(1).add(ShipFactory.makeShip(ShipType.CARRIER,"Quasar Fire-class Bulk Cruiser")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Fang Fighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Aurek-class Tactical Strikefighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"Rogue-class Starfighter")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"V-19 Torrent Starfighter")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"R-41 Starchaser")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"StarViper-class Attack Platform")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Rihkxyrk Assault Fighter")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"Ixiyen-class Fast Attack Craft")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"GAT-12 Skipray Blastboat")); ship.get(8).add(ShipFactory.makeShip(ShipType.LIGHTFIGHTER,"I-7 Howlrunner")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"VCX-100 Light Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-2400 Light Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-2000 Light Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-1300 Light Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"YT-1250 Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"Stathas-class Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"MC-18 Light Freighter")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"Simiyiar-class Light Freighter")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"SS-54 Assault Ship")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"Stalwart-class Freighter")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"RX4 Patrol Ship")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"Mynock-class Assault Boat")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"Firespray-31-class Attack Craft")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"Pursuer-class Enforcement Ship")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"UT-60D U-wing Starfighter")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"PB-950 Patrol Boat")); ship.get(12).add(ShipFactory.makeShip(ShipType.PATROL,"Law-class Light Patrol Craft")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Beta-class ETR-3 Escort Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Delta-class DX-9 Stormtrooper Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Etti Lighter")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Gamma-class ATR-6 Assault Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"GR-75 Medium Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"ILH-KK Citadel-class Civilian Cruiser")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Kom'rk-class Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Loronar Medium Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Mobquet Medium Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Seltiss-1 Caravel")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Shaadlar-type Troopship")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"VT-49 Decimator")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Wayfarer-class Medium Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"YZ-775 Medium Transport")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Lambda-class T-4a Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Aegis-class Combat Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Delta-class JV-7 Escort Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Flarestar-class Attack Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Nu-class Attack Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Sentinel-class Landing Craft")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Upsilon-class Command Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Sheathipede-class Transport Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Sigma-class Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Low Altitude Assault Transport")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"BR-23 Courier")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Y-4 Raptor-class Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"CR25 Troop Carrier")); ship.get(11).add(ShipFactory.makeShip(ShipType.FREIGHTER,"YV-865 Aurore-class Freighter")); ship.get(5).add(ShipFactory.makeShip(ShipType.FRIGATE,"Pelta-class Frigate")); ship.get(6).add(ShipFactory.makeShip(ShipType.GUNSHIP,"Consular-class Cruiser")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Delta-class T-3c Shuttle")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Imperial Armored Transport")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Tra'kad-class Transport")); ship.get(10).add(ShipFactory.makeShip(ShipType.BOMBER,"Alpha-class Xg-1 Star Wing")); ship.get(7).add(ShipFactory.makeShip(ShipType.HEAVYFIGHTER,"TIE Avenger")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Amphibious Interstellar Assault Transport")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Kappa-class Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Grek-class Troop Shuttle")); ship.get(14).add(ShipFactory.makeShip(ShipType.SHUTTLE,"Crix-class Assault Shuttle")); ship.get(13).add(ShipFactory.makeShip(ShipType.TRANSPORT,"Hardcell-class Interstellar Transport")); long creditLimit = setup.getCreditLimit(); int roundLimit = setup.getRoundLimit(); Fleet fleet1 = new Fleet(creditLimit, shipTypeExample); Fleet fleet2 = new Fleet(creditLimit, shipTypeExample); FleetCreation f1 = new FleetCreation("Fleet 1", fleet1, ship); endfleetCreate(f1); fleet1.countInitial(); FleetCreation f2 = new FleetCreation("Fleet 2", fleet2, ship); endfleetCreate(f2); fleet2.countInitial(); //CombatSimulation int counter = 0; long startTime = System.currentTimeMillis(); do{ int g1 = fleet1.groundCombat(); int g2 = fleet2.groundCombat(); fleet1.groundDead(g2); fleet2.groundDead(g1); counter++; fleet1.combat(fleet2.getFleet().get(0), counter); fleet2.combat(fleet1.getFleet().get(0), counter); fleet1.repair(); fleet2.repair(); fleet1.collectFleetStats(); fleet2.collectFleetStats(); reports.newReport(counter,fleet1.getTotalTroops(),fleet2.getTotalTroops(),fleet1.getholdCount(),fleet1.getShipType(),fleet1.getDamageCount(),fleet1.getMessages(),fleet2.getholdCount(),fleet2.getShipType(),fleet2.getDamageCount(),fleet2.getMessages()); }while(!fleet1.getFleet().get(0).isEmpty() && !fleet2.getFleet().get(0).isEmpty() && counter < roundLimit); //Declare Winner long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; if(counter == roundLimit){ Winner winner = new Winner(0, counter,totalTime); }else if(fleet1.getFleet().get(0).isEmpty() && !fleet2.getFleet().get(0).isEmpty()){ Winner winner = new Winner(2, counter,totalTime); }else if(!fleet1.getFleet().get(0).isEmpty() && fleet2.getFleet().get(0).isEmpty()){ Winner winner = new Winner(1, counter,totalTime); }else if(fleet1.getFleet().get(0).isEmpty() && fleet2.getFleet().get(0).isEmpty()){ Winner winner = new Winner(0, counter,totalTime); } //Show Fleet Statistics reports.lastVisible(); reports.setFinal(counter - 1); } public static void endSetup(SimSetup setup){ while(!setup.getEnd()){ try{ Thread.sleep(1); }catch(Exception e){ System.out.print(e); } } } public static void endfleetCreate(FleetCreation fleetCreate){ while(!fleetCreate.getEnd()){ try{ Thread.sleep(1); }catch(Exception e){ System.out.print(e); } } } }
85.331325
264
0.726627
a1af5e613d3ab30c60e9d7b8be5d763578cb7582
1,068
package ch03.timers; import ch03.model.ScopeInstance; /** * @author Tom Baeyens */ public class Timer { protected String name; protected ScopeInstance scopeInstance; protected TimerHandler timerHandler; protected String time; protected boolean cancelOnScopeEnd; public ScopeInstance getScopeInstance() { return this.scopeInstance; } public void setScopeInstance(ScopeInstance scopeInstance) { this.scopeInstance = scopeInstance; } public TimerHandler getTimerHandler() { return timerHandler; } public void setTimerHandler(TimerHandler timerHandler) { this.timerHandler = timerHandler; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isCancelOnScopeEnd() { return cancelOnScopeEnd; } public void setCancelOnScopeEnd(boolean cancelOnScopeEnd) { this.cancelOnScopeEnd = cancelOnScopeEnd; } }
19.418182
61
0.71161
5190956014020b5c666da3ced40324af255665e3
463
package demo.sa.order.model; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.List; @Data @Document(collection = "orders") public class OrderEntity { @Id private String orderId; private List<Address> addresses; private Float totalPrice; private String currency; private List<Product> products; private List<OrderItem> orderItems; }
21.045455
62
0.75378
e6635d27546b7a36e088ab8bd345fbb247e87f79
5,002
package javaanpr.recognizer; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.Collections; import java.util.Comparator; import java.util.Vector; import javaanpr.imageanalysis.Char; public abstract class CharacterRecognizer { // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z public static char[] alphabet = { '0','1','2','3','4','5','6','7','8','9','A','B','C', 'D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z' }; public static float[][] features = { {0,1,0,1}, //0 {1,0,1,0}, //1 {0,0,1,1}, //2 {1,1,0,0}, //3 {0,0,0,1}, //4 {1,0,0,0}, //5 {1,1,1,0}, //6 {0,1,1,1}, //7 {0,0,1,0}, //8 {0,1,0,0}, //9 {1,0,1,1}, //10 {1,1,0,1} //11 }; public class RecognizedChar { public class RecognizedPattern { private char chr; private float cost; RecognizedPattern(char chr, float value) { this.chr = chr; this.cost = value; } public char getChar() { return this.chr; } public float getCost() { return this.cost; } } public class PatternComparer implements Comparator { int direction; public PatternComparer(int direction) { this.direction = direction; } public int compare(Object o1, Object o2) { float cost1 = ((RecognizedPattern)o1).getCost(); float cost2 = ((RecognizedPattern)o2).getCost(); int ret = 0; if (cost1 < cost2) ret = -1; if (cost1 > cost2) ret = 1; if (direction==1) ret *= -1; return ret; } } private Vector<RecognizedPattern> patterns; private boolean isSorted; RecognizedChar() { this.patterns = new Vector<RecognizedPattern>(); this.isSorted = false; } public void addPattern(RecognizedPattern pattern) { this.patterns.add(pattern); } public boolean isSorted() { return this.isSorted; } public void sort(int direction) { if (this.isSorted) return; this.isSorted = true; Collections.sort(patterns, (Comparator<? super RecognizedPattern>) new PatternComparer(direction)); } public Vector<RecognizedPattern> getPatterns() { if (this.isSorted) return this.patterns; return null; // if not sorted } public RecognizedPattern getPattern(int i) { if (this.isSorted) return this.patterns.elementAt(i); return null; } public BufferedImage render() { int width=500; int height=200; BufferedImage histogram = new BufferedImage(width+20, height+20, BufferedImage.TYPE_INT_RGB); Graphics2D graphic = histogram.createGraphics(); graphic.setColor(Color.LIGHT_GRAY); Rectangle backRect = new Rectangle(0,0,width+20,height+20); graphic.fill(backRect); graphic.draw(backRect); graphic.setColor(Color.BLACK); int colWidth = width / this.patterns.size(); int left, top; for (int ay = 0; ay <= 100; ay += 10) { int y = 15 + (int)((100 - ay) / 100.0f * (height - 20)); graphic.drawString(new Integer(ay).toString(), 3 , y+11); graphic.drawLine(25,y+5,35,y+5); } graphic.drawLine(35,19,35,height ); graphic.setColor(Color.BLUE); for (int i=0; i<patterns.size(); i++) { left = i * colWidth + 42; top = height - (int)( patterns.elementAt(i).cost * (height - 20)); graphic.drawRect( left, top , colWidth - 2, height - top ); graphic.drawString( patterns.elementAt(i).chr+" " , left + 2, top - 8); } return histogram; } } /** Creates a new instance of CharacterRecognizer */ public CharacterRecognizer() { } public abstract RecognizedChar recognize(Char chr) throws Exception; }
33.797297
114
0.471212
83f96423966dee3c184d85bdfce249a6d1f3aa74
2,872
package com.kneelawk.kfractal.generator.validation; import com.google.common.collect.ImmutableSet; import com.kneelawk.kfractal.generator.api.ir.*; import com.kneelawk.kfractal.generator.api.ir.attribute.IGlobalAttribute; import com.kneelawk.kfractal.generator.api.ir.instruction.Return; import com.kneelawk.kfractal.generator.api.ir.constant.VoidConstant; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; class VariableValidationTests { // TODO: Investigate local "variable" usages @Test void testIllegalVoidVariableType() { Program.Builder program = new Program.Builder(); program.addGlobalVariable("v", GlobalDeclaration.create(ValueTypes.VOID)); assertThrows(IllegalVariableTypeException.class, () -> ProgramValidator.checkValidity(program.build())); } @Test void testIllegalNullFunctionVariableType() { Program.Builder program = new Program.Builder(); program.addGlobalVariable("v", GlobalDeclaration.create(ValueTypes.NULL_FUNCTION)); assertThrows(IllegalVariableTypeException.class, () -> ProgramValidator.checkValidity(program.build())); } @Test void testIllegalNullPointerVariableType() { Program.Builder program = new Program.Builder(); program.addGlobalVariable("v", GlobalDeclaration.create(ValueTypes.NULL_POINTER)); assertThrows(IllegalVariableTypeException.class, () -> ProgramValidator.checkValidity(program.build())); } @ParameterizedTest(name = "testIllegalPreallocatedAnnotation({arguments})") @MethodSource("nonPointerValueTypes") void testIllegalPreallocatedAnnotation(ValueType variableType) { Program.Builder program = new Program.Builder(); program.addGlobalVariable("v", GlobalDeclaration.create(variableType, ImmutableSet.of(IGlobalAttribute.PREALLOCATED))); assertThrows(IllegalVariableAttributeException.class, () -> ProgramValidator.checkValidity(program.build())); } private static Stream<ValueType> nonPointerValueTypes() { return VariableValueTypesProvider.variableValueTypes().filter(v -> !ValueTypes.isPointer(v)); } @ParameterizedTest(name = "testVariableDeclaration({arguments})") @ArgumentsSource(VariableValueTypesProvider.class) void testVariableDeclaration(ValueType variableType) { Program.Builder program = new Program.Builder(); program.addGlobalVariable("v", GlobalDeclaration.create(variableType)); assertDoesNotThrow(() -> ProgramValidator.checkValidity(program.build())); } }
42.235294
117
0.758357
3f02a2d7d715ca723fdff45e2cd9ae233b92fd44
1,863
/* * Copyright (c) 2017 LingoChamp 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.liulishuo.okdownload.core.breakpoint; import androidx.annotation.NonNull; class RemitSyncToDBHelper { private final RemitSyncExecutor executor; long delayMillis; RemitSyncToDBHelper(@NonNull final RemitSyncExecutor.RemitAgent agent) { this(new RemitSyncExecutor(agent)); } RemitSyncToDBHelper(@NonNull final RemitSyncExecutor executor) { this.executor = executor; this.delayMillis = 1500; } void shutdown() { this.executor.shutdown(); } boolean isNotFreeToDatabase(int id) { return !executor.isFreeToDatabase(id); } void onTaskStart(int id) { // discard pending sync if we can executor.removePostWithId(id); executor.postSyncInfoDelay(id, delayMillis); } void endAndEnsureToDB(int id) { executor.removePostWithId(id); try { // already synced if (executor.isFreeToDatabase(id)) return; // force sync for ids executor.postSync(id); } finally { // remove free state executor.postRemoveFreeId(id); } } void discard(int id) { executor.removePostWithId(id); executor.postRemoveInfo(id); } }
26.239437
76
0.661299
82a9ce588bfc2653b2e51e9b1a3e9f19360b2660
1,014
package edu.purdue.comradesgui.src.javafx; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.stage.Stage; public class FXChessOptions extends Application { private FXComradesGUI comradesGUI; public FXChessOptions(FXComradesGUI comradesGUI) { this.comradesGUI = comradesGUI; } public FXComradesGUI getComradesGUI() { return comradesGUI; } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Options"); primaryStage.setResizable(false); TabPane tabPane = new TabPane(); Scene scene = new Scene(tabPane, 450, 550); Tab boardOptionsTab = new FXTabChessBoardOptions(comradesGUI); boardOptionsTab.setText("Board"); tabPane.getTabs().add(boardOptionsTab); Tab engineOptionTab = new FXTabChessEngineOptions(comradesGUI); engineOptionTab.setText("Engines"); tabPane.getTabs().add(engineOptionTab); primaryStage.setScene(scene); primaryStage.show(); } }
23.045455
65
0.776134
3cac4d4ac3b4ac54708ce478af26028edd25a3fe
216
package edu.carleton.COMP2601; /** * Created by haamedsultani (100884545) on 2017-01-24. */ public interface GameObserver { public void update(int[][] model, int gameState, int playerTurn, int cellNumber); }
21.6
85
0.722222
b8d1854f442c7e4e3a35164024394bfc41ab090c
6,970
package com.monezhao.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.monezhao.bean.sys.SysCodeInfo; import com.monezhao.common.Constants; import com.monezhao.common.base.BaseServiceImpl; import com.monezhao.common.exception.SysException; import com.monezhao.common.permission.FilterOperate; import com.monezhao.common.query.QueryWrapperGenerator; import com.monezhao.common.util.CommonUtil; import com.monezhao.common.util.RedisUtil; import com.monezhao.mapper.SysCodeInfoMapper; import com.monezhao.service.SysCodeInfoService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * 代码信息ServiceImpl * * @author [email protected] */ @Service public class SysCodeInfoServiceImpl extends BaseServiceImpl<SysCodeInfoMapper, SysCodeInfo> implements SysCodeInfoService { @Autowired private RedisUtil redisUtil; @Override public IPage<SysCodeInfo> list(IPage<SysCodeInfo> page, SysCodeInfo sysCodeInfo) { return page.setRecords(baseMapper.list(page, sysCodeInfo)); } /** * 加载数据字典进redis * * @param codeTypeIds 数据字典数组,以逗号隔开, 若传空则加载所有数据字典 */ @Override public void loadSysCodeInfoToRedis(String codeTypeIds) { if (CommonUtil.isNotEmptyAfterTrim(codeTypeIds)) { String[] codeTypeIdsArr = codeTypeIds.split(","); for (String codeTypeId : codeTypeIdsArr) { // 先清除 redisUtil.del(Constants.PREFIX_SYS_CODE_TYPE + codeTypeId); } } else { // 先清除 redisUtil.delPattern(Constants.PREFIX_SYS_CODE_TYPE + "*"); } Map<String, List<SysCodeInfo>> codeInfoMap = getSysCodeInfosFromDb(codeTypeIds); for (String codeInfoMapKey : codeInfoMap.keySet()) { redisUtil.set(Constants.PREFIX_SYS_CODE_TYPE + codeInfoMapKey, codeInfoMap.get(codeInfoMapKey)); } } /** * 从数据库查询数据字典 * * @param codeTypeIds 数据字典数组,以逗号隔开, 若传空则加载所有数据字典 * @return */ @Override public Map<String, List<SysCodeInfo>> getSysCodeInfosFromDb(String codeTypeIds) { Map<String, List<SysCodeInfo>> codeInfoMap = new HashMap<>(16); QueryWrapper<SysCodeInfo> queryWrapper = new QueryWrapper<>(); if (CommonUtil.isNotEmptyAfterTrim(codeTypeIds)) { QueryWrapperGenerator.addEasyQuery(queryWrapper, "codeTypeId", FilterOperate.IN, codeTypeIds); } QueryWrapperGenerator.addEasyQuery(queryWrapper, "isOk", FilterOperate.EQ, "1"); queryWrapper.orderByAsc("CODE_TYPE_ID", "SORT_NO"); List<SysCodeInfo> codeInfoList = this.list(queryWrapper); for (SysCodeInfo sysCodeInfo : codeInfoList) { List<SysCodeInfo> subList; if (!codeInfoMap.containsKey(sysCodeInfo.getCodeTypeId())) { subList = new ArrayList<>(); SysCodeInfo emptySysCodeInfo = new SysCodeInfo(); emptySysCodeInfo.setCodeInfoId(""); emptySysCodeInfo.setCodeTypeId(sysCodeInfo.getCodeTypeId()); emptySysCodeInfo.setContent(""); emptySysCodeInfo.setValue(""); emptySysCodeInfo.setSortNo(-999); subList.add(emptySysCodeInfo); } else { subList = codeInfoMap.get(sysCodeInfo.getCodeTypeId()); } subList.add(sysCodeInfo); codeInfoMap.put(sysCodeInfo.getCodeTypeId(), subList); } return codeInfoMap; } /** * 查询数据字典 * * @param codeTypeIds 数据字典数组,以逗号隔开, 若传空则加载所有数据字典 * @return */ @Override @SuppressWarnings("unchecked") public Map<String, List<SysCodeInfo>> getSysCodeInfosFromRedis(String codeTypeIds) { Set<String> keys = null; if (CommonUtil.isNotEmptyAfterTrim(codeTypeIds)) { keys = new HashSet<>(); String[] codeTypeIdsArr = codeTypeIds.split(","); for (String codeTypeId : codeTypeIdsArr) { keys.add(Constants.PREFIX_SYS_CODE_TYPE + codeTypeId); } } else { keys = redisUtil.keysPattern(Constants.PREFIX_SYS_CODE_TYPE + "*"); } Map<String, List<SysCodeInfo>> codeInfoMap = null; if (keys != null && keys.size() > 0) { codeInfoMap = new HashMap<>(16); for (String key : keys) { codeInfoMap.put(key.replace(Constants.PREFIX_SYS_CODE_TYPE, ""), (List<SysCodeInfo>) redisUtil.get(key)); } } return codeInfoMap; } /** * 新增代码信息,并加载进redis缓存 * * @param sysCodeInfo */ @Override @Transactional(rollbackFor = Exception.class) public void saveSysCodeInfo(SysCodeInfo sysCodeInfo) { if (exist(sysCodeInfo)) { throw new SysException("已存在此排序数据"); } this.save(sysCodeInfo); this.loadSysCodeInfoToRedis(sysCodeInfo.getCodeTypeId()); } /** * 修改代码信息,并加载进redis缓存 * * @param sysCodeInfo */ @Override @Transactional(rollbackFor = Exception.class) public void updateSysCodeInfo(SysCodeInfo sysCodeInfo) { if (exist(sysCodeInfo)) { throw new SysException("已存在此排序数据"); } this.updateById(sysCodeInfo); this.loadSysCodeInfoToRedis(sysCodeInfo.getCodeTypeId()); } /** * 是否存在冲突排序号 * @param info info * @return boolean */ public boolean exist(SysCodeInfo info) { QueryWrapper<SysCodeInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda() .eq(SysCodeInfo::getCodeTypeId, info.getCodeTypeId()) .eq(SysCodeInfo::getValue, info.getValue()); if (StringUtils.isNotEmpty(info.getCodeInfoId())) { queryWrapper.lambda() .ne(SysCodeInfo::getCodeInfoId, info.getCodeInfoId()); } List<SysCodeInfo> list = this.list(queryWrapper); return list != null && !list.isEmpty(); } /** * 删除代码信息,并重新加载redis缓存 * * @param ids */ @Override @Transactional(rollbackFor = Exception.class) public void deleteSysCodeInfo(String ids) { if (ids == null || ids.trim().length() == 0) { throw new SysException("ids can't be empty"); } String[] idsArr = ids.split(","); if (idsArr.length > 1) { this.removeByIds(Arrays.asList(idsArr)); } else { this.removeById(idsArr[0]); } this.loadSysCodeInfoToRedis(null); } }
34.50495
108
0.636442
1a64d6964fec2b1bca942fc7f79e1b1377e118e0
736
package shortestpath.util; /** * Represents all cardinal and ordinal directions * * @author Jake */ public enum Direction { UP(0, -1, false), DOWN(0, 1, false), LEFT(-1, 0, false), RIGHT(1, 0, false), UP_RIGHT(1, -1, true), DOWN_RIGHT(1, 1, true), DOWN_LEFT(-1, 1, true), UP_LEFT(-1, -1, true); private final int dx; private final int dy; private final boolean diagonal; private Direction(int dx, int dy, boolean diagonal) { this.dx = dx; this.dy = dy; this.diagonal = diagonal; } public int getDx() { return dx; } public int getDy() { return dy; } public boolean isDiagonal() { return diagonal; } }
17.52381
57
0.561141
0e3cf6ee559e28021d54acf6a63f27ae765b464e
1,995
/** * Hydrogenium * * Copyright (c) 2013 Ean Jee * * @author Ean Jee ([email protected]) */ package hydrogenium.server.console; import hydrogenium.util.InputHandler; import hydrogenium.util.InputListener; import hydrogenium.server.core.ServerCore; public class HydrogeniumServerConsole implements InputListener { private static final int DEFAULT_PORT = 5000; private static final int DEFAULT_FPS = 60; ServerCore server; public HydrogeniumServerConsole(int port, int fps, boolean reset) { InputHandler input = new InputHandler(this); new Thread(input).start(); server = new ServerCore(port, fps, reset); new Thread(server).start(); } public void shutdown() { server.shutdown(); } public boolean isDown() { return server.isDown(); } public void gotLine(String line) { if (line.startsWith("l")) { server.printClientList(); } else if (line.startsWith("p")) { server.pause(); } else if (line.startsWith("r")) { server.resume(); } } private static void printHelpMessage() {} public static void main(String[] args) { int port = DEFAULT_PORT; int fps = DEFAULT_FPS; boolean reset = false; // Collect command line args for (int i = 0; i < args.length; i++) { if (args[i].contains("-framerate")) { fps = Integer.parseInt(args[i].substring(10)); } else if (args[i].contains("-port")) { port = Integer.parseInt(args[i].substring(5)); } else if (args[i].contains("-reset")) { reset = true; } else { printHelpMessage(); } } new HydrogeniumServerConsole(port, fps, reset); } }
22.166667
69
0.534837
f8e9bf5ce23c299c7ae3044c4b2ea32af565d733
1,514
package me.whizvox.wsite.hash; import me.whizvox.wsite.util.Utils; import java.text.MessageFormat; import java.util.Arrays; public class Hash { public byte[] hashedPassword; public byte[] salt; public String compileAsHexString() { byte[] full = new byte[hashedPassword.length + salt.length]; System.arraycopy(hashedPassword, 0, full, 0, hashedPassword.length); System.arraycopy(salt, 0, full, hashedPassword.length, salt.length); return Utils.hexStringFromBytes(full); } @Override public boolean equals(Object o) { if (o instanceof Hash) { Hash other = (Hash) o; return Arrays.equals(hashedPassword, other.hashedPassword) && Arrays.equals(salt, other.salt); } return false; } @Override public String toString() { return compileAsHexString(); } public static Hash fromString(String str, int keyLengthBytes, int saltSize) { if (keyLengthBytes + saltSize != str.length() / 2) { throw new IllegalArgumentException(MessageFormat.format("Hash string ({0}) cannot be parsed with " + "key length of {1,number,#} bytes and salt length of {2,number,#} bytes", str, keyLengthBytes, saltSize)); } byte[] bytes = Utils.bytesFromHexString(str); Hash hash = new Hash(); hash.hashedPassword = new byte[keyLengthBytes]; hash.salt = new byte[saltSize]; System.arraycopy(bytes, 0, hash.hashedPassword, 0, keyLengthBytes); System.arraycopy(bytes, keyLengthBytes, hash.salt, 0, saltSize); return hash; } }
30.897959
116
0.696169
32fd3feacccfcc034519023c134f49609d4bbec6
495
package ru.stqa.pft.sandbox; import org.testng.Assert; import org.testng.annotations.Test; public class EquationsTest { @Test public void test0 () { Equations e = new Equations(1,2,3); Assert.assertEquals(e.rootNumber(),0); } @Test public void test1 () { Equations e = new Equations(1,2,1); Assert.assertEquals(e.rootNumber(),1); } @Test public void test2 () { Equations e = new Equations(1,3,1); Assert.assertEquals(e.rootNumber(),2); } }
14.558824
42
0.646465
1cc2872cd0b0e87df75f37a8e7ea4a67449c06ce
411
package moka.basic.service; /** * Created by moka on 2017/3/6 0006. */ public interface BasicService { <T> T convertBusinessValue(Object resource, Class<T> target, String... ignoreProperties); <T> T convertBusinessValue(Object resource, Object target, String... ignoreProperties); <T> T convertBusinessValueClass(Object resource, Object target, Class<T> zlass, String... ignoreProperties); }
27.4
112
0.73236
3989164eecb292018ae265234e42b1abc4e79bf2
1,294
/* ### * IP: GHIDRA * * 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 agent.frida.manager.evt; import agent.frida.frida.FridaClient; import agent.frida.manager.FridaSession; public class FridaSessionSelectedEvent extends AbstractFridaEvent<String> { private final String id; private FridaSession session; /** * The selected session ID must be specified by Frida. * * @param session Frida-defined session */ public FridaSessionSelectedEvent(FridaSession session) { super(FridaClient.getId(session)); this.session = session; this.id = FridaClient.getId(session); } /** * Get the selected session ID * * @return the session ID */ public String getSessionId() { return id; } public FridaSession getSession() { return session; } }
25.88
75
0.728748
b31a1e48e9c94b0eb67e321a5d46a791aa615bee
1,448
// Displays list of payment options // - credit card, check or cash // Displays fee for using each - 5%, 2% or 0% import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DebugFOurteen2 extends JFrame implements ItemListener { FlowLayout flow = new FlowLayout(); JComboBox<String> payMethod = new JComboBox<String>(); JLabel payList = new JLabel("Pay List"); JTextField totFees = new JTextField(25); String pctMsg = new String("per cent will be added to your bill"); int[] fees = {5, 2, 0}; int feePct = 0; String output; int fee = 0; public DebugFourteen2() { super("Pay List"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(flow) payMethod.addItemLisener(payMethod); add(payList); add(payMethod); payMethod.addItem("Credit card"); payMethod.addItem("Check"); payMethod.addItem("Cash"); add(totFees); } public static void main(String[] arguments) { JFrame cframe = new DebugFourteen2(); cframe.setSize(350,150); cframe.setVisible(true); } @Override public void itemStateChanged() { Object source = list.getSource(); if(source = payMethod) { int fee = payMethod.getSelectedIndex(); feePct = fees[x]; output = feePct + " " + pctMsg; totFees.setText(output); } } }
28.392157
70
0.607735
6033797dc0f679413a204fc4c9aa86730be2f712
1,352
package br.com.cesarcastro.pulsemkt.model; import com.google.gson.annotations.Expose; public class Address { @Expose private Integer addressId; @Expose private String address; @Expose private String number; @Expose private String complement; @Expose private String city; @Expose private String state; public Address() {} public Address(Integer addressId, String address, String number, String complement, String city, String state) { this.addressId = addressId; this.address = address; this.number = number; this.complement = complement; this.city = city; this.state = state; } public void setAddressId(Integer addressId) { this.addressId = addressId; } public void setAddress(String address) { this.address = address; } public void setNumber(String number) { this.number = number; } public void setComplement(String complement) { this.complement = complement; } public void setCity(String city) { this.city = city; } public void setState(String state) { this.state = state; } public Integer getAddressId() { return addressId; } public String getAddress() { return address; } public String getNumber() { return number; } public String getComplement() { return complement; } public String getCity() { return city; } public String getState() { return state; } }
18.026667
113
0.715976
d2e2cafe2d8cb6a47c57b19a3aad3e551be250a5
29,637
package org.folio.service.orders.flows.open; import io.vertx.core.json.JsonObject; import one.util.streamex.StreamEx; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.folio.completablefuture.FolioVertxCompletableFuture; import org.folio.orders.events.handlers.MessageAddress; import org.folio.orders.utils.FundDistributionUtils; import org.folio.orders.utils.HelperUtils; import org.folio.orders.utils.PoLineCommonUtil; import org.folio.orders.utils.ProtectedOperationType; import org.folio.orders.utils.validators.CompositePoLineValidationUtil; import org.folio.orders.utils.validators.OngoingOrderValidator; import org.folio.rest.core.exceptions.HttpException; import org.folio.rest.core.exceptions.InventoryException; import org.folio.rest.core.models.RequestContext; import org.folio.rest.jaxrs.model.Alert; import org.folio.rest.jaxrs.model.CompositePoLine; import org.folio.rest.jaxrs.model.CompositePurchaseOrder; import org.folio.rest.jaxrs.model.Error; import org.folio.rest.jaxrs.model.Location; import org.folio.rest.jaxrs.model.Piece; import org.folio.rest.jaxrs.model.PoLine; import org.folio.rest.jaxrs.model.ReportingCode; import org.folio.rest.jaxrs.model.Title; import org.folio.service.ProtectionService; import org.folio.service.finance.expenceclass.ExpenseClassValidationService; import org.folio.service.finance.transaction.EncumbranceWorkflowStrategy; import org.folio.service.finance.transaction.EncumbranceWorkflowStrategyFactory; import org.folio.service.inventory.InventoryManager; import org.folio.service.orders.OrderWorkflowType; import org.folio.service.orders.PurchaseOrderLineService; import org.folio.service.orders.PurchaseOrderService; import org.folio.service.pieces.PieceChangeReceiptStatusPublisher; import org.folio.service.pieces.PieceStorageService; import org.folio.service.titles.TitlesService; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.stream.Collectors; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.summingInt; import static java.util.stream.Collectors.toList; import static org.folio.orders.utils.HelperUtils.calculateInventoryItemsQuantity; import static org.folio.orders.utils.HelperUtils.calculatePiecesQuantityWithoutLocation; import static org.folio.orders.utils.HelperUtils.collectResultsOnSuccess; import static org.folio.orders.utils.PoLineCommonUtil.groupLocationsByHoldingId; import static org.folio.orders.utils.PoLineCommonUtil.groupLocationsByLocationId; import static org.folio.orders.utils.ResourcePathResolver.ALERTS; import static org.folio.orders.utils.ResourcePathResolver.REPORTING_CODES; import static org.folio.rest.jaxrs.model.CompositePurchaseOrder.WorkflowStatus.OPEN; import static org.folio.rest.jaxrs.model.CompositePurchaseOrder.WorkflowStatus.PENDING; public class OpenCompositeOrderManager { private static final Logger logger = LogManager.getLogger(OpenCompositeOrderManager.class); private final PurchaseOrderService purchaseOrderService; private final PurchaseOrderLineService purchaseOrderLineService; private final EncumbranceWorkflowStrategyFactory encumbranceWorkflowStrategyFactory; private final InventoryManager inventoryManager; private final PieceStorageService pieceStorageService; private final ProtectionService protectionService; private final PieceChangeReceiptStatusPublisher receiptStatusPublisher; private final ExpenseClassValidationService expenseClassValidationService; private final TitlesService titlesService; private final OpenCompositeOrderInventoryService openCompositeOrderInventoryService; public OpenCompositeOrderManager(PurchaseOrderLineService purchaseOrderLineService, EncumbranceWorkflowStrategyFactory encumbranceWorkflowStrategyFactory, InventoryManager inventoryManager, PieceStorageService pieceStorageService, PurchaseOrderService purchaseOrderService, ProtectionService protectionService, PieceChangeReceiptStatusPublisher receiptStatusPublisher, ExpenseClassValidationService expenseClassValidationService, TitlesService titlesService, OpenCompositeOrderInventoryService openCompositeOrderInventoryService) { this.purchaseOrderLineService = purchaseOrderLineService; this.encumbranceWorkflowStrategyFactory = encumbranceWorkflowStrategyFactory; this.inventoryManager = inventoryManager; this.pieceStorageService = pieceStorageService; this.purchaseOrderService = purchaseOrderService; this.protectionService = protectionService; this.receiptStatusPublisher = receiptStatusPublisher; this.expenseClassValidationService = expenseClassValidationService; this.titlesService = titlesService; this.openCompositeOrderInventoryService = openCompositeOrderInventoryService; } /** * Handles transition of given order to OPEN status. * * @param compPO Purchase Order to open * @return CompletableFuture that indicates when transition is completed */ public CompletableFuture<Void> process(CompositePurchaseOrder compPO, CompositePurchaseOrder poFromStorage, RequestContext requestContext) { compPO.setWorkflowStatus(OPEN); compPO.setDateOrdered(new Date()); EncumbranceWorkflowStrategy strategy = encumbranceWorkflowStrategyFactory.getStrategy(OrderWorkflowType.PENDING_TO_OPEN); return expenseClassValidationService.validateExpenseClasses(compPO.getCompositePoLines(), requestContext) .thenAccept(v -> FundDistributionUtils.validateFundDistributionTotal(compPO.getCompositePoLines())) .thenAccept(v -> OngoingOrderValidator.validate(compPO)) .thenCompose(v -> strategy.prepareProcessEncumbrancesAndValidate(compPO, poFromStorage, requestContext)) .thenApply(v -> this.validateMaterialTypes(compPO)) .thenCompose(aCompPO -> titlesService.fetchNonPackageTitles(compPO, requestContext)) .thenCompose(linesIdTitles -> { populateInstanceId(linesIdTitles, compPO.getCompositePoLines()); return processInventory(linesIdTitles, compPO, requestContext); }) .thenCompose(v -> finishProcessingEncumbrancesForOpenOrder(strategy, compPO, poFromStorage, requestContext)) .thenAccept(ok -> changePoLineStatuses(compPO)) .thenCompose(ok -> openOrderUpdatePoLinesSummary(compPO.getCompositePoLines(), requestContext)); } public CompletableFuture<Void> openOrderUpdatePoLinesSummary(List<CompositePoLine> compositePoLines, RequestContext requestContext) { return CompletableFuture.allOf( compositePoLines.stream() .map(this::openOrderRemoveLocationId) .map(this::openOrderConvertToPoLine) .map(line -> purchaseOrderLineService.saveOrderLine(line, requestContext)) .toArray(CompletableFuture[]::new)); } public PoLine openOrderConvertToPoLine(CompositePoLine compPoLine) { JsonObject pol = JsonObject.mapFrom(compPoLine); pol.remove(ALERTS); pol.remove(REPORTING_CODES); PoLine poLine = pol.mapTo(PoLine.class); poLine.setAlerts(compPoLine.getAlerts().stream().map(Alert::getId).collect(toList())); poLine.setReportingCodes(compPoLine.getReportingCodes().stream().map(ReportingCode::getId).collect(toList())); return poLine; } /** * Creates Inventory records associated with given PO line and updates PO line with corresponding links. * * @param compPOL Composite PO line to update Inventory for * @return CompletableFuture with void. */ public CompletableFuture<Void> openOrderUpdateInventory(CompositePoLine compPOL, String titleId, RequestContext requestContext) { if (Boolean.TRUE.equals(compPOL.getIsPackage())) { return completedFuture(null); } if (PoLineCommonUtil.isInventoryUpdateNotRequired(compPOL)) { // don't create pieces, if no inventory updates and receiving not required if (PoLineCommonUtil.isReceiptNotRequired(compPOL.getReceiptStatus())) { return completedFuture(null); } return openOrderCreatePieces(compPOL, titleId, Collections.emptyList(), true, requestContext).thenRun( () -> logger.info("Create pieces for PO Line with '{}' id where inventory updates are not required", compPOL.getId())); } return inventoryManager.handleInstanceRecord(compPOL, requestContext) .thenCompose(compPOLWithInstanceId -> inventoryManager.handleHoldingsAndItemsRecords(compPOLWithInstanceId, requestContext)) .thenCompose(piecesWithItemId -> { if (PoLineCommonUtil.isReceiptNotRequired(compPOL.getReceiptStatus())) { return completedFuture(null); } //create pieces only if receiving is required return openOrderCreatePieces(compPOL, titleId, piecesWithItemId, true, requestContext); }); } /** * Creates pieces that are not yet in storage * * @param compPOL PO line to create Pieces Records for * @param expectedPiecesWithItem expected Pieces to create with created associated Items records * @return void future */ public CompletableFuture<Void> openOrderCreatePieces(CompositePoLine compPOL, String titleId, List<Piece> expectedPiecesWithItem, boolean isOpenOrderFlow, RequestContext requestContext) { int createdItemsQuantity = expectedPiecesWithItem.size(); // do not create pieces in case of check-in flow if (compPOL.getCheckinItems() != null && compPOL.getCheckinItems()) { return completedFuture(null); } logger.info("Get pieces by poLine ID"); return pieceStorageService.getPiecesByPoLineId(compPOL, requestContext) .thenCompose(existingPieces -> { List<Piece> piecesToCreate; List<Piece> piecesWithLocationToProcess = createPiecesByLocationId(compPOL, expectedPiecesWithItem, existingPieces); List<Piece> piecesWithHoldingToProcess = createPiecesByHoldingId(compPOL, expectedPiecesWithItem, existingPieces); List<Piece> onlyLocationChangedPieces = getPiecesWithChangedLocation(compPOL, piecesWithLocationToProcess, existingPieces); if ((onlyLocationChangedPieces.size() == piecesWithLocationToProcess.size()) && !isOpenOrderFlow) { return FolioVertxCompletableFuture.allOf(requestContext.getContext(), onlyLocationChangedPieces.stream() .map(piece -> openOrderUpdatePieceRecord(piece, requestContext)).toArray(CompletableFuture[]::new)); } else { piecesToCreate = new ArrayList<>(piecesWithLocationToProcess); piecesToCreate.addAll(piecesWithHoldingToProcess); } piecesToCreate.addAll(createPiecesWithoutLocationId(compPOL, existingPieces)); piecesToCreate.forEach(piece -> piece.setTitleId(titleId)); logger.info("Trying to create pieces"); List<CompletableFuture<Piece>> piecesToCreateFutures = new ArrayList<>(); piecesToCreate.forEach(piece -> piecesToCreateFutures.add(openOrderCreatePiece(piece, requestContext)) ); return collectResultsOnSuccess(piecesToCreateFutures) .thenAccept(result -> logger.info("Number of created pieces: " + result.size())) .exceptionally(th -> { logger.error("Piece creation error"); return null; }); }) .thenAccept(v -> validateItemsCreation(compPOL, createdItemsQuantity)); } public CompletableFuture<Piece> openOrderCreatePiece(Piece piece, RequestContext requestContext) { logger.info("createPiece start"); return purchaseOrderService.getCompositeOrderByPoLineId(piece.getPoLineId(), requestContext) .thenCompose(order -> protectionService.isOperationRestricted(order.getAcqUnitIds(), ProtectedOperationType.CREATE, requestContext) .thenApply(v -> order)) .thenCompose(order -> openOrderUpdateInventory(order.getCompositePoLines().get(0), piece, requestContext)) .thenCompose(v -> pieceStorageService.insertPiece(piece, requestContext)); } /** * Creates Inventory records associated with given PO line and updates PO line with corresponding links. * * @param compPOL Composite PO line to update Inventory for * @return CompletableFuture with void. */ public CompletableFuture<Void> openOrderUpdateInventory(CompositePoLine compPOL, Piece piece, RequestContext requestContext) { if (Boolean.TRUE.equals(compPOL.getIsPackage())) { return titlesService.getTitleById(piece.getTitleId(), requestContext) .thenCompose(title -> inventoryManager.handleInstanceRecord(title, requestContext)) .thenCompose(title -> titlesService.saveTitle(title, requestContext).thenApply(json -> title)) .thenCompose(title -> { if (piece.getHoldingId() != null) { return completedFuture(piece.getHoldingId()); } return openCompositeOrderInventoryService.handleHoldingsRecord(compPOL, new Location().withLocationId(piece.getLocationId()), title.getInstanceId(), requestContext) .thenApply(holdingId -> { piece.setLocationId(null); piece.setHoldingId(holdingId); return holdingId; }); }) .thenCompose(holdingId -> openCompositeOrderInventoryService.createItemRecord(compPOL, holdingId, requestContext)) .thenAccept(itemId -> Optional.ofNullable(itemId).ifPresent(piece::withItemId)); } else { return inventoryManager.updateItemWithPoLineId(piece.getItemId(), piece.getPoLineId(), requestContext); } } // Flow to update piece // 1. Before update, get piece by id from storage and store receiving status // 2. Update piece with new content and complete future // 3. Create a message and check if receivingStatus is not consistent with storage; if yes - send a message to event bus public CompletableFuture<Void> openOrderUpdatePieceRecord(Piece piece, RequestContext requestContext) { CompletableFuture<Void> future = new CompletableFuture<>(); purchaseOrderService.getCompositeOrderByPoLineId(piece.getPoLineId(), requestContext) .thenCompose(order -> protectionService.isOperationRestricted(order.getAcqUnitIds(), ProtectedOperationType.UPDATE, requestContext)) .thenCompose(v -> inventoryManager.updateItemWithPoLineId(piece.getItemId(), piece.getPoLineId(), requestContext)) .thenAccept(vVoid -> pieceStorageService.getPieceById(piece.getId(), requestContext).thenAccept(pieceStorage -> { Piece.ReceivingStatus receivingStatusStorage = pieceStorage.getReceivingStatus(); pieceStorageService.updatePiece(piece, requestContext) .thenAccept(future::complete) .thenAccept(afterUpdate -> { JsonObject messageToEventBus = new JsonObject(); messageToEventBus.put("poLineIdUpdate", piece.getPoLineId()); Piece.ReceivingStatus receivingStatusUpdate = piece.getReceivingStatus(); logger.debug("receivingStatusStorage -- {}", receivingStatusStorage); logger.debug("receivingStatusUpdate -- {}", receivingStatusUpdate); if (receivingStatusStorage.compareTo(receivingStatusUpdate) != 0) { receiptStatusPublisher.sendEvent(MessageAddress.RECEIPT_STATUS, messageToEventBus, requestContext); } }) .exceptionally(e -> { logger.error("Error updating piece by id to storage {}", piece.getId(), e); future.completeExceptionally(e); return null; }); }) .exceptionally(e -> { logger.error("Error getting piece by id from storage {}", piece.getId(), e); future.completeExceptionally(e); return null; }) ) .exceptionally(t -> { logger.error("User to update piece with id={}", piece.getId(), t.getCause()); future.completeExceptionally(t); return null; }); return future; } public List<Piece> createPiecesByLocationId(CompositePoLine compPOL, List<Piece> expectedPiecesWithItem, List<Piece> existingPieces) { List<Piece> piecesToCreate = new ArrayList<>(); // For each location collect pieces that need to be created. groupLocationsByLocationId(compPOL) .forEach((existingPieceLocationId, existingPieceLocations) -> { List<Piece> filteredExistingPieces = filterByLocationId(existingPieces, existingPieceLocationId); List<Piece> createdPiecesWithItem = processPiecesWithLocationAndItem(expectedPiecesWithItem, filteredExistingPieces, existingPieceLocationId); piecesToCreate.addAll(createdPiecesWithItem); List<Piece> piecesWithoutItem = processPiecesWithoutItemAndLocationId(compPOL, filteredExistingPieces, existingPieceLocationId, existingPieceLocations); piecesToCreate.addAll(piecesWithoutItem); }); return piecesToCreate; } public List<Piece> getPiecesWithChangedLocation(CompositePoLine compPOL, List<Piece> needProcessPieces, List<Piece> existingPieces) { Map<String, Map<Piece.Format, Integer>> existingPieceMap = numOfPiecesByFormatAndLocationId(existingPieces, compPOL.getId()); Map<String, Map<Piece.Format, Integer>> needProcessPiecesMap = numOfPiecesByFormatAndLocationId(needProcessPieces, compPOL.getId()); List<Piece> piecesForLocationUpdate = new ArrayList<>(); for (Map.Entry<String, Map<Piece.Format, Integer>> entry : existingPieceMap.entrySet()) { String existingPieceLocationId = entry.getKey(); Map<Piece.Format, Integer> existingPieceQtyMap = entry.getValue(); for (Map.Entry<Piece.Format, Integer> existPieceFormatQty : existingPieceQtyMap.entrySet()) { Map<Piece.Format, Integer> pieceLocationMap = needProcessPiecesMap.get(existingPieceLocationId); if (pieceLocationMap == null) { needProcessPiecesMap.forEach((newLocationId, value) -> { Integer pieceQty = value.get(existPieceFormatQty.getKey()); if (pieceQty != null && pieceQty.equals(existPieceFormatQty.getValue())) { List<Piece> piecesWithUpdatedLocation = existingPieces.stream() .filter(piece -> existingPieceLocationId.equals(piece.getLocationId()) && existPieceFormatQty.getKey() == piece.getFormat()) .map(piece -> piece.withLocationId(newLocationId)) .collect(Collectors.toList()); piecesForLocationUpdate.addAll(piecesWithUpdatedLocation); } }); } } } return piecesForLocationUpdate; } public List<Piece> createPiecesWithoutLocationId(CompositePoLine compPOL, List<Piece> existingPieces) { List<Piece> piecesToCreate = new ArrayList<>(); Map<Piece.Format, Integer> expectedQuantitiesWithoutLocation = calculatePiecesQuantityWithoutLocation(compPOL); Map<Piece.Format, Integer> existingPiecesQuantities = calculateQuantityOfExistingPiecesWithoutLocation(existingPieces); expectedQuantitiesWithoutLocation.forEach((format, expectedQty) -> { int remainingPiecesQuantity = expectedQty - existingPiecesQuantities.getOrDefault(format, 0); if (remainingPiecesQuantity > 0) { for (int i = 0; i < remainingPiecesQuantity; i++) { piecesToCreate.add(new Piece().withFormat(format).withPoLineId(compPOL.getId())); } } }); return piecesToCreate; } public static Map<String, Map<Piece.Format, Integer>> numOfPiecesByFormatAndLocationId(List<Piece> pieces, String poLineId) { return pieces.stream() .filter(piece -> Objects.nonNull(piece.getPoLineId()) && Objects.nonNull(piece.getLocationId()) && piece.getPoLineId().equals(poLineId)) .collect(groupingBy(Piece::getLocationId, groupingBy(Piece::getFormat, summingInt(q -> 1)))); } private Map<Piece.Format, Integer> calculateQuantityOfExistingPiecesWithoutItem(List<Piece> pieces) { return StreamEx.of(pieces) .filter(piece -> StringUtils.isEmpty(piece.getItemId())) .groupingBy(Piece::getFormat, collectingAndThen(toList(), List::size)); } private Map<Piece.Format, Integer> calculateQuantityOfExistingPiecesWithoutLocation(List<Piece> pieces) { return StreamEx.of(pieces) .filter(piece -> StringUtils.isEmpty(piece.getLocationId())) .groupingBy(Piece::getFormat, collectingAndThen(toList(), List::size)); } private List<Piece> filterByLocationId(List<Piece> pieces, String locationId) { return pieces.stream() .filter(piece -> locationId.equals(piece.getLocationId())) .collect(Collectors.toList()); } private List<Piece> filterByHoldingId(List<Piece> pieces, String holdingId) { return pieces.stream() .filter(piece -> holdingId.equals(piece.getHoldingId())) .collect(Collectors.toList()); } private CompositePurchaseOrder validateMaterialTypes(CompositePurchaseOrder purchaseOrder){ if (purchaseOrder.getWorkflowStatus() != PENDING) { List<Error> errors = CompositePoLineValidationUtil.checkMaterialsAvailability(purchaseOrder.getCompositePoLines()); if (!errors.isEmpty()) { throw new HttpException(422, errors.get(0)); } } return purchaseOrder; } private void validateItemsCreation(CompositePoLine compPOL, int itemsSize) { int expectedItemsQuantity = calculateInventoryItemsQuantity(compPOL); if (itemsSize != expectedItemsQuantity) { String message = String.format("Error creating items for PO Line with '%s' id. Expected %d but %d created", compPOL.getId(), expectedItemsQuantity, itemsSize); throw new InventoryException(message); } } private CompletableFuture<Void> processInventory(Map<String, List<Title>> lineIdsTitles, CompositePurchaseOrder compPO, RequestContext requestContext) { return FolioVertxCompletableFuture.allOf(requestContext.getContext(), compPO.getCompositePoLines() .stream() .map(poLine -> openOrderUpdateInventory(poLine, getFirstTitleIdIfExist(lineIdsTitles, poLine), requestContext)) .toArray(CompletableFuture[]::new) ); } private String getFirstTitleIdIfExist(Map<String, List<Title>> lineIdsTitles, CompositePoLine poLine) { return Optional.ofNullable(lineIdsTitles.get(poLine.getId())) .map(titles -> titles.get(0)) .map(Title::getId) .orElse(null); } private List<Piece> createPiecesByHoldingId(CompositePoLine compPOL, List<Piece> expectedPiecesWithItem, List<Piece> existingPieces) { List<Piece> piecesToCreate = new ArrayList<>(); // For each location collect pieces that need to be created. groupLocationsByHoldingId(compPOL) .forEach((existingPieceHoldingId, existingPieceLocations) -> { List<Piece> filteredExistingPieces = filterByHoldingId(existingPieces, existingPieceHoldingId); List<Piece> createdPiecesWithItem = processPiecesWithHoldingAndItem(expectedPiecesWithItem, filteredExistingPieces, existingPieceHoldingId); piecesToCreate.addAll(createdPiecesWithItem); List<Piece> piecesWithoutItem = processPiecesWithoutItemAndHoldingId(compPOL, filteredExistingPieces, existingPieceHoldingId, existingPieceLocations); piecesToCreate.addAll(piecesWithoutItem); }); return piecesToCreate; } private List<Piece> processPiecesWithoutItemAndLocationId(CompositePoLine compPOL, List<Piece> existedPieces, String existingPieceLocationId, List<Location> existingPieceLocations) { List<Piece> piecesToCreate = new ArrayList<>(); Map<Piece.Format, Integer> expectedQuantitiesWithoutItem = HelperUtils.calculatePiecesWithoutItemIdQuantity(compPOL, existingPieceLocations); Map<Piece.Format, Integer> existedQuantityWithoutItem = calculateQuantityOfExistingPiecesWithoutItem(existedPieces); expectedQuantitiesWithoutItem.forEach((format, expectedQty) -> { int remainingPiecesQuantity = expectedQty - existedQuantityWithoutItem.getOrDefault(format, 0); if (remainingPiecesQuantity > 0) { for (int i = 0; i < remainingPiecesQuantity; i++) { piecesToCreate.add(new Piece().withFormat(format).withLocationId(existingPieceLocationId).withPoLineId(compPOL.getId())); } } }); return piecesToCreate; } private List<Piece> processPiecesWithoutItemAndHoldingId(CompositePoLine compPOL, List<Piece> existedPieces, String existingPieceHoldingId, List<Location> existingPieceLocations) { List<Piece> piecesToCreate = new ArrayList<>(); Map<Piece.Format, Integer> expectedQuantitiesWithoutItem = HelperUtils.calculatePiecesWithoutItemIdQuantity(compPOL, existingPieceLocations); Map<Piece.Format, Integer> existedQuantityWithoutItem = calculateQuantityOfExistingPiecesWithoutItem(existedPieces); expectedQuantitiesWithoutItem.forEach((format, expectedQty) -> { int remainingPiecesQuantity = expectedQty - existedQuantityWithoutItem.getOrDefault(format, 0); if (remainingPiecesQuantity > 0) { for (int i = 0; i < remainingPiecesQuantity; i++) { piecesToCreate.add(new Piece().withFormat(format).withHoldingId(existingPieceHoldingId).withPoLineId(compPOL.getId())); } } }); return piecesToCreate; } private List<Piece> processPiecesWithLocationAndItem(List<Piece> piecesWithItem, List<Piece> existedPieces, String existingPieceLocationId) { List<Piece> expectedPiecesWithItem = filterByLocationId(piecesWithItem, existingPieceLocationId); return collectMissingPiecesWithItem(expectedPiecesWithItem, existedPieces); } private List<Piece> processPiecesWithHoldingAndItem(List<Piece> piecesWithItem, List<Piece> existedPieces, String existingPieceLocationId) { List<Piece> expectedPiecesWithItem = filterByHoldingId(piecesWithItem, existingPieceLocationId); return collectMissingPiecesWithItem(expectedPiecesWithItem, existedPieces); } /** * Find pieces for which created items, but which are not yet in the storage. * * @param piecesWithItem pieces for which created items * @param existingPieces pieces from storage * @return List of Pieces with itemId that are not in storage. */ private List<Piece> collectMissingPiecesWithItem(List<Piece> piecesWithItem, List<Piece> existingPieces) { return piecesWithItem.stream() .filter(pieceWithItem -> existingPieces.stream() .noneMatch(existingPiece -> pieceWithItem.getItemId().equals(existingPiece.getItemId()))) .collect(Collectors.toList()); } private CompositePoLine openOrderRemoveLocationId(CompositePoLine compositePoLine) { compositePoLine.getLocations().forEach(location -> { if (location.getHoldingId() != null) { location.setLocationId(null); } }); return compositePoLine; } private void populateInstanceId(Map<String, List<Title>> lineIdsTitles, List<CompositePoLine> lines) { getNonPackageLines(lines).forEach(line -> { if (lineIdsTitles.containsKey(line.getId())) { line.setInstanceId(lineIdsTitles.get(line.getId()).get(0).getInstanceId()); } }); } private void changePoLineStatuses(CompositePurchaseOrder compPO) { compPO.getCompositePoLines().forEach(poLine -> { changeReceiptStatus(compPO, poLine); changePaymentStatus(compPO, poLine); }); } private void changePaymentStatus(CompositePurchaseOrder compPO, CompositePoLine poLine) { if (compPO.getOrderType().equals(CompositePurchaseOrder.OrderType.ONGOING)) { poLine.setPaymentStatus(CompositePoLine.PaymentStatus.ONGOING); } else if (poLine.getPaymentStatus() == CompositePoLine.PaymentStatus.PENDING) { poLine.setPaymentStatus(CompositePoLine.PaymentStatus.AWAITING_PAYMENT); } } private void changeReceiptStatus(CompositePurchaseOrder compPO, CompositePoLine poLine) { if (compPO.getOrderType().equals(CompositePurchaseOrder.OrderType.ONGOING)) { poLine.setReceiptStatus(CompositePoLine.ReceiptStatus.ONGOING); } else if (poLine.getReceiptStatus() == CompositePoLine.ReceiptStatus.PENDING) { poLine.setReceiptStatus(CompositePoLine.ReceiptStatus.AWAITING_RECEIPT); } } private List<CompositePoLine> getNonPackageLines(List<CompositePoLine> compositePoLines) { return compositePoLines.stream().filter(line -> !line.getIsPackage()).collect(toList()); } private CompletableFuture<Void> finishProcessingEncumbrancesForOpenOrder(EncumbranceWorkflowStrategy strategy, CompositePurchaseOrder compPO, CompositePurchaseOrder poFromStorage, RequestContext requestContext) { return strategy.processEncumbrances(compPO, poFromStorage, requestContext) .handle((v, t) -> { if (t == null) return CompletableFuture.completedFuture(v); // There was an error when processing the encumbrances despite the previous validations. // Order lines should be saved to avoid leaving an open order with locationId instead of holdingId. return openOrderUpdatePoLinesSummary(compPO.getCompositePoLines(), requestContext) .handle((vv, tt) -> { throw new CompletionException(t.getCause()); }); }) .thenCompose(v -> v) // wait for future returned by handle .thenApply(v -> null); } }
51.994737
184
0.752843
fb7c655df7da6a9bb1d30e06d472e88a34a2937b
4,348
package com.example.plenti_full; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.plenti_full.Javabeans.Favorite; import com.example.plenti_full.Javabeans.Recipe; import java.util.ArrayList; /** @author Ocbick * * CRUD OPERATIONS * */ public class DatabaseHandler extends SQLiteOpenHelper { /* Database Version */ public static final int DATABASE_VERSION = 1; /* Database Name */ public static final String DATABASE_NAME = "recipedb"; /* Table Names */ public static final String TABLE_RECIPES = "recipes"; public static final String TABLE_FAVORITES = "favorites"; /* Column Names */ public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_IMAGE = "image"; /* CREATE TABLE STATEMENT */ public static final String CREATE_RECIPE_TABLE = "CREATE TABLE " + TABLE_RECIPES + " (" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT," + COLUMN_IMAGE + " TEXT)"; public static final String CREATE_FAVORITES_TABLE = "CREATE TABLE " + TABLE_FAVORITES + " (" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT," + COLUMN_IMAGE + " TEXT)"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_RECIPE_TABLE); db.execSQL(CREATE_FAVORITES_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } /* INSERT RECORDS */ public void addRecipe(Recipe recipe){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_NAME, recipe.getName()); values.put(COLUMN_IMAGE, recipe.getImage()); db.insert(TABLE_RECIPES, null, values); db.close(); } public void addFavorite(Favorite favorite){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_NAME, favorite.getName()); values.put(COLUMN_IMAGE, favorite.getImage()); db.insert(TABLE_FAVORITES, null, values); db.close(); } public void UpdateRecipes(ArrayList<Recipe> Recipes) { deleteAllRecipes(); for (Recipe recipe: Recipes ) { addRecipe(recipe); } } /* RETRIEVE RECORDS */ public ArrayList<Recipe> getAllRecipes(){ SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_RECIPES , null); ArrayList<Recipe> recipes = new ArrayList<>(); while(cursor.moveToNext()) { recipes.add(new Recipe( cursor.getString(1), cursor.getString(2))); } db.close(); return recipes; } public ArrayList<Favorite> getAllFavorites(){ SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVORITES , null); ArrayList<Favorite> favorites = new ArrayList<>(); while(cursor.moveToNext()) { favorites.add(new Favorite( cursor.getString(1), cursor.getString(2))); } db.close(); return favorites; } /* UPDATE RECORDS */ /* DELETE RECORDS */ public void deleteFavorite(String favorite){ SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_FAVORITES, COLUMN_NAME + " = ?", new String[]{favorite}); db.close(); } public void deleteAllRecipes() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("delete from "+ TABLE_RECIPES); } public void deleteAllFavorites() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("delete from "+ TABLE_FAVORITES); } }
24.022099
78
0.613155
629ada7af13b2e5999ad17c59ea22346677d2479
101
/** * View Models used by Spring MVC REST controllers. */ package msb.shortcut.master.web.rest.vm;
20.2
51
0.722772
6225c5c457861b9a5bf8c45cd6294362970b8b8c
2,352
package com.qianyuan.casedetail.utils; import android.app.DownloadManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import com.lzy.okgo.OkGo; import com.qianyuan.casedetail.application.MyApplication; import com.qianyuan.casedetail.bean.Url; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.io.File; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import okhttp3.Call; import okhttp3.Response; import static android.R.attr.id; /** * Created by sun on 2017/4/26. */ public class DownLoadImgUtil { //获取网络图片并保存到sd //参一:url,参二:保存文件名称,参三:保存文件路径 public static void downLoadImg(final String path, final String imageName, final String folderName) { Runnable runnable = new Runnable() { @Override public void run() { // 使用httpUrlconnection try { URL url = new URL(path); // 根据 地址获取连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); InputStream is = conn.getInputStream(); // BitmapFactory是一个工具类decodeStream 将流转换成Bitmap Bitmap bitmap = BitmapFactory.decodeStream(is); LocalFileLayer mLocalFileLayer = new LocalFileLayer(folderName); // 缓存到二级 mLocalFileLayer.putBitmap(imageName, bitmap); } catch (Exception e) { e.printStackTrace(); } } }; ThreadUtils.runOnSubThread(runnable); } //参一:url,参二:保存文件路径名称 public static void downLoadFile(final String url, final String path, final String fileName) { Runnable runnable = new Runnable() { @Override public void run() { OkGo.get(url).execute(new com.lzy.okgo.callback.FileCallback(path, fileName) { @Override public void onSuccess(File file, Call call, Response response) { } }); } }; ThreadUtils.runOnSubThread(runnable); } }
31.783784
104
0.608844
bd6dd2cde9f5e8fd828ab0023ad36f7005cb1493
773
package algorythms; import java.util.ArrayList; public class HukumkaSort implements Algorythm { @Override public ArrayList<Integer> sort(ArrayList<Integer> data) { int i = 1; int j = 2; int temp; while (i < data.size()) {//n-1 if (data.get(i - 1) < data.get(i)) {//1 i = j;//1 j = j + 1;//2 } else {//10 temp = data.get(i);//1 data.set(i, data.get(i - 1));//2 data.set(i - 1, temp);//1 i = i - 1;//2 if (i == 0) {//1 i = j;//1 j++;//2 } } } //(n-1)*11 + 2 = 11n - 11 + 2 = 11n - 9 return data; } }
24.935484
61
0.368693
dad51c4769dcd8abad3efc4d99f48f5f266d4bd7
2,630
package org.oddjob.arooa.design.designer; import org.oddjob.arooa.design.DesignNotifier; import org.oddjob.arooa.design.actions.ActionContributor; import org.oddjob.arooa.design.actions.ConfigurableMenus; import org.oddjob.arooa.design.view.SwingFormView; import org.oddjob.arooa.design.view.ViewHelper; import org.oddjob.arooa.logging.Appender; import org.oddjob.arooa.logging.LogLevel; import org.oddjob.arooa.logging.LoggerAdapter; import javax.swing.*; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import java.awt.*; /** * The Swing GUI designer dialogue for Oddjob. * * @author Rob Gordon */ public class ArooaDesignerFormView implements SwingFormView { private final JComponent component; private final Component cell; private final MenuProvider menus; /** * Constructor * * @param designerForm The underlying form. */ public ArooaDesignerFormView(ArooaDesignerForm designerForm) { this(designerForm, false); } /** * Constructor. * */ public ArooaDesignerFormView(ArooaDesignerForm designerForm, boolean noErrorDialog) { DesignNotifier designerNotifier = designerForm.getConfigHelper(); DesignerModel designerModel = new DesignerModelImpl(designerNotifier); ConfigurableMenus menus = new ConfigurableMenus(); new DesignerEditActions(designerModel).contributeTo(menus); ActionContributor viewActions = new ViewActionsContributor( designerModel); viewActions.contributeTo(menus); this.menus = menus; component = new DesignerPanel(designerModel, menus); viewActions.addKeyStrokes(component); cell = ViewHelper.createDetailButton(designerForm); if (!noErrorDialog) { final Appender errorListener = event -> { if (!event.getLevel().isLessThan(LogLevel.ERROR)) { JOptionPane.showMessageDialog( component, event.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }; component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { LoggerAdapter .appenderAdapterFor("org.oddjob.arooa.design") .addAppender(errorListener); } public void ancestorMoved(AncestorEvent event) { } public void ancestorRemoved(AncestorEvent event) { LoggerAdapter .appenderAdapterFor("org.oddjob.arooa.design") .removeAppender(errorListener); } }); } } public Component cell() { return cell; } public Component dialog() { return component; } public MenuProvider getMenus() { return menus; } }
23.274336
72
0.722814
b7c908842d26cba3092e9f65fe16842570385ede
2,579
package org.grejpfrut.tiller.demo; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import org.grejpfrut.tiller.builders.ArticleBuilder; import org.grejpfrut.tiller.entities.Article; import org.grejpfrut.tiller.entities.Paragraph; import org.grejpfrut.tiller.entities.Sentence; import org.grejpfrut.tiller.utils.TillerConfiguration; /** * * @author Adam Dudczak */ public class TillerDemo { private final TillerConfiguration conf; public static void main(String args[]) { if (args.length != 1) { System.out.println("you must specify the path to file with text"); return; } TillerDemo td = new TillerDemo(new TillerConfiguration()); StringBuffer sb = new StringBuffer(); try { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(args[0]), "UTF8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } } catch (Exception e) { System.out.println("Exception while getting content of file " + args[0]); } System.out.println(td.demo(sb.toString(), false)); } public TillerDemo(TillerConfiguration conf) { this.conf = conf; } public String demo(String text, boolean isHtml) { if (isHtml ) return demoHtml(text); String newline = System.getProperty("line.separator"); ArticleBuilder ab = new ArticleBuilder(this.conf); Article art = ab.getArcticle(text); StringBuffer sb = new StringBuffer(); sb.append("<article>" + newline); for (Paragraph p : art.getParagraphs()) { sb.append(" <paragraph>" + newline); for (Sentence s : p.getSentences()) { sb.append(" <sentence>" + s.getText() + "</sentence>" + newline); } sb.append(" </paragraph>" + newline); } sb.append("</article>" + newline); return sb.toString(); } private String demoHtml(String text) { String newline = System.getProperty("line.separator"); ArticleBuilder ab = new ArticleBuilder(this.conf); Article art = ab.getArcticle(text); StringBuffer sb = new StringBuffer(); int counter = 0; sb.append("<ol>" + newline); for (Paragraph p : art.getParagraphs()) { String title = p.getTitle() != null ? p.getTitle() : "--"; sb.append(" <li>"+ title + "<ol>" + newline); for (Sentence s : p.getSentences()) { sb.append(" <li>" + s.getText() + "</li>" + newline); } sb.append(" </ol></li>" + newline); } sb.append("</ol>" + newline); return sb.toString(); } }
28.032609
70
0.64366
479c335f4b51eedd6ded7486b64a61324fd89913
47,066
package aceim.protocol.snuk182.icq.inner.dataprocessing; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import aceim.api.utils.Logger; import aceim.protocol.snuk182.icq.inner.ICQConstants; import aceim.protocol.snuk182.icq.inner.ICQServiceInternal; import aceim.protocol.snuk182.icq.inner.ICQServiceResponse; import aceim.protocol.snuk182.icq.inner.dataentity.Flap; import aceim.protocol.snuk182.icq.inner.dataentity.ICBMMessage; import aceim.protocol.snuk182.icq.inner.dataentity.ICQOnlineInfo; import aceim.protocol.snuk182.icq.inner.dataentity.Snac; import aceim.protocol.snuk182.icq.inner.dataentity.TLV; import aceim.protocol.snuk182.icq.utils.ProtocolUtils; import android.os.Environment; /* * it's strongly recommended not even breathe here, unless you're absolutely absolutely sure about what you gonna do... */ public class FileTransferEngine { private static final int SERVER_SOCKET_TIMEOUT = 600000; private static final String proxyUrl = "ars.oscar.aol.com"; private final Map<Long, FileRunnableService> activeTransfers = new HashMap<Long, FileRunnableService>(); private final ICQServiceInternal service; private final List<ICBMMessage> ftMessages = new ArrayList<ICBMMessage>(); private List<NotificationData> notifications = new LinkedList<NotificationData>(); public FileTransferEngine(ICQServiceInternal service) { this.service = service; } public List<ICBMMessage> getMessages() { return ftMessages; } public void fileReceiveResponse(long messageId, Boolean accept) { ICBMMessage message = findMessageByMessageId(messageId); if (message == null) { service.log("ft: no message"); return; } if (!message.senderId.equals(service.getUn())){ message.receiverId = message.senderId; message.senderId = service.getUn(); } message.rvMessageType = (short) (accept ? 2 : 1); if (!accept) { service.log("ft: reject from "+message.receiverId); service.getMessagingEngine().sendFileMessageReject(message); } else { service.log("ft: accept from "+message.receiverId); acceptFile(message); } } private void acceptFile(ICBMMessage message) { connectPeer(message, null, true); } private void createPeer(ICBMMessage message, List<File> files) throws IOException { service.log("ft: creating own peer"); FileRunnableService frs = activeTransfers.get(ProtocolUtils.bytes2LongBE(message.messageId, 0)); if (frs == null){ service.log("ft: new runnable for "+message.receiverId); frs = new FileRunnableService(FileRunnableService.TARGET_PEER, message, files); frs.connectionState = FileRunnableService.CONNSTATE_FILE_HEADER; activeTransfers.put(ProtocolUtils.bytes2LongBE(message.messageId, 0), frs); } else { service.log("ft: existing runnable for "+message.receiverId); frs.message = message; frs.target = FileRunnableService.TARGET_PEER; } frs.connectionState = FileRunnableService.CONNSTATE_FILE_HEADER; frs.server = createLocalSocket(frs); message.externalPort = frs.server.getLocalPort(); message.rvIp = ProtocolUtils.getIPString(service.getInternalIp()); message.rvMessageType = 0; sendFileTransferRequest(message, files); } private void connectPeer(ICBMMessage message, FileRunnableService runnable, boolean incoming) { service.log("connecting peer "+message.rvIp+":"+message.externalPort+"//sender "+message.senderId+"//receiver "+message.receiverId); Socket socket; try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddress.getByAddress(ProtocolUtils.ipString2ByteBE(message.rvIp)), message.externalPort), 7000); } catch (UnknownHostException e) { service.log(e); socket = null; } catch (IOException e) { service.log(e); socket = null; } if (socket != null && socket.isConnected()) { service.log("ft: direct socket connected for "+message.receiverId); if (runnable == null){ service.log("ft: new runnable for "+message.receiverId); runnable = new FileRunnableService(socket, FileRunnableService.TARGET_PEER, message); runnable.connectionState = FileRunnableService.CONNSTATE_FILE_HEADER; activeTransfers.put(ProtocolUtils.bytes2LongBE(message.messageId, 0), runnable); } else { service.log("ft: existing runnable for "+message.receiverId); if (runnable.server != null){ try { runnable.server.close(); runnable.server = null; } catch (IOException e) { service.log(e); } } runnable.socket = socket; runnable.connectionState = FileRunnableService.CONNSTATE_FILE_HEADER; runnable.target = FileRunnableService.TARGET_PEER; } runnable.start(); if (!message.senderId.equals(service.getUn())){ message.receiverId = message.senderId; } service.getRunnableService().sendToSocket(getAcceptMessage(message)); } else { service.log("ft: no direct connection"); if (incoming/* && checkForClientsDCCapability(message.receiverId)*/){ service.log("ft: creating socket for "+message.receiverId); try { createPeer(message, null); } catch (IOException e) { service.log(e); connectProxy(message, runnable); } } else { connectProxy(message, runnable); } } } @SuppressWarnings("unused") private boolean checkForClientsDCCapability(String receiverId) { String dcCap = ProtocolUtils.getHexString(ICQConstants.CLSID_DIRECT); for (ICQOnlineInfo info: service.getBuddyList().buddyInfos){ if (info.uin.equals(receiverId) && info.capabilities!=null){ for (String cap: info.capabilities){ if (dcCap.equals(cap)){ return true; } } } } return false; } private void connectProxy(ICBMMessage message, FileRunnableService runnable) { Socket socket; try { if (message.connectFTProxy){ service.log("connecting proxy "+message.rvIp+":"+service.getLoginPort()); socket = new Socket(message.rvIp, service.getLoginPort()); } else { service.log("creating proxy call"); socket = new Socket(proxyUrl, service.getLoginPort()); } } catch (UnknownHostException e) { service.log(e); socket = null; } catch (IOException e) { service.log(e); socket = null; } if (socket != null && socket.isConnected()) { if (runnable == null) { runnable = new FileRunnableService(socket, FileRunnableService.TARGET_PROXY, message); activeTransfers.put(ProtocolUtils.bytes2LongBE(message.messageId, 0), runnable); } else { if (runnable.server != null){ try { runnable.server.close(); runnable.server = null; } catch (IOException e) { service.log(e); } } runnable.socket = socket; runnable.connectionState = FileRunnableService.CONNSTATE_HANDSHAKE; runnable.target = FileRunnableService.TARGET_PROXY; runnable.message = message; } runnable.start(); } else { transferFailed(new IOException("Cannot connect"), "", message, message.senderId); } } public ICBMMessage findMessageByMessageId(long messageId) { for (ICBMMessage msg : ftMessages) { if (ProtocolUtils.bytes2LongBE(msg.messageId, 0) == messageId) { return msg; } } return null; } public ICBMMessage findMessageByMessageId(byte[] messageId) { for (ICBMMessage msg : ftMessages) { if (Arrays.equals(messageId, msg.messageId)) { return msg; } } return null; } public void removeMessageByMessageId(long messageId) { for (int i=ftMessages.size()-1; i>=0; i--) { ICBMMessage msg = ftMessages.get(i); if (ProtocolUtils.bytes2LongBE(msg.messageId, 0) == messageId) { ftMessages.remove(i); break; } } } class FileRunnableService extends Thread { public static final int CONNSTATE_CONNECTED = 0; public static final int CONNSTATE_HANDSHAKE = 1; public static final int CONNSTATE_FILE_HEADER = 2; public static final int CONNSTATE_FILE_BODY = 3; public static final int CONNSTATE_FILE_SENT = 4; public static final int CONNSTATE_DISCONNECTED = 5; public static final int TARGET_PEER = 0; public static final int TARGET_PROXY = 1; ServerSocket server = null; Socket socket; int connectionState = CONNSTATE_CONNECTED; int target; ICBMMessage message; String participantUid = null; List<byte[]> blobs = new LinkedList<byte[]>(); List<File> files = null; long currentFileSizeLeft = 0; long currentFileSize = 0; byte[] currentFileInfo = null; int totalFiles = 1; private ExtendedBufferedOutputStream currentFileStream; private String currentFileName; byte[] buffer = null; public FileRunnableService(Socket socket, int target, ICBMMessage message) { this(socket, target, message, null); } public FileRunnableService(int target, ICBMMessage message, List<File> files) { this(null, target, message, files); } public FileRunnableService(Socket socket, int target, ICBMMessage message, List<File> files) { this.socket = socket; this.target = target; this.message = message; this.files = files; if (files != null) { totalFiles = files.size(); currentFileSize = 0; for (File f : files) { currentFileSize += f.length(); } } if (message.senderId !=null && !message.senderId.equals(service.getUn())){ participantUid = message.senderId; } else { participantUid = message.receiverId; } setName("File transfer " + message.senderId); } @Override public void run() { if (socket == null) { return; } if (message.receiverId.equals(service.getUn())){ message.receiverId = message.senderId; message.senderId = service.getUn(); } if (target == TARGET_PROXY) { sendHandshake(); } else if (files != null && files.size()>0 && message.connectFTPeer) { connectionState = CONNSTATE_FILE_HEADER; fireTransfer(); } /*else { if (files != null) { sendFileInfo(files.get(0)); } }*/ getDataFromSocket(); } private void sendFileInfo(File file) { byte[] infoBlob; byte[] filenameBytes = file.getName().getBytes(); String encoding = null;/*"UTF-16BE"; try { filenameBytes = file.getName().getBytes(encoding); } catch (UnsupportedEncodingException e) { filenameBytes = file.getName().getBytes(); encoding = "UTF-8"; }*/ if (filenameBytes.length + 194 > 256){ infoBlob = new byte[filenameBytes.length + 194]; } else { infoBlob = new byte[256]; } Arrays.fill(infoBlob, (byte) 0); infoBlob[0] = 0x4f; // file header infoBlob[1] = 0x46; infoBlob[2] = 0x54; infoBlob[3] = 0x32; int pos = 4; System.arraycopy(ProtocolUtils.short2ByteBE((short) infoBlob.length), 0, infoBlob, pos, 2); pos+=2; System.arraycopy(ProtocolUtils.short2ByteBE((short) 0x101), 0, infoBlob, pos, 2); //stage pos+=2; System.arraycopy(message.messageId, 0, infoBlob, pos, 8); //cookie; pos+=8; System.arraycopy(new byte[]{0,0}, 0, infoBlob, pos, 2); //encryption pos+=2; System.arraycopy(new byte[]{0,0}, 0, infoBlob, pos, 2); //compression pos+=2; System.arraycopy(ProtocolUtils.short2ByteBE((short) totalFiles), 0, infoBlob, pos, 2); //total files pos+=2; System.arraycopy(ProtocolUtils.short2ByteBE((short) files.size()), 0, infoBlob, pos, 2); // files left pos+=2; System.arraycopy(new byte[]{0,1}, 0, infoBlob, pos, 2); //dunno pos+=2; System.arraycopy(new byte[]{0,1}, 0, infoBlob, pos, 2); //dunno pos+=2; System.arraycopy(ProtocolUtils.int2ByteBE((int) currentFileSize), 0, infoBlob, pos, 4); pos+=4; System.arraycopy(ProtocolUtils.int2ByteBE((int) file.length()), 0, infoBlob, pos, 4); pos+=4; System.arraycopy(ProtocolUtils.int2ByteBE((int) file.lastModified()/1000), 0, infoBlob, pos, 4); pos+=4; try { System.arraycopy(ProtocolUtils.int2ByteBE((int) getChecksum(file)), 0, infoBlob, pos, 4); } catch (IOException e) { service.log(e); System.arraycopy(ProtocolUtils.int2ByteBE( 0), 0, infoBlob, pos, 4); } pos+=4; System.arraycopy(new byte[]{(byte) 0xff,(byte) 0xff,0,0}, 0, infoBlob, pos, 4); //dunno what's that pos+=4; System.arraycopy(new byte[]{0,0,0,0}, 0, infoBlob, pos, 4); pos+=4; System.arraycopy(new byte[]{0,0,0,0}, 0, infoBlob, pos, 4); pos+=4; System.arraycopy(new byte[]{(byte) 0xff,(byte) 0xff,0,0}, 0, infoBlob, pos, 4); pos+=4; System.arraycopy(new byte[]{0,0,0,0}, 0, infoBlob, pos, 4); pos+=4; System.arraycopy(new byte[]{(byte) 0xff,(byte) 0xff,0,0}, 0, infoBlob, pos, 4); pos+=4; byte[] id = new String("Cool FileXfer").getBytes(); System.arraycopy(id, 0, infoBlob, pos, id.length); pos+=32; infoBlob[pos] = 0x20; pos++; infoBlob[pos] = 0x1c; pos++; infoBlob[pos] = 0x11; pos++; pos+=69; //dummy? pos+=16; //mac file info? //if (encoding.equals("UTF-16BE")) { // System.arraycopy(new byte[]{0,2}, 0, infoBlob, pos, 2); //encoding //} else { System.arraycopy(new byte[]{0,0}, 0, infoBlob, pos, 2); //encoding //} pos+=2; System.arraycopy(new byte[]{0,0}, 0, infoBlob, pos, 2); //encoding subcode pos+=2; System.arraycopy(filenameBytes, 0, infoBlob, pos, filenameBytes.length); sendToSocket(infoBlob); } private void sendHandshake() { sendToSocket(getHandshakeData(message)); } private boolean getDataFromSocket() { byte[] tail = null; int read = 0; int tailLength = 0; while (connectionState != CONNSTATE_DISCONNECTED && socket != null && socket.isConnected() && !socket.isClosed()) { InputStream is; try { is = socket.getInputStream(); if (is.available() < 1) { Thread.sleep(300); } else { Thread.sleep(500); if (tail == null) { byte[] lengthBytes; switch (connectionState) { case CONNSTATE_CONNECTED: case CONNSTATE_HANDSHAKE: lengthBytes = new byte[2]; is.read(lengthBytes, 0, 2); tailLength = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(lengthBytes)); break; case CONNSTATE_FILE_HEADER: byte[] fileHdrMark = new byte[4]; is.read(fileHdrMark, 0, 4); if (fileHdrMark[0] == 0x4f // file header && fileHdrMark[1] == 0x46 && fileHdrMark[2] == 0x54 && fileHdrMark[3] == 0x32) { lengthBytes = new byte[2]; is.read(lengthBytes, 0, 2); tailLength = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(lengthBytes)) - 6; } break; case CONNSTATE_FILE_BODY: if (buffer == null) { buffer = new byte[88000]; } read = is.read(buffer, 0, buffer.length); service.log("read " + read+"| bytes left " + currentFileSizeLeft); currentFileSizeLeft -= read; fileData(buffer, read, currentFileSizeLeft); if (currentFileSizeLeft < 1) { sendFileAck(); connectionState = CONNSTATE_FILE_HEADER; totalFiles--; buffer = null; if (totalFiles < 1) { cleanup(); } } /* * if (buffer.length >= currentFileSizeLeft){ * //read = is.read(buffer, 0, buffer.length); * //buffer = new byte[(int) * currentFileSizeLeft]; read = is.read(buffer, * 0, buffer.length); service.log("read "+read); * * currentFileSizeLeft-=read; fileData(buffer, * read, currentFileSizeLeft); * * if (currentFileSizeLeft < 1){ sendFileAck(); * connectionState = CONNSTATE_FILE_HEADER; * totalFiles--; buffer = null; if (totalFiles < * 1){ ftMessages.remove(message); * activeTransfers.remove(message.messageId); * socket.close(); } } * * } else { read = is.read(buffer, 0, * buffer.length); service.log("read "+read); * currentFileSizeLeft-=read; fileData(buffer, * read, currentFileSizeLeft); } */ continue; } read = 0; tail = new byte[tailLength]; read += is.read(tail, 0, tailLength); service.log("-- FT Got " + ProtocolUtils.getSpacedHexString(tail)); if (read < tailLength) { continue; } } else { read += is.read(tail, 6 + read, tailLength - read); if (read < tailLength) { continue; } } try { blobs.add(tail); } catch (Exception e) { service.log(e); } new Thread("File transfer processor") { @Override public void run() { try { forceBlobProcess(); } catch (Exception e) { service.log(e); } } }.start(); tail = null; } } catch (IOException e) { service.log(e); } catch (InterruptedException e) { service.log(e); } } cleanup(); return false; } private void sendFileAck() { if (currentFileInfo == null) { return; } byte[] out = getFileInfoByteBlock(currentFileInfo, (short) 0x204); sendToSocket(out); } public synchronized boolean sendToSocket(byte[] out) { try { OutputStream os = socket.getOutputStream(); service.log("-- FT To be sent " + ProtocolUtils.getSpacedHexString(out)); os.write(out); } catch (IOException e) { connectionState = CONNSTATE_DISCONNECTED; service.log(e); } return true; } protected void forceBlobProcess() throws Exception { synchronized (blobs) { while (blobs.size() > 0) { byte[] blob = blobs.remove(0); process(blob); } } } private void process(byte[] blob) { switch (connectionState) { case CONNSTATE_CONNECTED: case CONNSTATE_HANDSHAKE: parseRendezvous(blob); break; case CONNSTATE_FILE_HEADER: service.log("got header"); currentFileInfo = blob; parseFileInfoBlob(blob); break; case CONNSTATE_FILE_BODY: // fileData(blob); break; } } public void parseRendezvous(byte[] blob) { switch (blob[3]) { case 0x3: connectionState = CONNSTATE_HANDSHAKE; int portId = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(blob, 10)); String rvIp = ProtocolUtils.getIPString(blob, 12); message.rvMessageType = 0; message.receiverId = participantUid; //if (files == null){ service.getRunnableService().sendToSocket(getRedirectToProxyMessage(rvIp, portId, message, 2)); /*} else { service.getRunnableService().sendToSocket(getAcceptMessage(message)); }*/ break; case 0x4: //sendFileInfo(files.get(0)); break; case 0x5: connectionState = CONNSTATE_FILE_HEADER; if (files != null){ message.receiverId = participantUid; service.getRunnableService().sendToSocket(getAcceptMessage(message)); fireTransfer(); } break; } } private void parseFileInfoBlob(byte[] blob) { // assume we have no 6 bytes of header in a blob int pos = 0; short stage = ProtocolUtils.bytes2ShortBE(blob, pos); pos += 2; pos += 8; // skip msg cookie //short encryption = ProtocolUtils.bytes2ShortBE(blob, pos); pos += 2; //short compression = ProtocolUtils.bytes2ShortBE(blob, pos); pos += 2; int filesCount = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(blob, pos)); pos += 2; //int filesLeft = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(blob, pos)); pos += 2; //int partsCount = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(blob, pos)); pos += 2; pos += 2; // dunno what's there //long totalFilesize = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(blob, pos)); pos += 4; long thisFileSize = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(blob, pos)); pos += 4; long modTime = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(blob, pos))*1000; pos += 4; //long checksum = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(blob, pos)); pos += 4; pos += 16; // dunno what's there ^^ long thisFileSizeSent = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(blob, pos)); pos += 4; @SuppressWarnings("unused") long checksumSent = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(blob, pos)); pos += 4; pos += 32; // skip ID //byte flags = blob[pos]; pos++; pos += 2; // skip some offsets pos += 69; // skip dummy pos += 16; // skip mac file info short charsetType = ProtocolUtils.bytes2ShortBE(blob, pos); pos += 2; short charsetSubcode = ProtocolUtils.bytes2ShortBE(blob, pos); pos += 2; service.log("char code "+charsetType+"|char subcode "+charsetSubcode); int filenamePos = pos; for (int i=blob.length-2; i>pos; i--){ if (blob[i] != 0){ pos = i+1; break; } } int filemaneSize = pos - filenamePos; byte[] filenameBytes = new byte[filemaneSize]; System.arraycopy(blob, filenamePos, filenameBytes, 0, filemaneSize); String encoding; switch (charsetType) { case 0: encoding = "UTF-8"; break; case 2: encoding = "UTF-16"; break; default: encoding = "windows-1251"; break; } String filename; try { filename = new String(filenameBytes, encoding); } catch (UnsupportedEncodingException e) { filename = new String(filenameBytes); } if (files == null){ totalFiles = filesCount; service.log("file info " + filename + " sized " + thisFileSize); currentFileSizeLeft = thisFileSize; currentFileSize = thisFileSize; currentFileStream = createFile(filename, thisFileSize, modTime, message, participantUid); currentFileName = filename; byte[] out = getFileInfoByteBlock(blob, (short) 0x202); sendToSocket(out); connectionState = CONNSTATE_FILE_BODY; } else { switch(stage){ case 0x202: connectionState = CONNSTATE_FILE_BODY; sendFileToSocket(files.get(0)); break; case 0x204: files.remove(0); if (files.size()<1){ cleanup(); } else { sendFileInfo(files.get(0)); } break; case 0x205: byte[] out2 = getFileInfoByteBlock(blob, (short) 0x106); sendToSocket(out2); break; case 0x106: break; case 0x207: connectionState = CONNSTATE_FILE_BODY; sendFileToSocket(files.get(0), thisFileSizeSent); break; } } } private void sendFileToSocket(final File file){ sendFileToSocket(file, 0); } private void sendFileToSocket(final File file, long startFrom) { OutputStream os; try { os = socket.getOutputStream(); } catch (IOException e) { service.log(e); transferFailed(e, file.getAbsolutePath(), message, participantUid); cleanup(); return; } long length = file.length(); if (length > 8000){ buffer = new byte[8000]; } else { buffer = new byte[(int) length]; } currentFileSizeLeft = 0; int read = 0; service.log("sending "+file.getName()+" to "+participantUid); BufferedInputStream bis = null; try { FileInputStream fis = new FileInputStream(file); if (startFrom > 0){ fis.skip(startFrom); currentFileSizeLeft += startFrom; } bis = new BufferedInputStream(fis, 8000); while(currentFileSizeLeft < length){ read = bis.read(buffer, 0, buffer.length); if (read < 0){ break; } os.write(buffer, 0, read); os.flush(); currentFileSizeLeft += read; service.log("sent "+currentFileSizeLeft+" bytes"); sendNotification(message.messageId, file.getAbsolutePath(), length, currentFileSizeLeft, false, null, participantUid); try { Thread.sleep(500); } catch (InterruptedException e) { service.log(e); } } } catch (IOException e) { service.log(e); transferFailed(e, file.getAbsolutePath(), message, participantUid); cleanup(); return; } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { service.log(e); } } } connectionState = CONNSTATE_FILE_HEADER; service.log(file.getName()+" sent"); } private void cleanup() { try { socket.close(); ftMessages.remove(message); activeTransfers.remove(ProtocolUtils.bytes2LongBE(message.messageId, 0)); if (server != null){ server.close(); server = null; } } catch (IOException e) { } } private synchronized void fileData(byte[] blob, int read, final long bytesLeft) { if (currentFileStream != null) { try { /* * if (connectionState == CONNSTATE_FILE_HEADER){ * currentFileStream.close(); currentFileStream = null; } * else if (connectionState == CONNSTATE_FILE_BODY){ * currentFileStream.write(blob); } */ if (connectionState == CONNSTATE_FILE_BODY) { currentFileStream.write(blob, 0, read); currentFileStream.flush(); if (bytesLeft < 1) { connectionState = CONNSTATE_FILE_HEADER; final String filename = currentFileStream.file.getAbsolutePath(); currentFileStream.close(); currentFileStream = null; service.log(currentFileName + " got"); sendNotification( message.messageId, filename, currentFileSize, currentFileSize - bytesLeft, true, null, participantUid); } else { sendNotification( message.messageId, currentFileStream.getFile().getAbsolutePath(), currentFileSize, currentFileSize - bytesLeft, true, null, participantUid); } } // messageId, filename, totalSize, sizeTransferred, // isReceive, error } catch (IOException e) { Logger.log(e); try { currentFileStream.close(); } catch (IOException e1) { Logger.log(e); } currentFileStream = null; } } } public void fireTransfer() { service.log("client ready, proceed FT"); if (message.receiverId.equals(service.getUn())){ message.receiverId = message.senderId; message.senderId = service.getUn(); } if (files != null){ if (currentFileSizeLeft < 1){ sendFileInfo(files.get(0)); } } } } private synchronized void sendNotification(byte[] messageId, String filename, long totalSize, long sizeSent, boolean incoming, String error, String participantUid){ NotificationData data = new NotificationData(messageId, filename, totalSize, sizeSent, incoming, error, participantUid); notifications.add(data); new Thread("Notification"){ @Override public void run(){ sendNotifications(); } }.start(); } public long getChecksum(File file) throws IOException, IllegalStateException { long sum = 0; long end = file.length(); RandomAccessFile aFile = null; try { FileTransferChecksum summer = new FileTransferChecksum(); ByteBuffer buffer = ByteBuffer.allocate(1024); long remaining = end; aFile = new RandomAccessFile(file, "r"); FileChannel channel = aFile.getChannel(); while (remaining > 0) { buffer.rewind(); buffer.limit((int) Math.min(remaining, buffer.capacity())); int count = channel.read(buffer); if (count == -1) break; buffer.flip(); remaining -= buffer.limit(); summer.update(buffer.array(), buffer.arrayOffset(), buffer.limit()); } if (remaining > 0) { throw new IOException("could not get checksum for entire file; " + remaining + " failed of " + end); } sum = summer.getValue(); } finally { if (aFile != null) { aFile.close(); } } return sum; } private void sendNotifications() { synchronized (notifications) { while (notifications.size() > 0){ NotificationData data = notifications.remove(0); service.getServiceResponse().respond(ICQServiceResponse.RES_FILEPROGRESS, data.messageId, data.filePath, data.totalSize, data.sent, data.incoming, data.error, data.participantUid); } } } private byte[] getHandshakeData(ICBMMessage message) { service.log("get handshake for "+message.externalPort+" id "+ProtocolUtils.getHexString(message.messageId)); byte[] header = new byte[12]; Arrays.fill(header, (byte) 0); header[2] = 0x04; header[3] = 0x4a; if (message.connectFTProxy){ header[5] = 0x4; } else { header[5] = 0x2; } byte[] uinBytes; try { uinBytes = message.senderId.getBytes("ASCII"); } catch (UnsupportedEncodingException e1) { uinBytes = message.senderId.getBytes(); } TLV clsidTlv = new TLV(); clsidTlv.type = 1; clsidTlv.value = ICQConstants.CLSID_AIM_FILESEND; byte[] tlvBytes = service.getDataParser().tlvs2Bytes(new TLV[] { clsidTlv }); byte[] out = new byte[21 + uinBytes.length + tlvBytes.length + ((message.connectFTProxy) ? 2 : 0)]; byte pos = 0; System.arraycopy(header, 0, out, pos, header.length); pos += header.length; out[pos] = (byte) uinBytes.length; pos++; System.arraycopy(uinBytes, 0, out, pos, uinBytes.length); pos += uinBytes.length; if (message.connectFTProxy){ System.arraycopy(ProtocolUtils.short2ByteBE((short) message.externalPort), 0, out, pos, 2); pos+=2; } System.arraycopy(message.messageId, 0, out, pos, 8); pos += 8; System.arraycopy(tlvBytes, 0, out, pos, tlvBytes.length); System.arraycopy(ProtocolUtils.short2ByteBE((short) (out.length - 2)), 0, out, 0, 2); return out; } public void transferFailed(Exception e, String filename, ICBMMessage message, String participantUid) { if (!message.senderId.equals(service.getUn())){ message.receiverId = participantUid; message.senderId = service.getUn(); } message.rvMessageType = 1; service.getMessagingEngine().sendFileMessageReject(message); sendNotification(message.messageId, filename, 100, 0, false, e.getLocalizedMessage(), participantUid); } private ExtendedBufferedOutputStream createFile(String filename, long filesize, long modTime, ICBMMessage message, String participantUid) { // Dummy String storageState = Environment.getExternalStorageState(); if (storageState.equals(Environment.MEDIA_MOUNTED)) { try { File file = (File) service.getServiceResponse().respond(ICQServiceResponse.RES_GET_FILE_FOR_SAVING, filename, service.getBuddyList().findBuddyByUin(participantUid), modTime); FileOutputStream fos = new FileOutputStream(file, true); ExtendedBufferedOutputStream os = new ExtendedBufferedOutputStream(file, fos); return os; } catch (IOException e) { e.printStackTrace(); } } else { transferFailed(new IOException("No storage mounted"), filename, message, participantUid); } return null; } private byte[] getFileInfoByteBlock(byte[] blob, short state) { byte[] out = new byte[blob.length + 6]; out[0] = 0x4f; // file header out[1] = 0x46; out[2] = 0x54; out[3] = 0x32; System.arraycopy(ProtocolUtils.short2ByteBE((short) (blob.length + 6)), 0, out, 4, 2); System.arraycopy(ProtocolUtils.short2ByteBE(state), 0, blob, 0, 2); System.arraycopy(blob, 0, out, 6, blob.length); return out; } private Flap getAcceptMessage(ICBMMessage message){ message.rvMessageType = 2; Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; data.requestId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; TLV tlv2711 = new TLV(); tlv2711.type = 0x2711; byte[] tlv5data = service.getDataParser().tlvs2Bytes(new TLV[]{tlv2711}); byte[] tlv5fullData = new byte[26 + tlv5data.length]; System.arraycopy(ProtocolUtils.short2ByteBE(message.rvMessageType), 0, tlv5fullData, 0, 2); System.arraycopy(message.messageId, 0, tlv5fullData, 2, 8); System.arraycopy(ICQConstants.CLSID_AIM_FILESEND, 0, tlv5fullData, 10, 16); System.arraycopy(tlv5data, 0, tlv5fullData, 26, tlv5data.length); TLV ch2messageTLV = new TLV(); ch2messageTLV.type = 0x5; ch2messageTLV.value = tlv5fullData; byte[] uidBytes; try { uidBytes = message.receiverId.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { uidBytes = message.receiverId.getBytes(); } byte[] snacRawData = new byte[11 + uidBytes.length]; System.arraycopy(message.messageId, 0, snacRawData, 0, 8); System.arraycopy(ProtocolUtils.short2ByteBE((short) 2), 0, snacRawData, 8, 2); snacRawData[10] = (byte) message.receiverId.length(); System.arraycopy(uidBytes, 0, snacRawData, 11, uidBytes.length); data.data = new TLV[] { ch2messageTLV }; data.plainData = snacRawData; flap.data = data; return flap; } private Flap getRedirectToProxyMessage(String rvIp, int portId, ICBMMessage message, int seqNum) { Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; data.requestId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; /* * TLV internalIpTLV = new TLV(); internalIpTLV.setType(0x03); byte[] * buffer; try { buffer = InetAddress.getLocalHost().getAddress(); } * catch (UnknownHostException e) { buffer = new byte[]{0,0,0,0}; } * internalIpTLV.setValue(buffer); * * TLV portTLV = new TLV(); portTLV.setType(0x05); * portTLV.setValue(Utils.short2ByteBE(ICQConstants.ICBM_PORT)); */ TLV unknownA = new TLV(); unknownA.type = 0xa; unknownA.value = new byte[] { 0, (byte) seqNum }; TLV rvIPtlv = new TLV(); rvIPtlv.type = 2; rvIPtlv.value = ProtocolUtils.ipString2ByteBE(rvIp); TLV xoredRvIpTlv = new TLV(); xoredRvIpTlv.type = 0x16; xoredRvIpTlv.value = ProtocolUtils.unxorByteArray(rvIPtlv.value); TLV extPortTlv = new TLV(); extPortTlv.type = 5; extPortTlv.value = ProtocolUtils.short2ByteBE((short) portId); TLV xoredPortTlv = new TLV(); xoredPortTlv.type = 0x17; xoredPortTlv.value = ProtocolUtils.unxorByteArray(extPortTlv.value); TLV redirectTlv = new TLV(); redirectTlv.type = 0x10; TLV[] tlv5content = new TLV[] { unknownA, rvIPtlv, xoredRvIpTlv, extPortTlv, xoredPortTlv, redirectTlv }; byte[] tlv5data = service.getDataParser().tlvs2Bytes(tlv5content); byte[] tlv5fullData = new byte[26 + tlv5data.length]; System.arraycopy(ProtocolUtils.short2ByteBE(message.rvMessageType), 0, tlv5fullData, 0, 2); System.arraycopy(message.messageId, 0, tlv5fullData, 2, 8); System.arraycopy(ICQConstants.CLSID_AIM_FILESEND, 0, tlv5fullData, 10, 16); System.arraycopy(tlv5data, 0, tlv5fullData, 26, tlv5data.length); TLV ch2messageTLV = new TLV(); ch2messageTLV.type = 0x5; ch2messageTLV.value = tlv5fullData; byte[] uidBytes; try { uidBytes = message.receiverId.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { uidBytes = message.receiverId.getBytes(); } byte[] snacRawData = new byte[11 + uidBytes.length]; System.arraycopy(message.messageId, 0, snacRawData, 0, 8); System.arraycopy(ProtocolUtils.short2ByteBE((short) 2), 0, snacRawData, 8, 2); snacRawData[10] = (byte) message.receiverId.length(); System.arraycopy(uidBytes, 0, snacRawData, 11, uidBytes.length); data.data = new TLV[] { ch2messageTLV }; data.plainData = snacRawData; flap.data = data; return flap; } public long sendFiles(final ICBMMessage message) { message.rvMessageType = 0; if (message.messageId == null) { message.messageId = new byte[8]; ICBMMessagingEngine.RANDOM.nextBytes(message.messageId); } message.externalPort = service.getLoginPort(); message.rvIp = ProtocolUtils.getIPString(service.getInternalIp()); ftMessages.add(message); new Thread("File sender "+message.receiverId){ @Override public void run(){ try { List<File> files = message.getFileList(); createPeer(message, files); } catch (IOException e) { Logger.log(e); connectProxy(message, activeTransfers.get(ProtocolUtils.bytes2LongBE(message.messageId, 0))); } } }.start(); return ProtocolUtils.bytes2LongBE(message.messageId); } private void sendFileTransferRequest(ICBMMessage message, List<File> files){ short type = 1; TLV tlv2711 = null; TLV unknownA = new TLV(); unknownA.type = 0xa; if (files != null){ int count = files.size(); long filesize = 0; for (File f : files) { filesize += f.length(); } byte[] filename; if (files.size() == 1) { try { filename = files.get(0).getName().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { filename = files.get(0).getName().getBytes(); } } else { filename = new byte[0]; } byte[] tlv2711data = new byte[9 + filename.length]; int pos = 0; System.arraycopy(ProtocolUtils.short2ByteBE(type), 0, tlv2711data, pos, 2); pos += 2; System.arraycopy(ProtocolUtils.short2ByteBE((short) count), 0, tlv2711data, pos, 2); pos += 2; System.arraycopy(ProtocolUtils.int2ByteBE((int) filesize), 0, tlv2711data, pos, 4); pos += 4; System.arraycopy(filename, 0, tlv2711data, pos, filename.length); tlv2711 = new TLV(); tlv2711.type = 0x2711; tlv2711.value = tlv2711data; unknownA.value = new byte[] { 0, 1 }; } else { unknownA.value = new byte[] { 0, 2 }; } Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; data.requestId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; /* * TLV internalIpTLV = new TLV(); internalIpTLV.setType(0x03); byte[] * buffer; try { buffer = InetAddress.getLocalHost().getAddress(); } * catch (UnknownHostException e) { buffer = new byte[]{0,0,0,0}; } * internalIpTLV.setValue(buffer); * * TLV portTLV = new TLV(); portTLV.setType(0x05); * portTLV.setValue(Utils.short2ByteBE(ICQConstants.ICBM_PORT)); */ TLV unknownF = new TLV(); unknownF.type = 0xf; TLV rvIPtlv = new TLV(); rvIPtlv.type = 2; rvIPtlv.value = ProtocolUtils.ipString2ByteBE(message.rvIp); TLV xoredRvIpTlv = new TLV(); xoredRvIpTlv.type = 0x16; xoredRvIpTlv.value = ProtocolUtils.unxorByteArray(rvIPtlv.value); TLV extPortTlv = new TLV(); extPortTlv.type = 5; extPortTlv.value = ProtocolUtils.short2ByteBE((short) message.externalPort); TLV xoredPortTlv = new TLV(); xoredPortTlv.type = 0x17; xoredPortTlv.value = ProtocolUtils.unxorByteArray(extPortTlv.value); TLV internalIPTlv = new TLV(); internalIPTlv.type = 0x3; internalIPTlv.value = ProtocolUtils.ipString2ByteBE(message.rvIp); TLV tlv2712 = new TLV(); tlv2712.type = 0x2712; tlv2712.value = new String("utf-8").getBytes(); /* * TLV tlv2713 = new TLV(); tlv2713.type = 0x2713; tlv2713.value = new * byte[8]; Arrays.fill(tlv2713.value, (byte) 0); */ TLV[] tlv5content; if (files != null){ tlv5content = new TLV[] { unknownA, unknownF, rvIPtlv, xoredRvIpTlv, internalIPTlv, extPortTlv, xoredPortTlv, tlv2711, tlv2712 }; } else { tlv5content = new TLV[] { unknownA, unknownF, rvIPtlv, xoredRvIpTlv, internalIPTlv, extPortTlv, xoredPortTlv }; } byte[] tlv5data = service.getDataParser().tlvs2Bytes(tlv5content); byte[] tlv5fullData = new byte[26 + tlv5data.length]; System.arraycopy(ProtocolUtils.short2ByteBE(message.rvMessageType), 0, tlv5fullData, 0, 2); System.arraycopy(message.messageId, 0, tlv5fullData, 2, 8); System.arraycopy(ICQConstants.CLSID_AIM_FILESEND, 0, tlv5fullData, 10, 16); System.arraycopy(tlv5data, 0, tlv5fullData, 26, tlv5data.length); TLV ch2messageTLV = new TLV(); ch2messageTLV.type = 0x5; ch2messageTLV.value = tlv5fullData; byte[] uidBytes; try { uidBytes = message.receiverId.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { uidBytes = message.receiverId.getBytes(); } byte[] snacRawData = new byte[11 + uidBytes.length]; System.arraycopy(message.messageId, 0, snacRawData, 0, 8); System.arraycopy(ProtocolUtils.short2ByteBE((short) 2), 0, snacRawData, 8, 2); snacRawData[10] = (byte) message.receiverId.length(); System.arraycopy(uidBytes, 0, snacRawData, 11, uidBytes.length); data.data = new TLV[] { ch2messageTLV }; data.plainData = snacRawData; flap.data = data; service.getRunnableService().sendToSocket(flap); } private ServerSocket createLocalSocket(final FileRunnableService frs) throws IOException { final ServerSocket server = new ServerSocket(0); new Thread("FT Server socket listener") { @Override public void run() { try { server.setSoTimeout(SERVER_SOCKET_TIMEOUT); Socket socket = server.accept(); frs.socket = socket; service.log("client connected"); frs.start(); } catch (Exception e) { service.log(e); } } }.start(); return server; } public void redirectRequest(ICBMMessage message) { FileRunnableService runnable = activeTransfers.get(ProtocolUtils.bytes2LongBE(message.messageId, 0)); if (runnable == null) { return; } runnable.message = message; if (message.connectFTProxy){ connectProxy(message, runnable); } else if (message.connectFTPeer){ connectPeer(message, runnable, false); } } public void fireTransfer(ICBMMessage message) { FileRunnableService runnable = activeTransfers.get(ProtocolUtils.bytes2LongBE(message.messageId, 0)); if (runnable == null) { return; } runnable.fireTransfer(); } private class ExtendedBufferedOutputStream extends BufferedOutputStream { private final File file; public ExtendedBufferedOutputStream(File file, OutputStream os) { super(os, 88000); this.file = file; } public File getFile() { return file; } } public void cancel(Long messageId) { if (findMessageByMessageId(messageId) == null) { return; }; fileReceiveResponse(messageId, false); FileRunnableService runnable = activeTransfers.get(messageId); if (runnable == null) { return; } if (runnable.socket!=null && !runnable.socket.isClosed()){ try { runnable.socket.close(); } catch (IOException e) { service.log(e); } } activeTransfers.remove(messageId); removeMessageByMessageId(messageId); } private class NotificationData { public byte[] messageId; public String filePath; public long totalSize; public long sent; public boolean incoming; public String error; public String participantUid; public NotificationData( byte[] messageId, String filePath, long totalSize, long sent, boolean incoming, String error, String participantUid){ this.messageId = messageId; this.filePath = filePath; this.totalSize = totalSize; this.sent = sent; this.incoming = incoming; this.error = error; this.participantUid = participantUid; } } public void cancelAll() { for (FileRunnableService runnable: activeTransfers.values()){ if (runnable.socket != null && !runnable.socket.isClosed()){ try { runnable.socket.close(); } catch (IOException e) { service.log(e); } } } } /** * An implementation of the checksumming method used by AOL Instant Messenger's * file transfer protocol. */ public final class FileTransferChecksum { /** The checksum of an empty set of data. */ public static final long CHECKSUM_EMPTY = 0xffff0000L; /** The checksum value. */ private long checksum; { // init reset(); } /** * Creates a new file transfer checksum computer object. */ public FileTransferChecksum() { } public void update(int value) { update(new byte[] { (byte) value }, 0, 1); } public void update(final byte[] input, final int offset, final int len) { if (input == null){ return; } assert checksum >= 0; long check = (checksum >> 16) & 0xffffL; for (int i = 0; i < len; i++) { final long oldcheck = check; final int byteVal = input[offset + i] & 0xff; final int val; if ((i & 1) != 0) val = byteVal; else val = byteVal << 8; check -= val; if (check > oldcheck) check--; } check = ((check & 0x0000ffff) + (check >> 16)); check = ((check & 0x0000ffff) + (check >> 16)); checksum = check << 16 & 0xffffffffL; assert checksum >= 0; } public long getValue() { assert checksum >= 0; return checksum; } public void reset() { checksum = CHECKSUM_EMPTY; assert checksum >= 0; } public String toString() { return "FileTransferChecksum: " + checksum; } } }
30.621991
185
0.643288
4a81ae0b90d04cc944f360712fa4c25efb7189bc
7,762
/******************************************************************************* * Copyright (c) 2019 Infostretch Corporation * * 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.qmetry.qaf.automation.ui.webdriver; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.FindBys; import org.openqa.selenium.support.pagefactory.Annotations; import com.qmetry.qaf.automation.core.ConfigurationManager; import com.qmetry.qaf.automation.data.MetaDataScanner; import com.qmetry.qaf.automation.ui.AbstractTestPage; import com.qmetry.qaf.automation.ui.WebDriverTestBase; import com.qmetry.qaf.automation.util.ClassUtil; import com.qmetry.qaf.automation.util.StringUtil; public class ElementFactory { private static final Log logger = LogFactory.getLog(ElementFactory.class); private SearchContext context; public ElementFactory() { context = new WebDriverTestBase().getDriver(); } public ElementFactory(SearchContext context) { this.context = context; } @SuppressWarnings("unchecked") public void initFields(Object classObj) { Field[] flds = ClassUtil.getAllFields(classObj.getClass(), AbstractTestPage.class); for (Field field : flds) { try { field.setAccessible(true); if (isDecoratable(field)) { Object value = null; if (hasAnnotation(field, FindBy.class, FindBys.class)) { Annotations annotations = new Annotations(field); boolean cacheElement = annotations.isLookupCached(); By by = annotations.buildBy(); if (List.class.isAssignableFrom(field.getType())) { value = initList(by, context); } else { if (context instanceof WebElement) { value = new QAFExtendedWebElement((QAFExtendedWebElement) context, by); } else { value = new QAFExtendedWebElement((QAFExtendedWebDriver) context, by, cacheElement); } initMetadata(classObj, field, (QAFExtendedWebElement) value); } } else { com.qmetry.qaf.automation.ui.annotations.FindBy findBy = field .getAnnotation(com.qmetry.qaf.automation.ui.annotations.FindBy.class); if (List.class.isAssignableFrom(field.getType())) { value = initList(field, findBy.locator(), context, classObj); } else { if (QAFWebComponent.class.isAssignableFrom(field.getType())) { value = ComponentFactory.getObject(field.getType(), findBy.locator(), classObj, context); } else { value = $(findBy.locator()); if (context instanceof QAFExtendedWebElement) { ((QAFExtendedWebElement) value).parentElement = (QAFExtendedWebElement) context; } } initMetadata(classObj, field, (QAFExtendedWebElement) value); } } field.set(classObj, value); } } catch (Exception e) { logger.error(e); } } } private void initMetadata(Object classObj, Field field, QAFExtendedWebElement value) { if (null == value) return; value.getMetaData().put("pageClass", classObj.getClass()); value.getMetaData().put("objectName", field.getName()); value.getMetaData().putAll(MetaDataScanner.getMetadata(field)); } private boolean hasAnnotation(Field field, Class<? extends Annotation>... classes) { for (Class<? extends Annotation> cls : classes) { if (field.isAnnotationPresent(cls)) { return true; } } return false; } @SuppressWarnings("unchecked") private boolean isDecoratable(Field field) { if (!hasAnnotation(field, com.qmetry.qaf.automation.ui.annotations.FindBy.class, FindBy.class, FindBys.class)) { return false; } if (WebElement.class.isAssignableFrom(field.getType())) { return true; } if (!(List.class.isAssignableFrom(field.getType()))) { return false; } Type genericType = field.getGenericType(); if (!(genericType instanceof ParameterizedType)) { return false; } Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0]; return WebElement.class.isAssignableFrom((Class<?>) listType); } private Class<?> getListType(Field field) { Type genericType = field.getGenericType(); Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0]; return (Class<?>) listType; } private Object initList(By by, SearchContext context) throws Exception { return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { List.class }, new QAFExtendedWebElementListHandler(context, by)); } @SuppressWarnings("unchecked") private Object initList(Field field, String loc, SearchContext context, Object clsObject) throws Exception { loc = ConfigurationManager.getBundle().getString(loc, loc); Class<? extends QAFExtendedWebElement> cls = (Class<? extends QAFExtendedWebElement>) getListType(field); InvocationHandler iHandler = QAFWebComponent.class.isAssignableFrom(cls) ? new ComponentListHandler(context, loc, cls, clsObject) : new ComponentListHandler(context, loc, getElemenetClass(), clsObject); return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { List.class }, iHandler); } public static QAFWebElement $(String loc) { QAFExtendedWebElement eleToReturn = new QAFExtendedWebElement(loc); String compClass = eleToReturn.getMetaData().containsKey("component-class") ? (String) eleToReturn.getMetaData().get("component-class") : ConfigurationManager.getBundle().getString("default.element.impl"); if (StringUtil.isNotBlank(compClass)) { try { return (QAFWebElement) ComponentFactory.getObject(Class.forName(compClass), loc, null); } catch (Exception e) { logger.error(e); } } return eleToReturn; } @SuppressWarnings("unchecked") public static Class<? extends QAFExtendedWebElement> getElemenetClass(){ try { Class<?> cls = Class.forName(ConfigurationManager.getBundle().getString("default.element.impl", QAFExtendedWebElement.class.getCanonicalName())); return (Class<? extends QAFExtendedWebElement>) cls; } catch (Exception e) { return QAFExtendedWebElement.class; } } }
39.20202
149
0.701366
da23a3cbcdd4f7310c10fe607399c200c6f7a6ee
2,462
/* * Copyright 2017 Pete Cornish * * 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.apiman.cli.util; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.LoggerConfig; /** * Common logging functionality. * * @author Pete Cornish {@literal <[email protected]>} */ public final class LogUtil { /** * Used for printing output to the user; typically this is mapped to stdout. */ public static final Logger OUTPUT = LogManager.getLogger("output"); /** * Platform line separator. */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * Whether to log at debug level. */ private static boolean logDebug; private LogUtil() { } /** * Configure the logging subsystem. * * @param logDebug whether debug logging is enabled */ public static void configureLogging(boolean logDebug) { LogUtil.logDebug = logDebug; final LoggerContext context = (LoggerContext) LogManager.getContext(false); final LoggerConfig rootLogger = context.getConfiguration().getRootLogger(); // remove existing appenders rootLogger.getAppenders().forEach((appenderName, appender) -> rootLogger.removeAppender(appenderName)); final Appender appender; if (logDebug) { rootLogger.setLevel(Level.DEBUG); appender = context.getConfiguration().getAppender("ConsoleVerbose"); } else { appender = context.getConfiguration().getAppender("ConsoleTerse"); } rootLogger.addAppender(appender, null, null); context.updateLoggers(); } public static boolean isLogDebug() { return logDebug; } }
30.395062
111
0.690902
80627c8291bd494bb14c41f8f928942fe354b10c
8,432
/* * * Vear 2017-2018 * 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 jb2.map; import jb2.gai.EntParameters; import jb2.math.FastMath; import jb2.math.Vector3f; import jb2.util.JbException; /** * * @author vear */ public class RouteNode implements Comparable { public NavRoute route; public RouteNode parent; public NavCell node; // current link to reach this node public NavLink linkTo; // estimate cost to target public float estimate; // node cost //public float nodecost; // own cost (depends only on node) //public float linkcost; // cost to this node (depends only on links to this node) //public float prevcost; //public float diminishingPrevcost; // route cost to this node //public float routecost; // queue priority public float cost; // the depth of node, depth is limited to 200 items public int depth; public RouteNode(NavRoute r) { route=r; node = route.start; //setOwncost(dest); // for initial node, own cost is 0 setEstimate(); // no node cost on root //calculateNodeCost(); depth = 0; // for start node, there is no previous cost, just the estimate cost = 0; linkTo= null; parent= null; } public RouteNode(NavRoute r, RouteNode p, NavLink link) { route=r; node = link.to; setEstimate(); parent = p; depth = parent.depth + 1; linkTo = link; cost = getCost(p, link); } protected float getCost(RouteNode newParent, NavLink newLink) { // 25 estimate // 26 estimate offset // 27 link // 28 link offset // 29 node // 30 node offset // 31 parent // 32 parent offset // 33 diminishing parent // 34 diminishing parent offset float newPrev = 0; //float newDimPrev = 0; EntParameters parms = route.bot.navParams; if(newParent!=null) { newPrev = newParent.cost * parms.getParameter(EntParameters.ParamType.PrevCost); } float newLinkCost = 0; if(newLink!=null) { newLinkCost = calculateLinkCost(newLink); } // 1f, // 1 planWeight // 0f, // 2 plan bias (-200 to 200) // 1f, // 3 traversalWeight // 0f, // 4 traversal bias (-200 to 200) // 20f, // 5 deathWeight (0 to 200) // 0f, // 6 death bias (-200 to 200) float nodeCost = FastMath.max(node.getWeight(route.bot.team, 0) * parms.getParameter(EntParameters.ParamType.NodePlan) + parms.getParameter(EntParameters.ParamType.NodePlanBias),0); nodeCost += FastMath.max(node.getWeight(route.bot.team, 1) * parms.getParameter(EntParameters.ParamType.NodeTraversal) + parms.getParameter(EntParameters.ParamType.NodeTraversalBias),0); nodeCost += FastMath.max(node.getWeight(route.bot.team, 2) * parms.getParameter(EntParameters.ParamType.NodeDeath) + parms.getParameter(EntParameters.ParamType.NodeDeathBias),0); // change to estimate only to have something actually working float priority = // FastMath.max(estimate*parms.getParameter(EntParameters.ParamType.PriorityEstimate)+parms.getParameter(EntParameters.ParamType.PriorityEstimateBias),0) // + FastMath.max(newLinkCost*parms.getParameter(EntParameters.ParamType.PriorityLink)+parms.getParameter(EntParameters.ParamType.PriorityLinkBias),0) +FastMath.max(nodeCost*parms.getParameter(EntParameters.ParamType.PriorityNode)+parms.getParameter(EntParameters.ParamType.PriorityNodeBias),0) +FastMath.max(newPrev*parms.getParameter(EntParameters.ParamType.PriorityPrev)+parms.getParameter(EntParameters.ParamType.PriorityPrevBias),0) //+FastMath.max(newDimPrev*parms.getParameter(EntParameters.ParamType.PriorityPrev)+parms.getParameter(EntParameters.ParamType.PriorityPrevBias),0) ; return priority; } protected float calculateLinkCost( NavLink withLink) { if(withLink==null) return 0f; float dist = withLink.from.bounds.center.distance(withLink.to.bounds.center); float manh = withLink.from.bounds.center.manhattanDistance(withLink.to.bounds.center); float heightDist = FastMath.abs(withLink.from.bounds.center.y - withLink.to.bounds.center.y); float diff = manh - dist; // link weights // 7 from 0 distance, 1 manhattan distance // 8 distWeight // 9 height difference weight // 10 height difference bias (-200 to 200) // 11 stuckWeight (0 to 200) // 12 stuck bias (-200 to 200) EntParameters parms = route.bot.navParams; float own=0; // cost of the link as distance own = (dist + diff*parms.getParameter(EntParameters.ParamType.LinkDistanceType)) *parms.getParameter(EntParameters.ParamType.LinkDistance) ; // cost of the link as height own += FastMath.max(heightDist * parms.getParameter(EntParameters.ParamType.LinkHeightDiff) + parms.getParameter(EntParameters.ParamType.LinkHeightDiffBias),0); // if bot was stuck on this route own += FastMath.max(withLink.getAbsBotStuckCount()*parms.getParameter(EntParameters.ParamType.LinkStuck)+parms.getParameter(EntParameters.ParamType.LinkStuckBias),0); return own; } public boolean checkAndSwitch(RouteNode newp, NavLink newLink) { if(node!=newLink.to) { throw new JbException("checkAndSwitch with different node than previously"); } float newCost = getCost(newp, newLink); if(newCost<cost) { if(parent==null) { throw new JbException("checkAndSwitch with root node"); } parent = newp; depth = parent.depth + 1; linkTo = newLink; cost = newCost; return true; } return false; } protected void setEstimate() { // estimate to target area float dist = node.bounds.center.distance(route.targetNode.bounds.center, route.twoD); float manh = node.bounds.center.manhattanDistance(route.targetNode.bounds.center, route.twoD) - dist; EntParameters parms = route.bot.navParams; estimate = dist + (manh * parms.getParameter(EntParameters.ParamType.EstimateDistanceType)); } @Override public int compareTo(Object o) { RouteNode other = (RouteNode) o; int res = Float.compare(cost+estimate, other.cost+other.estimate); if(res == 0) res = Float.compare(estimate, other.estimate); return res; } @Override public int hashCode() { int hash = 3; hash = 41 * hash + this.node.nodeid; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RouteNode other = (RouteNode) obj; if (this.node.nodeid != other.node.nodeid) { return false; } return true; } }
38.153846
194
0.639943
9b958cb9b04ed55e7de4cc32396313e039d71c03
4,899
package com.memrekobak.mqttcontrolapp; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; public class ControlActivity extends AppCompatActivity { MqttClass mqttClass = new MqttClass(ControlActivity.this); private FirebaseAuth mAuth; FragmentClass fragmentClass = new FragmentClass(ControlActivity.this); Button btnSub; Button btnPub; FirebaseFirestore fireDB = FirebaseFirestore.getInstance(); ProgressBar progressBar; @Override public void onBackPressed() { super.onBackPressed(); mqttClass.Disconnect(getApplicationContext()); mAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = mAuth.getCurrentUser(); mqttClass.ManageUsers(); currentUser.delete(); mAuth.signOut(); Intent intent = new Intent(ControlActivity.this, MainActivity.class); startActivity(intent); finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_control); mAuth = FirebaseAuth.getInstance(); if (savedInstanceState == null) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { fragmentClass.ChangeFragment(new InfoFragment()); LayoutName(); progressBar=findViewById(R.id.progressInfo); progressBar.setVisibility(View.INVISIBLE); } }, 1500); } btnPub = findViewById(R.id.btnPublish); btnSub = findViewById(R.id.btnSubscribe); btnPub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragmentClass.ChangeFragment(new PublishFragment()); setTitle("Publish"); } }); btnSub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragmentClass.ChangeFragment(new SubscribeFragment()); setTitle("Subscribe"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) {//menü Bağlantı fonk. MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.cont_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) {//menu if (item.getItemId() == R.id.log_out) { try { mAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = mAuth.getCurrentUser(); mqttClass.ManageUsers(); currentUser.delete(); mAuth.signOut(); Intent intent = new Intent(ControlActivity.this, MainActivity.class); startActivity(intent); finish(); mqttClass.Disconnect(getApplicationContext()); } catch (Exception e) { e.printStackTrace(); } } else if (item.getItemId() == R.id.info) { try { fragmentClass.ChangeFragment(new InfoFragment()); LayoutName(); } catch (Exception e) { e.printStackTrace(); } } return super.onOptionsItemSelected(item); } void LayoutName() { fireDB.collection("Users") .whereEqualTo("UserID", mAuth.getUid()) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { String servername = (String) document.get("ServerName"); setTitle(servername); } } } }); } }
28.988166
88
0.595632
261614560aa26462a5eaf673ff759e21cacc9557
1,306
package org.archive.url; import java.net.URISyntaxException; import junit.framework.TestCase; public class WaybackURLKeyMakerTest extends TestCase { public void testMakeKey() throws URISyntaxException { WaybackURLKeyMaker km = new WaybackURLKeyMaker(); assertEquals("-", km.makeKey(null)); assertEquals("-", km.makeKey("")); assertEquals("dskgfljsdlkgjslkj)/", km.makeKey("dskgfljsdlkgjslkj")); assertEquals("filedesc:foo.arc.gz", km.makeKey("filedesc:foo.arc.gz")); assertEquals("filedesc:/foo.arc.gz", km.makeKey("filedesc:/foo.arc.gz")); assertEquals("filedesc://foo.arc.gz", km.makeKey("filedesc://foo.arc.gz")); assertEquals("warcinfo:foo.warc.gz", km.makeKey("warcinfo:foo.warc.gz")); assertEquals("com,alexa)", km.makeKey("dns:alexa.com")); assertEquals("org,archive)", km.makeKey("dns:archive.org")); assertEquals("org,archive)/", km.makeKey("http://archive.org/")); assertEquals("org,archive)/goo", km.makeKey("http://archive.org/goo/")); assertEquals("org,archive)/goo", km.makeKey("http://archive.org/goo/?")); assertEquals("org,archive)/goo?a&b", km.makeKey("http://archive.org/goo/?b&a")); assertEquals("org,archive)/goo?a=1&a=2&b", km.makeKey("http://archive.org/goo/?a=2&b&a=1")); assertEquals("org,archive)/", km.makeKey("http://archive.org:/")); } }
45.034483
94
0.704441
17929c8b985bdba556c717197ee772dbf34b876b
833
package org.highmed.dsf.fhir.spring.config; import org.highmed.dsf.fhir.help.ExceptionHandler; import org.highmed.dsf.fhir.help.ParameterConverter; import org.highmed.dsf.fhir.help.ResponseGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HelperConfig { @Autowired private PropertiesConfig propertiesConfig; @Bean public ExceptionHandler exceptionHandler() { return new ExceptionHandler(responseGenerator()); } @Bean public ResponseGenerator responseGenerator() { return new ResponseGenerator(propertiesConfig.getServerBaseUrl()); } @Bean public ParameterConverter parameterConverter() { return new ParameterConverter(exceptionHandler()); } }
24.5
68
0.817527
5438e1f0d42066b2fbbafb8b303c2a419ff028ca
5,751
/* * Copyright 2018 tweerlei Wruck + Buchmeier GbR - http://www.tweerlei.de/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tweerlei.common.xml; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import de.tweerlei.common.codec.Base64Codec; import de.tweerlei.common.codec.HexCodec; /** * Basisklasse für SAX-Parser * * @author Robert Wruck */ public abstract class AbstractXMLParser extends DefaultHandler { private static final Pattern DATETIME_PATTERN = Pattern.compile("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}))?(Z|[-+][0-9]{1,2}:[0-9]{1,2})?"); private final boolean nsAware; private final boolean validating; /** * Parst ein xsd:boolean * @param s Wert * @return boolean * @throws RuntimeException, wenn der Wert ungültig ist */ public static boolean parseBoolean(String s) { if (s != null) { if (s.equals("true") || s.equals("1")) return (true); if (s.equals("false") || s.equals("0")) return (false); } throw new RuntimeException("Invalid boolean value: " + s); } /** * Parst ein xsd:decimal * @param s Wert * @return long * @throws RuntimeException, wenn der Wert ungültig ist */ public static double parseDecimal(String s) { if (s != null) { return (Double.parseDouble(s)); } throw new RuntimeException("Invalid decimal value: " + s); } /** * Parst ein xsd:integer * @param s Wert * @return long * @throws RuntimeException, wenn der Wert ungültig ist */ public static long parseInteger(String s) { if (s != null) { return (Long.parseLong(s)); } throw new RuntimeException("Invalid integer value: " + s); } /** * Parst ein xsd:date oder xsd:dateTime * @param s Wert * @return Date * @throws RuntimeException, wenn der Wert ungültig ist */ public static Date parseDate(String s) { if (s != null) { final Matcher m = DATETIME_PATTERN.matcher(s); if (m.matches()) { final Calendar c = Calendar.getInstance(); c.setLenient(false); if (m.group(8) != null) { if (m.group(8).equals("Z")) { c.setTimeZone(TimeZone.getTimeZone("GMT")); } else { c.setTimeZone(TimeZone.getTimeZone("GMT" + m.group(8))); } } c.set(Calendar.YEAR, Integer.parseInt(m.group(1))); c.set(Calendar.MONTH, Calendar.JANUARY + Integer.parseInt(m.group(2)) - 1); c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(3))); if (m.group(4) != null) { c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(5))); c.set(Calendar.MINUTE, Integer.parseInt(m.group(6))); c.set(Calendar.SECOND, Integer.parseInt(m.group(7))); } else { c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); } c.set(Calendar.MILLISECOND, 0); return (c.getTime()); } } throw new RuntimeException("Invalid date or dateTime value: " + s); } /** * Parst ein xsd:hexBinary * @param s Wert * @return Bytes * @throws RuntimeException, wenn der Wert ungültig ist */ public static byte[] parseHexBinary(String s) { if (s != null) { final HexCodec hc = new HexCodec(); try { return (hc.decode(s)); } catch (IOException e) { // Fall through to throw } } throw new RuntimeException("Invalid hexBinary value: " + s); } /** * Parst ein xsd:base64Binary * @param s Wert * @return Bytes * @throws RuntimeException, wenn der Wert ungültig ist */ public static byte[] parseBase64Binary(String s) { if (s != null) { final Base64Codec hc = new Base64Codec(); try { return (hc.decode(s)); } catch (IOException e) { // Fall through to throw } } throw new RuntimeException("Invalid boolean value: " + s); } /** * Konstruktor * @param useNS Namespaces berücksichtigen * @param validate Validieren */ public AbstractXMLParser(boolean useNS, boolean validate) { nsAware = useNS; validating = validate; } private void parse(InputSource s) throws SAXException { try { final SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(nsAware); f.setValidating(validating); final SAXParser p = f.newSAXParser(); p.parse(s, this); } catch (IOException e) { throw new SAXException(e); } catch (ParserConfigurationException e) { throw new SAXException(e); } } /** * Parst einen Datenstrom * @param s Datenstrom * @throws SAXException bei Fehlern */ public void parse(InputStream s) throws SAXException { parse(new InputSource(s)); } /** * Parst einen Datenstrom * @param s Datenstrom * @throws SAXException bei Fehlern */ public void parse(Reader s) throws SAXException { parse(new InputSource(s)); } }
23.764463
177
0.657451
556e1dbab0c281ef9906ce073ceb5cae9659987f
1,719
package com.crypteron.cipherobject.sample; import java.io.IOException; import java.math.BigInteger; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import com.crypteron.Opt; import com.crypteron.Secure; public class Customer { private int id; @Secure(opts = Opt.TOKEN) private BigInteger ssn; private String name; @Secure(opts = Opt.TOKEN) private String cardNumber; @Secure(mask = "6*") private String accountNotes; public int getId() { return id; } public void setId(int id) { this.id = id; } public BigInteger getSsn() { return ssn; } public void setSsn(BigInteger ssn) { this.ssn = ssn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getAccountNotes() { return accountNotes; } public void setAccountNotes(String accountNotes) { this.accountNotes = accountNotes; } @Override public String toString() { ObjectMapper om = new ObjectMapper(); try { return om.writerWithDefaultPrettyPrinter().writeValueAsString(this); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "error"; } }
20.223529
74
0.67772