blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
โ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b02dbcb300a7bd041b7882f16d9eca543a216e46 | 02192ccb01261784f1e7da8a5730ca089152a831 | /src/replit/Giris9.java | d4e170263749e6b15a7ae3b7974ab20d2dd95cbb | []
| no_license | Mustafakonya/JavaPractice | 99e9fb4fd9e1e8c9a34f1c0eaf4bfc0bc0954202 | a15edb739b4e7761680489e0d6aba14a71c2c0de | refs/heads/master | 2022-11-29T15:22:38.234542 | 2020-08-12T16:26:39 | 2020-08-12T16:26:39 | 287,063,065 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,369 | java | package replit;
public class Giris9 {
public static void main(String[] args) {
/*Ekrana Amerika bayraฤฤฑnฤฑ yazdฤฑran Java kodunu yazฤฑnฤฑz.
Beklenen รฤฑktฤฑ:
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
==============================================
==============================================
==============================================
==============================================
==============================================
============================================== */
System.out.println("* * * * * * ==================================" );
System.out.println(" * * * * * ==================================" );
System.out.println("* * * * * * ==================================" );
System.out.println(" * * * * * ==================================" );
System.out.println("* * * * * * ==================================" );
System.out.println(" * * * * * ==================================" );
System.out.println("* * * * * * ==================================" );
System.out.println(" * * * * * ==================================" );
System.out.println("* * * * * * ==================================" );
System.out.println("==============================================" );
System.out.println("==============================================" );
System.out.println("==============================================" );
System.out.println("==============================================" );
System.out.println("==============================================" );
System.out.println("==============================================" );
}
}
| [
"[email protected]"
]
| |
e906fbec68fb0fafa7e4d08e4247999dbb8dded1 | 656ce78b903ef3426f8f1ecdaee57217f9fbc40e | /src/o/_cls1E97.java | 1a0e978ba24a10835e13b54e5abe6408e52a0347 | []
| no_license | zhuharev/periscope-android-source | 51bce2c1b0b356718be207789c0b84acf1e7e201 | 637ab941ed6352845900b9d465b8e302146b3f8f | refs/heads/master | 2021-01-10T01:47:19.177515 | 2015-12-25T16:51:27 | 2015-12-25T16:51:27 | 48,586,306 | 8 | 10 | null | null | null | null | UTF-8 | Java | false | false | 268 | java | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package o;
final class _cls1E97
implements _cls141F.if
{
_cls1E97()
{
}
}
| [
"[email protected]"
]
| |
191011f30e21d87e50d295b87885baa7618c2a7c | e73c76ccca55e4a2283663cc20dc52252afe41d3 | /e3-sso-web/src/main/java/cn/e3mall/sso/controller/RegisterController.java | 5afd9483bf43feef36ad2f51a04fdc6ece436fe0 | []
| no_license | lzmoon392/e3mall | 6c0f2db67ba05a9e606659db7061a544cd94e9e2 | 8423771d2de9529afd28e47a7b23fed7d629795b | refs/heads/master | 2022-12-20T20:16:13.542795 | 2021-04-03T07:25:18 | 2021-04-03T07:25:18 | 251,232,675 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,158 | java | package cn.e3mall.sso.controller;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.sso.service.RegisterService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* @author: jerry
* @create: 2020-04-27 19:32
*/
@Controller
public class RegisterController {
@Resource
private RegisterService registerService;
@RequestMapping("/page/register")
public String register() {
return "register";
}
@RequestMapping("/user/check/{param}/{type}")
@ResponseBody
public E3Result checkData(@PathVariable String param, @PathVariable Integer type) {
return registerService.checkData(param, type);
}
@RequestMapping(value = "/user/register",method = RequestMethod.POST)
@ResponseBody
public E3Result register(TbUser user) {
return registerService.register(user);
}
}
| [
"[email protected]"
]
| |
a9e70abf0a18f5f4bbf8a11f9d82c67d35000121 | 69904e627ab348695b14290670955c567f2df36a | /app/src/main/java/com/jacksonelfersdev/bontaki/MainActivity.java | 34531f8aa3a2edcb69592a11dd77dc08a106c368 | []
| no_license | jackson-elfers/bontaki-android | 50a95c7dcc375367f6810cd0aef318c87df5bfb8 | b7eb7cf9824ee246ef937009f43ee48c312d4738 | refs/heads/master | 2022-08-28T06:37:03.111624 | 2020-05-21T22:16:20 | 2020-05-21T22:16:20 | 263,812,303 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,078 | java | package com.jacksonelfersdev.bontaki;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView mWebView;
@Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
// REMOTE RESOURCE
mWebView.loadUrl("https://bontaki.herokuapp.com");
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
@Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
}
| [
"[email protected]"
]
| |
b2d78ef16efc046f7513abf36c78815c49e77c2e | 54bef2a110947646232d3618435f39fb9698acd3 | /ServerSource/src/game/bruno/game/player/UnitWorker.java | 367cf121898bcc470d15eccd5dfabcd65ddb931b | []
| no_license | bhazero025/Game | d9f0fdf67ab3a5aba286bb67029d5db86f9f792d | fbc47f5da916549a876f7cb0e72a62bac24ee7d6 | refs/heads/master | 2021-01-19T10:06:15.057651 | 2017-07-08T03:48:18 | 2017-07-08T03:48:18 | 82,160,701 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 238 | java | package game.bruno.game.player;
public class UnitWorker extends Unit
{
private static final long serialVersionUID = 1L;
public UnitWorker()
{
this.setAttack(0);
this.setCost(20);
this.setWork(100);
this.setFood(0);
}
}
| [
"[email protected]"
]
| |
d4ed084235669cca6c284e9b3324aa1155ea7d7b | f886ef7640f87b056ad6cc5bbbd8c6033da17710 | /src/edu/harding/acornmaze/OptionsActivity.java | dd7c8bd1a83967ca00f6587ddd500d36fb5f3d70 | []
| no_license | dsebasti/Acorn-Maze | ce1ea25ab9957c8c651388f4d0c8a925c124b77e | 0cffcd20a012f03494095b62e186f6d8802bf72a | refs/heads/master | 2020-04-09T04:14:36.805206 | 2011-11-02T18:07:08 | 2011-11-02T18:07:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 145 | java | package edu.harding.acornmaze;
import android.preference.PreferenceActivity;
public class OptionsActivity extends PreferenceActivity {
}
| [
"[email protected]"
]
| |
1cf857a593c8183d2abff2996a9ee6c04b110924 | 9cb58203d15a86ac8a6fec5e8cfa4876ea38aac7 | /src/main/java/com/framework/PropertiesManager.java | 068e661c9c422790709b0ac48c816b790072ef68 | []
| no_license | tbratanov/Selenium-Maven-Framework | 34ad94f8e19f577f6b6e22909034f48944965688 | a225d46034b9435b70a6f7fc88a51f1fb9aed09a | refs/heads/main | 2023-06-02T20:24:06.858607 | 2021-06-13T10:02:39 | 2021-06-13T10:02:39 | 376,504,776 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,086 | java | package com.framework;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesManager {
public enum PropertiesManagerEnum {
INSTANCE;
private Properties configProperties = null;
private Properties uiMappings = null;
private static final String UI_MAP = "src/test/resources/mappings/ui_map.properties";
private static final String CONFIG_PROPERTIES = "src/test/resources/config.properties";
private static Properties loadProperties(String url) {
Properties props = new Properties();
try {
props.load(new FileInputStream(url));
} catch (IOException ex) {
Utils.LOG.error("Loading properties failed!");
}
return props;
}
public Properties getConfigProperties() {
return configProperties = loadProperties(CONFIG_PROPERTIES);
}
public Properties getUiMappings() {
return uiMappings = loadProperties(UI_MAP);
}
}
}
| [
"[email protected]"
]
| |
e2618d4d03f010509c7c505a1d345a96348ff24e | 0afb02f811bd62f4552bfe0ca953c3261401a753 | /src/com.wuss.leetCode/Main28.java | b89dafc7f5f8563541eb2a66a70f61147561c65c | []
| no_license | wuss12/leetcode | d53874310a3e246bedae86919ac7f5be30937242 | 08ea82f20ff20683599ab024cc8ea836932e0c8e | refs/heads/master | 2021-06-20T00:57:36.987641 | 2021-05-26T10:16:16 | 2021-05-26T10:16:16 | 215,947,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,184 | java | package com.wuss.leetCode;
/**
* ๅฎ็ฐย strStr()ย ๅฝๆฐใ
*
* ็ปๅฎไธไธชย haystack ๅญ็ฌฆไธฒๅไธไธช needle ๅญ็ฌฆไธฒ๏ผๅจ haystack ๅญ็ฌฆไธฒไธญๆพๅบ needle ๅญ็ฌฆไธฒๅบ็ฐ็็ฌฌไธไธชไฝ็ฝฎ (ไป0ๅผๅง)ใๅฆๆไธๅญๅจ๏ผๅ่ฟๅย -1ใ
*
* ็คบไพ 1:
*
* ่พๅ
ฅ: haystack = "hello", needle = "ll"
* ่พๅบ: 2
* ็คบไพ 2:
*
* ่พๅ
ฅ: haystack = "aaaaa", needle = "bba"
* ่พๅบ: -1
*
* ๆฅๆบ๏ผๅๆฃ๏ผLeetCode๏ผ
* ้พๆฅ๏ผhttps://leetcode-cn.com/problems/implement-strstr
* ่ไฝๆๅฝ้ขๆฃ็ฝ็ปๆๆใๅไธ่ฝฌ่ฝฝ่ฏท่็ณปๅฎๆนๆๆ๏ผ้ๅไธ่ฝฌ่ฝฝ่ฏทๆณจๆๅบๅคใ
*/
public class Main28 {
public static int strStr(String haystack, String needle) {
int sorceLen = haystack.length();
int needLen = needle.length();
if (sorceLen < needLen){
return -1;
}
for (int i=0;i<= sorceLen - needLen;i++){
int j=0;
for ( ;j<needLen;j++){
if (haystack.charAt(i+j)!= needle.charAt(j)){
break;
}
}
if (j == needLen){
return i;
}
}
return -1;
}
}
| [
"XdasA2J9zK_sRJfA8HrW"
]
| XdasA2J9zK_sRJfA8HrW |
b5292ce887421510485ab01ae43f5816cdf6f35c | 46952c353f5a6fdc7b517aed380d4424796cd306 | /SELENIUM_PROJECT/src/practic/Synchronization.java | 45b949d14f5990147296e8cce5effcca351959fb | []
| no_license | viper0309/git-mySeleniumJava | db05bfc79e30b340e11a46b6e1900335e12a6919 | 416f0a859a42276310391d32c5f176887fa278a0 | refs/heads/master | 2020-03-19T02:21:10.520361 | 2018-06-02T05:23:05 | 2018-06-02T05:23:05 | 135,621,022 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 829 | java | package practic;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Synchronization {
@Test
public void NegativeTC(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\shreya\\Desktop\\MySeleniumSetup\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1#identifier");
driver.manage().timeouts().implicitlyWait(4000, TimeUnit.SECONDS);
driver.findElement(By.linkText("Create account")).click();
driver.findElement(By.xpath("")).sendKeys("");
driver.findElement(arg0)
}
} | [
"[email protected]"
]
| |
4b5969d8c870283217a37d783050514b4f63ee61 | 99eb51a300fccb7523bcc6017ddaf9fbd48f054b | /omp-mth-productSpecialist/src/main/java/com/meitianhui/productSpecialist/entity/PsCashDailyAccountBuyer.java | 5b84666fb0d58d11f6c4874b0511504cc52fcd4a | []
| no_license | carrieysn/webside-dtgrid1 | e88b2d3fea451f54d75ab7ac1316f8c6dcb0ed9f | 8c686b1cad70d8753451b96839265187734652e0 | refs/heads/master | 2020-05-29T15:10:17.468944 | 2017-06-12T06:07:42 | 2017-06-12T06:07:42 | 63,915,634 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,723 | java | package com.meitianhui.productSpecialist.entity;
import java.io.Serializable;
import java.math.BigDecimal;
/***
* ไนฐๆน็ฐ้ๆฅ่ฎฐ่ดฆ
*
* @author ไธ็ก
* @date 2016ๅนด5ๆ30ๆฅ
*/
public class PsCashDailyAccountBuyer implements Serializable {
private static final long serialVersionUID = -6297303083451984260L;
private String daily_account_id; // ๆฅ่ฎฐ่ดฆๆ ่ฏ
private String buyer_company_id; // ไนฐๅฎถๅ
ฌๅธๆ ่ฏ
private String buyer_id; // ไนฐๅฎถๆ ่ฏ
private String order_no; // ่ฎขๅ็ผๅท
private String order_date; // ่ฎขๅๆฅๆ
private String detail; // ่ฎขๅ่ฏดๆ๏ผๆ่ฆ๏ผ
private BigDecimal amount; // ๅ็้้ข
private String currency_code; // ๅธ็ง็ฌฆๅท๏ผ้ป่ฎคCNY๏ผ
private String account_date; // ไผ่ฎกๆฅๆ
private String booking_mark; // ่ฎฐ่ดฆๆนๅ๏ผๅฏ้ๅผ๏ผ่ฎฐ่ดฆๆนๅ๏ผๅฏ้ๅผ๏ผincome๏ผๆถๅ
ฅ๏ผใexpenditure๏ผๆฏๅบ๏ผ
private String created_date; // ๅๅปบๆฅๆ
private String remark; // ๅคๆณจ
public String getDaily_account_id() {
return daily_account_id;
}
public void setDaily_account_id(String daily_account_id) {
this.daily_account_id = daily_account_id;
}
public String getBuyer_company_id() {
return buyer_company_id;
}
public void setBuyer_company_id(String buyer_company_id) {
this.buyer_company_id = buyer_company_id;
}
public String getBuyer_id() {
return buyer_id;
}
public void setBuyer_id(String buyer_id) {
this.buyer_id = buyer_id;
}
public String getOrder_no() {
return order_no;
}
public void setOrder_no(String order_no) {
this.order_no = order_no;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date = order_date;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency_code() {
return currency_code;
}
public void setCurrency_code(String currency_code) {
this.currency_code = currency_code;
}
public String getAccount_date() {
return account_date;
}
public void setAccount_date(String account_date) {
this.account_date = account_date;
}
public String getBooking_mark() {
return booking_mark;
}
public void setBooking_mark(String booking_mark) {
this.booking_mark = booking_mark;
}
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| [
"[email protected]"
]
| |
a36db476e79f756b5c214a737fad51c9a471b888 | 84a2b5b3b636c07564d449c402b458c4e8ec0760 | /kafka-manager-web/src/main/java/com/xiaojukeji/kafka/manager/web/api/versionone/op/OpClusterTaskController.java | 633258773cad1923e984bdbffac39fc29a9cfb03 | [
"Apache-2.0"
]
| permissive | tcf1207239873/Logi-KafkaManager | 535b663d24c988425ec564fbe072a7910e6c86af | 73e51a888b0c1fcda186e2a08e224e5c1fb80a08 | refs/heads/master | 2023-05-07T02:19:23.776822 | 2021-05-10T09:30:59 | 2021-05-10T09:30:59 | 360,016,146 | 2 | 0 | Apache-2.0 | 2021-06-08T06:55:35 | 2021-04-21T03:03:59 | Java | UTF-8 | Java | false | false | 7,113 | java | package com.xiaojukeji.kafka.manager.web.api.versionone.op;
import com.xiaojukeji.kafka.manager.common.constant.ApiPrefix;
import com.xiaojukeji.kafka.manager.common.constant.Constant;
import com.xiaojukeji.kafka.manager.common.entity.pojo.ClusterDO;
import com.xiaojukeji.kafka.manager.common.entity.pojo.ClusterTaskDO;
import com.xiaojukeji.kafka.manager.common.entity.vo.op.task.*;
import com.xiaojukeji.kafka.manager.kcm.common.entry.ao.ClusterTaskStatus;
import com.xiaojukeji.kafka.manager.kcm.common.bizenum.ClusterTaskTypeEnum;
import com.xiaojukeji.kafka.manager.common.bizenum.KafkaFileEnum;
import com.xiaojukeji.kafka.manager.common.entity.Result;
import com.xiaojukeji.kafka.manager.common.entity.ResultStatus;
import com.xiaojukeji.kafka.manager.kcm.common.entry.dto.ClusterTaskActionDTO;
import com.xiaojukeji.kafka.manager.kcm.common.entry.dto.AbstractClusterTaskDTO;
import com.xiaojukeji.kafka.manager.common.utils.ValidateUtils;
import com.xiaojukeji.kafka.manager.common.entity.pojo.KafkaFileDO;
import com.xiaojukeji.kafka.manager.kcm.ClusterTaskService;
import com.xiaojukeji.kafka.manager.kcm.KafkaFileService;
import com.xiaojukeji.kafka.manager.common.utils.JsonUtils;
import com.xiaojukeji.kafka.manager.common.utils.SpringTool;
import com.xiaojukeji.kafka.manager.service.cache.PhysicalClusterMetadataManager;
import com.xiaojukeji.kafka.manager.service.service.ClusterService;
import com.xiaojukeji.kafka.manager.web.converters.ClusterTaskModelConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author zengqiao
* @date 20/4/26
*/
@Api(tags = "OP-Clusterๅ็บง้จ็ฝฒ็ธๅ
ณๆฅๅฃ(REST)")
@RestController
@RequestMapping(ApiPrefix.API_V1_OP_PREFIX)
public class OpClusterTaskController {
@Autowired
private ClusterService clusterService;
@Autowired
private KafkaFileService kafkaFileService;
@Autowired
private ClusterTaskService clusterTaskService;
@ApiOperation(value = "้็พคไปปๅก็ฑปๅ", notes = "")
@RequestMapping(value = "cluster-tasks/enums", method = RequestMethod.GET)
@ResponseBody
public Result getClusterTaskEnums() {
Map<String, Object> enumMap = new HashMap<>(1);
enumMap.put(AbstractClusterTaskDTO.TASK_TYPE_PROPERTY_FIELD_NAME, JsonUtils.toJson(ClusterTaskTypeEnum.class));
return new Result<>(enumMap);
}
@ApiOperation(value = "ๅๅปบ้็พคไปปๅก", notes = "")
@RequestMapping(value = "cluster-tasks", method = RequestMethod.POST)
@ResponseBody
public Result createTask(@RequestBody AbstractClusterTaskDTO dto) {
dto.setKafkaRoleBrokerHostMap(PhysicalClusterMetadataManager.getKafkaRoleBrokerHostMap(dto.getClusterId()));
dto.setKafkaFileBaseUrl(kafkaFileService.getDownloadBaseUrl());
return clusterTaskService.createTask(dto, SpringTool.getUserName());
}
@ApiOperation(value = "้็พคไปปๅกๅ่กจ", notes = "")
@RequestMapping(value = "cluster-tasks", method = RequestMethod.GET)
@ResponseBody
public Result<List<ClusterTaskVO>> getTaskList() {
List<ClusterTaskDO> doList = clusterTaskService.listAll();
if (ValidateUtils.isNull(doList)) {
return Result.buildFrom(ResultStatus.MYSQL_ERROR);
}
Map<Long, String> clusterNameMap = clusterService.listAll().stream().collect(
Collectors.toMap(ClusterDO::getId, ClusterDO::getClusterName, (key1, key2) -> key2)
);
return new Result<>(ClusterTaskModelConverter.convert2ClusterTaskVOList(doList, clusterNameMap));
}
@ApiOperation(value = "่งฆๅ้็พคไปปๅก", notes = "")
@RequestMapping(value = "cluster-tasks", method = RequestMethod.PUT)
@ResponseBody
public Result executeTask(@RequestBody ClusterTaskActionDTO dto) {
return Result.buildFrom(clusterTaskService.executeTask(dto.getTaskId(), dto.getAction(), dto.getHostname()));
}
@ApiOperation(value = "้็พคไปปๅกๅ
ไฟกๆฏ")
@RequestMapping(value = "cluster-tasks/{taskId}/metadata", method = RequestMethod.GET)
@ResponseBody
public Result<ClusterTaskMetadataVO> getTaskMetadata(@PathVariable Long taskId) {
ClusterTaskDO clusterTaskDO = clusterTaskService.getById(taskId);
if (ValidateUtils.isNull(clusterTaskDO)) {
return Result.buildFrom(ResultStatus.RESOURCE_NOT_EXIST);
}
return new Result<>(ClusterTaskModelConverter.convert2ClusterTaskMetadataVO(
clusterTaskDO,
clusterService.getById(clusterTaskDO.getClusterId()),
kafkaFileService.getFileByFileName(clusterTaskDO.getServerProperties())
));
}
@ApiOperation(value = "้็พคไปปๅก็ถๆ", notes = "ๆดไธชไปปๅก็็ถๆ")
@RequestMapping(value = "cluster-tasks/{taskId}/status", method = RequestMethod.GET)
@ResponseBody
public Result<ClusterTaskStatusVO> getTaskStatus(@PathVariable Long taskId) {
Result<ClusterTaskStatus> dtoResult = clusterTaskService.getTaskStatus(taskId);
if (!Constant.SUCCESS.equals(dtoResult.getCode())) {
return new Result<>(dtoResult.getCode(), dtoResult.getMessage());
}
return new Result<>(ClusterTaskModelConverter.convert2ClusterTaskStatusVO(
dtoResult.getData(),
PhysicalClusterMetadataManager.getBrokerHostKafkaRoleMap(dtoResult.getData().getClusterId())
));
}
@ApiOperation(value = "้็พคไปปๅกๆฅๅฟ", notes = "ๅ
ทไฝๆบๅจ็ๆฅๅฟ")
@RequestMapping(value = "cluster-tasks/{taskId}/log", method = RequestMethod.GET)
@ResponseBody
public Result<String> getTaskLog(@PathVariable Long taskId,
@RequestParam("hostname") String hostname) {
return clusterTaskService.getTaskLog(taskId, hostname);
}
@ApiOperation(value = "ๆไปถ้ๆฉ", notes = "")
@RequestMapping(value = "cluster-tasks/kafka-files", method = RequestMethod.GET)
@ResponseBody
public Result<List<ClusterTaskKafkaFilesVO>> getKafkaFiles(
@RequestParam(value = "clusterId", required = false) Long clusterId) {
List<KafkaFileDO> kafkaFileDOList = kafkaFileService.getKafkaFiles();
if (ValidateUtils.isEmptyList(kafkaFileDOList)) {
return new Result<>();
}
List<ClusterTaskKafkaFilesVO> voList = new ArrayList<>();
for (KafkaFileDO kafkaFileDO: kafkaFileDOList) {
if (KafkaFileEnum.SERVER_CONFIG.getCode().equals(kafkaFileDO.getFileType())
&& !kafkaFileDO.getClusterId().equals(clusterId)) {
continue;
}
ClusterTaskKafkaFilesVO vo = new ClusterTaskKafkaFilesVO();
vo.setFileName(kafkaFileDO.getFileName());
vo.setFileMd5(kafkaFileDO.getFileMd5());
vo.setFileType(kafkaFileDO.getFileType());
voList.add(vo);
}
return new Result<>(voList);
}
} | [
"[email protected]"
]
| |
ca8555be609883c98e421207fccc677ab1c53af9 | 8513848b62758f704bc60d37ec1efd6a863d8636 | /app/src/main/java/com/example/android/ghdirectory/welcomepage.java | 35d5396140c0fbbdbd486a9e94763a1489915cda | []
| no_license | jash9519/reunion | 1ed98f7672eaa162568919b0aaf5f7f67a819ef2 | 52ea8aafc0b469353cc76bbf059e2154f3d0166b | refs/heads/master | 2021-10-28T03:37:55.848036 | 2019-04-21T13:27:44 | 2019-04-21T13:27:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,291 | java | package com.example.android.ghdirectory;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.app.Activity;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
public class welcomepage extends AppCompatActivity {
static EditText search ;
public String searchfinal = "" ;
public String category = "" ;
Spinner spinner;
String[] spinnerValue = {
"Name",
"Blood Group",
"Caste"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcomepage);
spinner =(Spinner)findViewById(R.id.spinner1);
final spinnerAdapter adapter = new spinnerAdapter(welcomepage.this, android.R.layout.simple_list_item_1);
adapter.addAll(spinnerValue);
adapter.add("Select Category");
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount());
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
if(spinner.getSelectedItem() == "Select Category")
{
}
else{
category = spinner.getSelectedItem().toString() ;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
search = findViewById(R.id.searchtext);
}
public void search (View view){
searchfinal = welcomepage.search.getText().toString() ;
Intent in = new Intent(this,results.class);
startActivity(in);
}
public String returncategory (){
return category ;
}
public String returnsearch (){
return searchfinal ;
}
}
| [
"[email protected]"
]
| |
681d9cc5d93c06a078b5b1a4a4a0fe389b478226 | c95b26c2f7dd77f5e30e2d1cd1a45bc1d936c615 | /azureus-core/src/main/java/org/gudy/azureus2/plugins/ui/toolbar/UIToolBarItem.java | e5a00d2410b7a166be228c634985bb1dda360001 | []
| no_license | ostigter/testproject3 | b918764f5c7d4c10d3846411bd9270ca5ba2f4f2 | 2d2336ef19631148c83636c3e373f874b000a2bf | refs/heads/master | 2023-07-27T08:35:59.212278 | 2023-02-22T09:10:45 | 2023-02-22T09:10:45 | 41,742,046 | 2 | 1 | null | 2023-07-07T22:07:12 | 2015-09-01T14:02:08 | Java | UTF-8 | Java | false | false | 2,072 | java | /*
* Copyright (C) Azureus Software, Inc, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.gudy.azureus2.plugins.ui.toolbar;
public interface UIToolBarItem {
public final static long STATE_ENABLED = 0x1;
public static final long STATE_DOWN = 0x2;
/**
* Retrieve the ID of the toolbar item
*
* @since 4.6.0.5
*/
public String getID();
/**
* Return the message bundle ID for the button text
*
* @since 4.6.0.5
*/
public String getTextID();
/**
* Sets the button's text to a messagebundle value looked up using the id
*
* @param id
* @since 4.6.0.5
*/
public void setTextID(String id);
/**
* Get the ID of the image used
*
* @since 4.6.0.5
*/
public String getImageID();
/**
* Sets the toolbar item to use the specified image
*
* @since 4.6.0.5
*/
public void setImageID(String id);
/**
* Returns if the toolbar item is always available (enabled)
*
* @since 4.6.0.5
*/
public boolean isAlwaysAvailable();
public long getState();
public void setState(long state);
public boolean triggerToolBarItem(long activationType, Object datasource);
public void setDefaultActivationListener(UIToolBarActivationListener defaultActivation);
}
| [
"oscar.stigter@e0aef87a-ea4e-0410-81cd-4b1fdc67522b"
]
| oscar.stigter@e0aef87a-ea4e-0410-81cd-4b1fdc67522b |
f6992dfa4c6997e601f85c93ee4e4c7a50537ff9 | bfaee625463c299fe86a5c8544ac5bdcac19ebe0 | /CoreSystemBean/src/main/java/net/alteiar/beans/dice/Dice.java | dd9857bdb7ff976e68c750ff11d6b67a63383b2a | []
| no_license | ligarnes/campaign-player | 671698cd51d3e1321c670f462a9057c298f2e8cb | 810fc29ad07c88a9de767d6051ce3892d9c297aa | refs/heads/master | 2022-06-24T15:13:25.309286 | 2020-01-29T02:11:58 | 2020-01-29T02:11:58 | 32,291,007 | 0 | 0 | null | 2022-05-31T17:19:16 | 2015-03-15T23:59:13 | Java | UTF-8 | Java | false | false | 246 | java | package net.alteiar.beans.dice;
import java.io.Serializable;
import net.alteiar.beans.dice.visitor.DiceVisitor;
public interface Dice extends Serializable {
void roll();
Integer getTotal();
void visit(DiceVisitor visitor);
}
| [
"[email protected]@9b2beeca-6fbb-a3e4-6c1f-7d7f8f7dc6a2"
]
| [email protected]@9b2beeca-6fbb-a3e4-6c1f-7d7f8f7dc6a2 |
363f7ad797c223b01e26d02f688cb245f845fcec | 24c1b951510ab424a11319ed017cefcbad5866bd | /src/main/java/uz/pdp/lesson1vaz2/controller/TaskController.java | fd2776c7db7572ecf4a073b3c186e03c74e71ac6 | []
| no_license | BekhzodDev/Module2Lesson1Task2 | 5a29d07e3c2e2d3e31b470ef265bd1bf7f101324 | 918d7052ee02c34b6a2f442edfbbd70dbeb1db82 | refs/heads/master | 2023-04-18T15:38:41.384968 | 2021-04-26T08:14:31 | 2021-04-26T08:14:31 | 361,395,044 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,622 | java | package uz.pdp.lesson1vaz2.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import uz.pdp.lesson1vaz2.entity.Task;
import uz.pdp.lesson1vaz2.payload.ApiResult;
import uz.pdp.lesson1vaz2.payload.TaskDto;
import uz.pdp.lesson1vaz2.service.TaskService;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/task")
public class TaskController {
@Autowired
TaskService taskService;
@PostMapping
public ResponseEntity<ApiResult> add(@Valid @RequestBody TaskDto taskDto) {
ApiResult add = taskService.add(taskDto);
if (add.isActive()) {
return ResponseEntity.status(202).body(add);
}
return ResponseEntity.status(409).body(add);
}
@GetMapping
public List<Task> getAll() {
List<Task> all = taskService.getAll();
return all;
}
@GetMapping("/{id}")
public Task getOneById(@PathVariable Integer id) {
Task oneById = taskService.getOneById(id);
return oneById;
}
@DeleteMapping("/{id}")
public ResponseEntity<ApiResult> delete(@PathVariable Integer id) {
ApiResult delete = taskService.delete(id);
if (delete.isActive()) {
return ResponseEntity.status(202).body(delete);
}
return ResponseEntity.status(409).body(delete);
}
@PutMapping("/{id}")
public ResponseEntity<ApiResult> edit(@Valid @RequestBody TaskDto taskDto, @PathVariable Integer id) {
ApiResult edit = taskService.edit(id, taskDto);
if (edit.isActive()) {
return ResponseEntity.status(202).body(edit);
}
return ResponseEntity.status(409).body(edit);
}
//for displaying validation message on console
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
}
| [
"[email protected]"
]
| |
030e772e321898beb284443680573b60d6fd8487 | d73abaa749ed95dcd7a0acfdaecbb0171002fac1 | /SpringBootKKVideo70JDBCTemplate/src/main/java/org/shyu/springboot/SpringBootKkVideo70JdbcTemplateApplication.java | addb9105f6a7223bd14e5d00910622c04445ee21 | []
| no_license | JackyShyu/SpringBootKKVideo70JDBCTemplate | e6ed4db1aa7c534d2136845bacf93793aa8fd3f5 | b4ac74b925b8c1045794624c77b2e146275c6e7d | refs/heads/master | 2020-03-30T17:11:52.723525 | 2018-10-03T20:22:11 | 2018-10-03T20:22:11 | 151,425,991 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 832 | java | package org.shyu.springboot;
import org.shyu.springboot.model.Employee;
import org.shyu.springboot.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootKkVideo70JdbcTemplateApplication implements CommandLineRunner {
@Autowired
private EmployeeService employeeService;
public static void main(String[] args) {
SpringApplication.run(SpringBootKkVideo70JdbcTemplateApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Employee employee = new Employee("Mark", "[email protected]", 3000);
employeeService.saveEmployee(employee);
}
}
| [
"[email protected]"
]
| |
69b59b337e0e4873ff61adc23df95954e452eeb0 | 5b23d3c0af4784cfb1fd752bc4b25cc0f68ad2a1 | /cracking-the-coding-interview/concepts-and-algorithms/recursion-and-dynamic-programming/src/test/java/com/ashish/ParenthesisTest.java | a687a6db635d5fb4626cdadeaeb0fef58be1ea6d | [
"MIT"
]
| permissive | ashiishsharma/PracticeCode | 1a5df660ce1c7a6ef888c1e56e526eb6850cbd58 | 9afe57deb45e8446904227dc6e51fad21de82dd6 | refs/heads/master | 2022-12-22T02:13:15.402952 | 2021-06-12T16:53:31 | 2021-06-12T16:53:31 | 54,332,747 | 0 | 0 | MIT | 2022-12-10T01:22:43 | 2016-03-20T18:12:32 | Java | UTF-8 | Java | false | false | 1,072 | java | package com.ashish;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Set;
/**
* <B>Cracking The Coding Interview : Edition : 6</B>
* <p>
* 8.9
* <p>
* <B>Parens:</B>
* <p>
* Implement an algorithm to print all valid (i.e., properly opened and closed) combinations
* of n pairs of parentheses.
* EXAMPLE
* Input: 3
* Output: (( () ) ) , ( () () ) , ( () ) () , () ( () ) , () () ()
*
* @author Ashish Sharma on 03/05/2019.
* @since 03/05/2019.
*/
public class ParenthesisTest {
private Parenthesis parenthesis;
@BeforeMethod
public void init() {
parenthesis = new Parenthesis();
}
@Test
public void testParenthesis() {
Set parenthesisSet = parenthesis.generateParens(4);
parenthesisSet.forEach(str -> System.out.println(str));
}
@Test
public void testParenthesisEfficient() {
List parenthesisList = parenthesis.generateParensEfficient(4);
parenthesisList.forEach(str -> System.out.println(str));
}
}
| [
"[email protected]"
]
| |
af5d43def595d6e07965a43fd5298e3aa3071f6e | e5aeb6a09cf0ca868ab175966282db6c5c4811db | /blog-web/src/main/java/com/kangyonggan/blog/web/shiro/HasAnyRolesTag.java | 10e16f6420668871a06143f84f0fddf60d200572 | []
| no_license | kangyonggan/blog-back | 05faee91d480b9e285726d3ce2f278fba337b31e | 6ba513cdf8126154cb23eb489a43ea59c779df78 | refs/heads/master | 2021-03-27T17:17:50.657633 | 2017-01-24T14:44:44 | 2017-01-24T14:44:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,755 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.kangyonggan.blog.web.shiro;
import org.apache.shiro.subject.Subject;
/**
* Displays body content if the current user has any of the roles specified.
*
* <p>Equivalent to {@link org.apache.shiro.web.tags.HasAnyRolesTag}</p>
*
* @since 0.2
*/
public class HasAnyRolesTag extends RoleTag {
// Delimeter that separates role names in tag attribute
private static final String ROLE_NAMES_DELIMETER = ",";
protected boolean showTagBody(String roleNames) {
boolean hasAnyRole = false;
Subject subject = getSubject();
if (subject != null) {
// Iterate through roles and check to see if the user has one of the roles
for (String role : roleNames.split(ROLE_NAMES_DELIMETER)) {
if (subject.hasRole(role.trim())) {
hasAnyRole = true;
break;
}
}
}
return hasAnyRole;
}
} | [
"[email protected]"
]
| |
03ce1c5cecaf6235061b4181ed9f64151ee9368d | 1dae85d4c7a529395ba3a83b84152d5309bd89ad | /src/test/java/com/nilhcem/clearbrain/business/QuickMemoBoTest.java | 1564aa40ad259291127687c32836ddf2d1753e94 | []
| no_license | canwe/clearbrain | 1c21862913e687a2fab3f1f5625863fb23537412 | f3e42aad2b3c6f23e3dfa35f4c4770ce84b0f7a8 | refs/heads/master | 2020-12-14T08:54:04.393189 | 2014-09-30T13:56:08 | 2014-09-30T13:56:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,417 | java | package com.nilhcem.clearbrain.business;
import static org.junit.Assert.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.nilhcem.clearbrain.core.hibernate.TransactionalReadWrite;
import com.nilhcem.clearbrain.core.test.abstr.AbstractDbTest;
import com.nilhcem.clearbrain.dao.UserDao;
import com.nilhcem.clearbrain.model.QuickMemo;
import com.nilhcem.clearbrain.model.User;
public class QuickMemoBoTest extends AbstractDbTest {
private static final String DEFAULT_CONTENT = "";
private static final String NEW_CONTENT = "Hey, this is my <br /> new content";
@Autowired
private QuickMemoBo memoBo;
@Autowired
private LanguageBo langBo;
@Autowired
private UserDao userDao;
@Test
@TransactionalReadWrite
public void testGetByUser() {
// A quick memo is created when a user is created
User user = testUtils.createTestUser("QuickMemoBoTest@testGetByUser");
QuickMemo memo = memoBo.getByUser(user);
assertNotNull(memo);
}
@Test
@TransactionalReadWrite
public void testCreateQuickMemo() {
// Create a user manually (without memo)
User user = new User();
user.setEmail("QuickMemoBoTest@UntakenEmail");
user.setPassword("");
user.setLanguage(langBo.findByLocale(new Locale("en", "US")));
user.setRegistrationDate(Calendar.getInstance().getTime());
userDao.save(user);
// Create a quick memo
memoBo.createQuickMemo(user);
QuickMemo memo = memoBo.getByUser(user);
assertEquals(QuickMemoBoTest.DEFAULT_CONTENT, memo.getContent());
assertNull(memo.getSaveDate()); // Save date should be null when a memo is created
assertEquals(user.getId(), memo.getUser().getId());
}
@Test
@TransactionalReadWrite
public void testUpdateMemo() {
User user = testUtils.createTestUser("QuickMemoBoTest@testUpdateMemo");
QuickMemo memo = memoBo.getByUser(user);
assertFalse(QuickMemoBoTest.NEW_CONTENT.equals(memo.getContent()));
// Update memo
Date before = testUtils.getDateBeforeTest();
memoBo.updateMemo(user, QuickMemoBoTest.NEW_CONTENT);
Date after = testUtils.getDateAfterTest();
// Test updated values
QuickMemo updatedMemo = memoBo.getByUser(user);
assertEquals(NEW_CONTENT, updatedMemo.getContent());
assertEquals(memo.getId(), updatedMemo.getId());
testUtils.checkDateBetween(updatedMemo.getSaveDate(), before, after);
}
}
| [
"[email protected]"
]
| |
105bff59790d0633edbd954cc88eda7563251e4a | f5bcc663b2170584af387602aa260f71c770fd3c | /notification-service/src/main/java/com/stackroute/notificationservice/controllers/WebSocketController.java | be324b9fe6ca9fa6aa7930bf438a9ec96d6af01d | [
"Apache-2.0"
]
| permissive | stackroute/ibm-wave3-plasma-hackathon | a28f44086e40440c17943ee78372e7acf84bd100 | e6aca83d3292770107cc46e898e1a6bd9840bdda | refs/heads/master | 2020-04-24T14:49:03.637881 | 2019-02-22T10:44:25 | 2019-02-22T10:44:25 | 172,025,637 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 896 | java | package com.stackroute.notificationservice.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin("*")
public class WebSocketController {
private final SimpMessagingTemplate template;
@Autowired
WebSocketController(SimpMessagingTemplate template) {
this.template = template;
}
@MessageMapping("/data")
public void onReceivedName(String data) throws Exception {
// System.out.println("JSON format " + user);
System.out.println("Data coming from particular topic " + data);
this.template.convertAndSend("/topic", data );
}
} | [
"[email protected]"
]
| |
8c4b3a5def52ee92c51ab89c6d1c998f2c4d9c04 | 29f12706d3d7e8db50cd93414393b7861006a3b2 | /src/main/java/com/shoumipay/domain/GoodsCostsExample.java | dc8c21581a419802a57d75d6922351edc963fc4e | []
| no_license | chengyezhao/duolafu | 35492cbd17a69079f97aa490d507fe6bf130181b | 3070f131e44894cf0902f68228bae24d53b4a492 | refs/heads/master | 2020-03-21T21:49:45.585709 | 2018-06-29T01:43:16 | 2018-06-29T01:43:16 | 139,087,090 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 27,350 | java | package com.shoumipay.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class GoodsCostsExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public GoodsCostsExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andGoodsidIsNull() {
addCriterion("goodsId is null");
return (Criteria) this;
}
public Criteria andGoodsidIsNotNull() {
addCriterion("goodsId is not null");
return (Criteria) this;
}
public Criteria andGoodsidEqualTo(Long value) {
addCriterion("goodsId =", value, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidNotEqualTo(Long value) {
addCriterion("goodsId <>", value, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidGreaterThan(Long value) {
addCriterion("goodsId >", value, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidGreaterThanOrEqualTo(Long value) {
addCriterion("goodsId >=", value, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidLessThan(Long value) {
addCriterion("goodsId <", value, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidLessThanOrEqualTo(Long value) {
addCriterion("goodsId <=", value, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidIn(List<Long> values) {
addCriterion("goodsId in", values, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidNotIn(List<Long> values) {
addCriterion("goodsId not in", values, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidBetween(Long value1, Long value2) {
addCriterion("goodsId between", value1, value2, "goodsid");
return (Criteria) this;
}
public Criteria andGoodsidNotBetween(Long value1, Long value2) {
addCriterion("goodsId not between", value1, value2, "goodsid");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(Integer value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(Integer value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(Integer value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(Integer value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(Integer value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(Integer value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<Integer> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<Integer> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(Integer value1, Integer value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(Integer value1, Integer value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andBillingMethodsIsNull() {
addCriterion("billing_Methods is null");
return (Criteria) this;
}
public Criteria andBillingMethodsIsNotNull() {
addCriterion("billing_Methods is not null");
return (Criteria) this;
}
public Criteria andBillingMethodsEqualTo(Integer value) {
addCriterion("billing_Methods =", value, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsNotEqualTo(Integer value) {
addCriterion("billing_Methods <>", value, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsGreaterThan(Integer value) {
addCriterion("billing_Methods >", value, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsGreaterThanOrEqualTo(Integer value) {
addCriterion("billing_Methods >=", value, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsLessThan(Integer value) {
addCriterion("billing_Methods <", value, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsLessThanOrEqualTo(Integer value) {
addCriterion("billing_Methods <=", value, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsIn(List<Integer> values) {
addCriterion("billing_Methods in", values, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsNotIn(List<Integer> values) {
addCriterion("billing_Methods not in", values, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsBetween(Integer value1, Integer value2) {
addCriterion("billing_Methods between", value1, value2, "billingMethods");
return (Criteria) this;
}
public Criteria andBillingMethodsNotBetween(Integer value1, Integer value2) {
addCriterion("billing_Methods not between", value1, value2, "billingMethods");
return (Criteria) this;
}
public Criteria andCostIsNull() {
addCriterion("cost is null");
return (Criteria) this;
}
public Criteria andCostIsNotNull() {
addCriterion("cost is not null");
return (Criteria) this;
}
public Criteria andCostEqualTo(BigDecimal value) {
addCriterion("cost =", value, "cost");
return (Criteria) this;
}
public Criteria andCostNotEqualTo(BigDecimal value) {
addCriterion("cost <>", value, "cost");
return (Criteria) this;
}
public Criteria andCostGreaterThan(BigDecimal value) {
addCriterion("cost >", value, "cost");
return (Criteria) this;
}
public Criteria andCostGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("cost >=", value, "cost");
return (Criteria) this;
}
public Criteria andCostLessThan(BigDecimal value) {
addCriterion("cost <", value, "cost");
return (Criteria) this;
}
public Criteria andCostLessThanOrEqualTo(BigDecimal value) {
addCriterion("cost <=", value, "cost");
return (Criteria) this;
}
public Criteria andCostIn(List<BigDecimal> values) {
addCriterion("cost in", values, "cost");
return (Criteria) this;
}
public Criteria andCostNotIn(List<BigDecimal> values) {
addCriterion("cost not in", values, "cost");
return (Criteria) this;
}
public Criteria andCostBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("cost between", value1, value2, "cost");
return (Criteria) this;
}
public Criteria andCostNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("cost not between", value1, value2, "cost");
return (Criteria) this;
}
public Criteria andCollectingMethodsIsNull() {
addCriterion("collecting_Methods is null");
return (Criteria) this;
}
public Criteria andCollectingMethodsIsNotNull() {
addCriterion("collecting_Methods is not null");
return (Criteria) this;
}
public Criteria andCollectingMethodsEqualTo(Integer value) {
addCriterion("collecting_Methods =", value, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsNotEqualTo(Integer value) {
addCriterion("collecting_Methods <>", value, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsGreaterThan(Integer value) {
addCriterion("collecting_Methods >", value, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsGreaterThanOrEqualTo(Integer value) {
addCriterion("collecting_Methods >=", value, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsLessThan(Integer value) {
addCriterion("collecting_Methods <", value, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsLessThanOrEqualTo(Integer value) {
addCriterion("collecting_Methods <=", value, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsIn(List<Integer> values) {
addCriterion("collecting_Methods in", values, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsNotIn(List<Integer> values) {
addCriterion("collecting_Methods not in", values, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsBetween(Integer value1, Integer value2) {
addCriterion("collecting_Methods between", value1, value2, "collectingMethods");
return (Criteria) this;
}
public Criteria andCollectingMethodsNotBetween(Integer value1, Integer value2) {
addCriterion("collecting_Methods not between", value1, value2, "collectingMethods");
return (Criteria) this;
}
public Criteria andSettlementModelIsNull() {
addCriterion("settlement_Model is null");
return (Criteria) this;
}
public Criteria andSettlementModelIsNotNull() {
addCriterion("settlement_Model is not null");
return (Criteria) this;
}
public Criteria andSettlementModelEqualTo(Integer value) {
addCriterion("settlement_Model =", value, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelNotEqualTo(Integer value) {
addCriterion("settlement_Model <>", value, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelGreaterThan(Integer value) {
addCriterion("settlement_Model >", value, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelGreaterThanOrEqualTo(Integer value) {
addCriterion("settlement_Model >=", value, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelLessThan(Integer value) {
addCriterion("settlement_Model <", value, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelLessThanOrEqualTo(Integer value) {
addCriterion("settlement_Model <=", value, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelIn(List<Integer> values) {
addCriterion("settlement_Model in", values, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelNotIn(List<Integer> values) {
addCriterion("settlement_Model not in", values, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelBetween(Integer value1, Integer value2) {
addCriterion("settlement_Model between", value1, value2, "settlementModel");
return (Criteria) this;
}
public Criteria andSettlementModelNotBetween(Integer value1, Integer value2) {
addCriterion("settlement_Model not between", value1, value2, "settlementModel");
return (Criteria) this;
}
public Criteria andB2bModelIsNull() {
addCriterion("B2B_Model is null");
return (Criteria) this;
}
public Criteria andB2bModelIsNotNull() {
addCriterion("B2B_Model is not null");
return (Criteria) this;
}
public Criteria andB2bModelEqualTo(Integer value) {
addCriterion("B2B_Model =", value, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelNotEqualTo(Integer value) {
addCriterion("B2B_Model <>", value, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelGreaterThan(Integer value) {
addCriterion("B2B_Model >", value, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelGreaterThanOrEqualTo(Integer value) {
addCriterion("B2B_Model >=", value, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelLessThan(Integer value) {
addCriterion("B2B_Model <", value, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelLessThanOrEqualTo(Integer value) {
addCriterion("B2B_Model <=", value, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelIn(List<Integer> values) {
addCriterion("B2B_Model in", values, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelNotIn(List<Integer> values) {
addCriterion("B2B_Model not in", values, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelBetween(Integer value1, Integer value2) {
addCriterion("B2B_Model between", value1, value2, "b2bModel");
return (Criteria) this;
}
public Criteria andB2bModelNotBetween(Integer value1, Integer value2) {
addCriterion("B2B_Model not between", value1, value2, "b2bModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelIsNull() {
addCriterion("P2P_Direct_Model is null");
return (Criteria) this;
}
public Criteria andP2pDirectModelIsNotNull() {
addCriterion("P2P_Direct_Model is not null");
return (Criteria) this;
}
public Criteria andP2pDirectModelEqualTo(Integer value) {
addCriterion("P2P_Direct_Model =", value, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelNotEqualTo(Integer value) {
addCriterion("P2P_Direct_Model <>", value, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelGreaterThan(Integer value) {
addCriterion("P2P_Direct_Model >", value, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelGreaterThanOrEqualTo(Integer value) {
addCriterion("P2P_Direct_Model >=", value, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelLessThan(Integer value) {
addCriterion("P2P_Direct_Model <", value, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelLessThanOrEqualTo(Integer value) {
addCriterion("P2P_Direct_Model <=", value, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelIn(List<Integer> values) {
addCriterion("P2P_Direct_Model in", values, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelNotIn(List<Integer> values) {
addCriterion("P2P_Direct_Model not in", values, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelBetween(Integer value1, Integer value2) {
addCriterion("P2P_Direct_Model between", value1, value2, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pDirectModelNotBetween(Integer value1, Integer value2) {
addCriterion("P2P_Direct_Model not between", value1, value2, "p2pDirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelIsNull() {
addCriterion("P2P_Indirect_Model is null");
return (Criteria) this;
}
public Criteria andP2pIndirectModelIsNotNull() {
addCriterion("P2P_Indirect_Model is not null");
return (Criteria) this;
}
public Criteria andP2pIndirectModelEqualTo(Integer value) {
addCriterion("P2P_Indirect_Model =", value, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelNotEqualTo(Integer value) {
addCriterion("P2P_Indirect_Model <>", value, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelGreaterThan(Integer value) {
addCriterion("P2P_Indirect_Model >", value, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelGreaterThanOrEqualTo(Integer value) {
addCriterion("P2P_Indirect_Model >=", value, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelLessThan(Integer value) {
addCriterion("P2P_Indirect_Model <", value, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelLessThanOrEqualTo(Integer value) {
addCriterion("P2P_Indirect_Model <=", value, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelIn(List<Integer> values) {
addCriterion("P2P_Indirect_Model in", values, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelNotIn(List<Integer> values) {
addCriterion("P2P_Indirect_Model not in", values, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelBetween(Integer value1, Integer value2) {
addCriterion("P2P_Indirect_Model between", value1, value2, "p2pIndirectModel");
return (Criteria) this;
}
public Criteria andP2pIndirectModelNotBetween(Integer value1, Integer value2) {
addCriterion("P2P_Indirect_Model not between", value1, value2, "p2pIndirectModel");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | [
"[email protected]"
]
| |
ef91246f925c2ef5c329ef238265021788cb6ed6 | 66040a4d06bdf82241583c7065ca835713e78546 | /Code/ftc_app/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OPAutoCenterPark.java | f3929dde9013b2cd3578d3838bc24a28d9e2f7aa | [
"BSD-3-Clause"
]
| permissive | DisgruntledRobots/FTC2016-17 | 1ad374ecb01b986798cd2168812c451ba2afaf47 | 4690d56a99b180f446830747cb33b0f23de5a2a6 | refs/heads/master | 2021-06-13T01:00:25.078108 | 2017-02-18T03:38:25 | 2017-02-18T03:38:25 | 76,076,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,845 | java | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
/*
* This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either
* the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu
* of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode
* class is instantiated on the roberto Controller and executed.
*
* This particular OpMode just executes a basic Tank Drive Teleop for a PushBot
* It includes all the skeletal structure that all linear OpModes contain.
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@Autonomous(name="Test OPAutoCenterPark", group="Linear Opmode") // @Autonomous(...) is the other common choice
//@Disabled
public class OPAutoCenterPark extends LinearOpMode {
/* Declare OpMode members. */
HardwareTestbot roberto = new HardwareTestbot(); // Use a Pushbot's hardware
private ElapsedTime runtime = new ElapsedTime();
static final double COUNTS_PER_MOTOR_REV = 1120 ; // eg: TETRIX Motor Encoder
static final double WHEEL_DIAMETER_INCHES = 4.0 ; // For figuring circumference
static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV) /
(WHEEL_DIAMETER_INCHES * 3.1415);
static final double DRIVE_SPEED = 0.6;
static final double TURN_SPEED = 0.5;
@Override
public void runOpMode() throws InterruptedException {
/*
* Initialize the drive system variables.
* The init() method of the hardware class does all the work here
*/
roberto.init(hardwareMap);
// Send telemetry message to signify roberto waiting;
telemetry.addData("Status", "Resetting Encoders"); //
telemetry.update();
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
idle();
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// Send telemetry message to indicate successful Encoder reset
telemetry.addData("Path0", "Starting at %7d :%7d",
roberto.driveMotorFrontLeft.getCurrentPosition(),
roberto.driveMotorFrontRight.getCurrentPosition(),
roberto.driveMotorBackRight.getCurrentPosition(),
roberto.driveMotorBackLeft.getCurrentPosition());
telemetry.update();
// Wait for the game to start (driver presses PLAY)
waitForStart();
/*Step through each leg of the path,
Note: Reverse movement is obtained by setting a negative distance (not speed)
encoderStrafeDrive(DRIVE_SPEED, (double)15);*/
// encoderDrive(DRIVE_SPEED,-40,-40,10);
//turnLeft(12);
encoderDrive(DRIVE_SPEED,-38,-38,10);
shootBall((-.65*0.55), 5);
encoderDrive(DRIVE_SPEED,-30,-30,10);
// roberto.leftClaw.setPosition(1.0); // S4: Stop and close the claw.
// roberto.rightClaw.setPosition(0.0);
// sleep(1000); // pause for servos to move
telemetry.addData("Path", "Complete");
telemetry.update();
}
/*
* Method to perform a relative move, based on encoder counts.
* Encoders are not reset as the move is based on the current position.
* Move will stop if any of three conditions occur:
* 1) Move gets to the desired position
* 2) Move runs out of time
* 3) Driver stops the opmode running.
*/
public void encoderDrive(double speed,double leftInches, double rightInches,double timeoutS) throws InterruptedException {
int newLeftTarget;
int newRightTarget;
// Ensure that the opmode is still active
if (opModeIsActive()) {
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// Determine new target position, and pass to motor controller
newLeftTarget = roberto.driveMotorFrontLeft.getCurrentPosition() + (int)(leftInches * COUNTS_PER_INCH);
newRightTarget = roberto.driveMotorFrontRight.getCurrentPosition() + (int)(rightInches * COUNTS_PER_INCH);
// newRightTarget = roberto.driveMotorBackRight.getCurrentPosition() + (int)(rightInches * COUNTS_PER_INCH);
// newLeftTarget = roberto.driveMotorBackLeft.getCurrentPosition() + (int)(leftInches * COUNTS_PER_INCH);
roberto.driveMotorFrontLeft.setTargetPosition(newLeftTarget);
roberto.driveMotorFrontRight.setTargetPosition(newRightTarget);
roberto.driveMotorBackRight.setTargetPosition(newRightTarget);
roberto.driveMotorBackLeft.setTargetPosition(newLeftTarget);
// Turn On RUN_TO_POSITION
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.RUN_TO_POSITION);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.RUN_TO_POSITION);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.RUN_TO_POSITION);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// reset the timeout time and start motion.
runtime.reset();
roberto.driveMotorFrontLeft.setPower(Math.abs(speed));
roberto.driveMotorFrontRight.setPower(Math.abs(speed));
roberto.driveMotorBackRight.setPower(Math.abs(speed));
roberto.driveMotorBackLeft.setPower(Math.abs(speed));
// keep looping while we are still active, and there is time left, and both motors are running.
while (opModeIsActive() &&
(runtime.seconds() < timeoutS) &&
( roberto.driveMotorFrontLeft.isBusy() &&
roberto.driveMotorFrontRight.isBusy()&&
roberto.driveMotorBackRight.isBusy() &&
roberto.driveMotorBackLeft.isBusy())) {
// Display it for the driver.
telemetry.addData("Path1", "Running to %7d :%7d", newLeftTarget, newRightTarget);
telemetry.addData("Path2", "Running at %7d :%7d",
roberto.driveMotorFrontLeft.getCurrentPosition(),
roberto.driveMotorFrontRight.getCurrentPosition(),
roberto.driveMotorBackRight.getCurrentPosition(),
roberto.driveMotorBackLeft.getCurrentPosition());
telemetry.update();
// Allow time for other processes to run.
idle();
}
// Stop all motion;
roberto.driveMotorFrontLeft.setPower(0);
roberto.driveMotorFrontRight.setPower(0);
roberto.driveMotorBackRight.setPower(0);
roberto.driveMotorBackLeft.setPower(0);
// Turn off RUN_TO_POSITION
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// sleep(250); // optional pause after each move
}
}
public void shootBall(double speed, double timeoutS){
if (opModeIsActive()) {
runtime.reset();
while (opModeIsActive() && (runtime.seconds() < timeoutS)){
roberto.leftFlywheelMotor.setPower(speed);
roberto.rightFlywheelMotor.setPower(speed);
roberto.throatMotor.setPower(1);
}
roberto.leftFlywheelMotor.setPower(0);
roberto.rightFlywheelMotor.setPower(0);
roberto.throatMotor.setPower(0);
}
}
public void encoderStrafeDrive(double speed,double strafeDistance) {
//strafeDistance should be positive for left and negative for right
/* roberto.driveMotorFrontRight.setPower(strafeDistance);
roberto.driveMotorFrontLeft.setPower(-strafeDistance);
roberto.driveMotorBackLeft.setPower(strafeDistance);
roberto.driveMotorBackRight.setPower(-strafeDistance);
*/
int newTarget;
// Ensure that the opmode is still active
if (opModeIsActive()) {
// Determine new target position, and pass to motor controller
newTarget = roberto.driveMotorFrontLeft.getCurrentPosition() + (int) (strafeDistance * COUNTS_PER_INCH);
// newTarget = roberto.driveMotorFrontRight.getCurrentPosition() + (int) (rightInches * COUNTS_PER_INCH);
// newTarget = roberto.driveMotorBackRight.getCurrentPosition() + (int)(rightInches * COUNTS_PER_INCH);
// newTarget = roberto.driveMotorBackLeft.getCurrentPosition() + (int)(leftInches * COUNTS_PER_INCH);
roberto.driveMotorFrontLeft.setTargetPosition(-newTarget);
roberto.driveMotorFrontRight.setTargetPosition(newTarget);
roberto.driveMotorBackRight.setTargetPosition(-newTarget);
roberto.driveMotorBackLeft.setTargetPosition(newTarget);
// Turn On RUN_TO_POSITION
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.RUN_TO_POSITION);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.RUN_TO_POSITION);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.RUN_TO_POSITION);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// reset the timeout time and start motion.
runtime.reset();
roberto.driveMotorFrontLeft.setPower(Math.abs(speed));
roberto.driveMotorFrontRight.setPower(Math.abs(speed));
roberto.driveMotorBackRight.setPower(Math.abs(speed));
roberto.driveMotorBackLeft.setPower(Math.abs(speed));
// keep looping while we are still active, and there is time left, and both motors are running.
while (opModeIsActive() &&
(roberto.driveMotorFrontLeft.isBusy() &&
roberto.driveMotorFrontRight.isBusy() &&
roberto.driveMotorBackRight.isBusy() &&
roberto.driveMotorBackLeft.isBusy())) {
// Display it for the driver.
telemetry.addData("Path1", "Running to %7d :%7d", strafeDistance);
telemetry.addData("Path2", "Running at %7d :%7d",
roberto.driveMotorFrontLeft.getCurrentPosition(),
roberto.driveMotorFrontRight.getCurrentPosition(),
roberto.driveMotorBackRight.getCurrentPosition(),
roberto.driveMotorBackLeft.getCurrentPosition());
telemetry.update();
// Allow time for other processes to run.
}
// Stop all motion;
roberto.driveMotorFrontLeft.setPower(0);
roberto.driveMotorFrontRight.setPower(0);
roberto.driveMotorBackRight.setPower(0);
roberto.driveMotorBackLeft.setPower(0);
// Turn off RUN_TO_POSITION
roberto.driveMotorFrontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorFrontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
roberto.driveMotorBackLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// sleep(250); // optional pause after each move
}
}
public void turnLeft(float inches) {
/*
call encoderDrive to turn to the left
Order of parameters:
double speed,double leftInches, double rightInches,double timeoutS
*/
try {
encoderDrive(TURN_SPEED, -inches, inches, 10.0); // S2: turn towards the first beacon
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}
public void turnRight(float inches) {
/*
call encoderDrive to turn to the right
*/
try {
encoderDrive(TURN_SPEED, inches, -inches, 10.0); // S2: turn towards the first beacon
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}
} | [
"[email protected]"
]
| |
2d4ac181244f7c8cba9753c785743cea3d53d062 | 69ff15c9fb4d431d6e6f439155b7b71e86502129 | /src/main/java/ru/develom/bot/MyBot.java | 9e8779040568bf2ce07a8a5b072847bc6c888255 | []
| no_license | qwerudu008/LongPollBot_VK_Java | 0af90e04fe28f93c88be9f92661fc722e9aa1b88 | 336c83e7276a19575fbdbc63afdb2855fa9b6f65 | refs/heads/master | 2023-03-28T12:09:19.980908 | 2021-03-25T20:20:20 | 2021-03-25T20:20:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,783 | java | package ru.develom.bot;
import api.longpoll.bots.BotsLongPoll;
import api.longpoll.bots.LongPollBot;
import api.longpoll.bots.exceptions.BotsLongPollException;
import api.longpoll.bots.exceptions.BotsLongPollHttpException;
import api.longpoll.bots.methods.messages.MessagesSend;
import api.longpoll.bots.model.events.messages.MessageNewEvent;
import api.longpoll.bots.model.objects.additional.Button;
import api.longpoll.bots.model.objects.additional.Keyboard;
import api.longpoll.bots.model.objects.basic.Message;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MyBot extends LongPollBot {
@Override
public void onMessageNew(MessageNewEvent messageNewEvent) {
Message message = messageNewEvent.getMessage();
Date date = new Date();
if (message.getText().toUpperCase().equals("ะะ ะะะฏ")) {
try {
new MessagesSend(this)
.setPeerId(message.getPeerId())
.setMessage("ะัะตะผั ะฝะฐ ัะตัะฒะตัะต: "+date.toString())
.execute();
} catch ( BotsLongPollHttpException | BotsLongPollException e) {
e.printStackTrace();
}
}
else if (message.getText().toUpperCase().equals("ะะะคะ")) {
try {
new MessagesSend(this)
.setPeerId(message.getPeerId())
.setMessage("ะะฝัะฐ ะธะท ัะพะพะฑัะตะฝะธั: \n"+"ะัะตะผั ะพัะฟัะฐะฒะบะธ ัะพะพะฑัะตะฝะธั ะฒ UNIX ัะพัะผะฐัะต: "+message.getDate().toString()+"\n"+"ID ะพัะฟัะฐะฒะธัะตะปั: "+
message.getFromId().toString()+"\n"+"ะกะพะพะฑัะตะฝะธะน ะฒ ะฑะตัะตะดะต: "+message.getConversationMessageId().toString())
.execute();
} catch ( BotsLongPollHttpException | BotsLongPollException e) {
e.printStackTrace();
}
}
else if (message.hasGeo()) {
try {
new MessagesSend(this)
.setPeerId(message.getPeerId())
.setMessage("ะขะฒะพะธ ะบะพะพัะดะธะฝะฐัั: "+message.getGeo().getCoordinates().getLatitude().toString()+" "+message.getGeo().getCoordinates().getLongitude().toString())
.execute();
} catch ( BotsLongPollHttpException | BotsLongPollException e) {
e.printStackTrace();
}
}
else if (message.hasAttachments()) {
try {
new MessagesSend(this)
.setPeerId(message.getPeerId())
.setMessage("ะ ัะพะพะฑัะตะฝะธะธ ะตััั ะฒะปะพะถะตะฝะธะต!")
.execute();
} catch ( BotsLongPollHttpException | BotsLongPollException e) {
e.printStackTrace();
}
}
else if (message.getText().toUpperCase().equals("ะะะ ะขะะะะ")) {
try {
new MessagesSend(this)
.setPeerId(message.getPeerId())
.setMessage("ะะพั ัะตะฑะต ะผะตะผะฐั!")
.attachPhoto(new File("F:\\ะฑะพั ะฒ ะฑะตัะตะดะต\\ััะตัะบะพ.jpg"))
.execute();
} catch ( BotsLongPollHttpException | BotsLongPollException e) {
e.printStackTrace();
}
}
}
@Override
public String getAccessToken() {
return "";
}
@Override
public int getGroupId() {
return ;
}
public static void main(String[] args) throws BotsLongPollHttpException, BotsLongPollException {
new BotsLongPoll(new MyBot()).run();
}
}
| [
"[email protected]"
]
| |
e705563856c9af459564f2f15a80e07aafcfaa26 | 2199c1ec81e60fad2f18e723839fa524231727a0 | /addlibrary/src/main/java/com/goldhouse/addlibrary/MyUtils.java | 62651246349bdd5184b05ec66e7a34d0f9be57f2 | []
| no_license | rampagemeepo/LibraryDemo | e74674e01a28f858da2539016483d8f5f24d01ab | 686369aeb4bdabf1266b18f04d042306ee3cba85 | refs/heads/master | 2022-12-08T11:10:42.784333 | 2020-08-28T09:01:37 | 2020-08-28T09:01:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 214 | java | package com.goldhouse.addlibrary;
/**
* Description:
* Author: GX
* CreateDate: 2020/8/28 16:34
* Version: 1.0
*/
public class MyUtils {
public static int add(int a, int b) {
return a+b;
}
}
| [
"[email protected]"
]
| |
7623d3ef2856987ed311a303d1579dd6719f0c05 | c49f40b88fa584f0fe91369c89af3df6087137c8 | /01javaBook/src/shuzu/ShuZu03.java | fad97417fe6fe55c1d596d55e08a825cb6bf27f3 | []
| no_license | meng3588105/U1 | fa12a6b323c312de8827479379f61d772bdba27e | 2451c8e7819e742db47c220798e24072435bfe01 | refs/heads/master | 2020-03-17T13:47:09.817959 | 2018-05-16T09:47:22 | 2018-05-16T09:47:22 | 133,644,522 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 657 | java | package shuzu;
import java.util.Scanner;
public class ShuZu03 {
/**
* ไธๆบ็ปไน 5
* */
public static void main(String[] args) {
int []zu=new int[4];//ๅฎไนไธไธชๆฐ็ป้ฟๅบฆ
Scanner meng00=new Scanner(System.in);
System.out.println("่ฏท่พๅ
ฅ4ๅฎถๅบ็ไปทๆ ผ");
for (int i = 0; i < zu.length; i++) {
System.out.print("็ฌฌ"+(i+1)+"ๅฎถๅบ็ไปทๆ ผ๏ผ");//่พๅ
ฅๆฏไธชๆฐ็ป็ๆฐ
zu[i]=meng00.nextInt();
}
int min = 0; //่ฎฐๅฝๆๅฐไปทๆ ผ
min=zu[0]; //ๆฏๆฌก้ฝๅ็ฌฌไธๅฎถๅบๅๆฏ่พ
for (int i = 0; i < zu.length; i++) {
if (zu[i]<min) { //
min=zu[i];
}
}System.out.print("ๆไฝไปทๆ ผ"+min);
}
}
| [
"[email protected]"
]
| |
40fd8335e12398519c3db348ec4b9e05b1279620 | 232c82605195912510edeffc0b75cf2c22fe13d7 | /src/main/java_recruit/com/xgh/recruitcmbs/entity/ResumeDelivery.java | bdc09c23a885ef98926036b3bcc0f7b809e50a7f | []
| no_license | bithup/recruitcmbs | 34dc1ae2f77d85aaac4dfa5d496900e234af7e26 | 4ac94aca44c1b058b9b55a60a6c9d18c5d656840 | refs/heads/master | 2021-01-01T18:40:37.488149 | 2017-07-26T09:16:08 | 2017-07-26T09:16:08 | 98,403,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,588 | java | package com.xgh.recruitcmbs.entity;
import java.io.Serializable;
import java.util.Date;
/**
*
* ็ฎๅๆ้่กจ
*
**/
@SuppressWarnings("serial")
public class ResumeDelivery implements Serializable {
/**ไธป้ฎid**/
private long id;
/**็จๆทid**/
private long memberId;
/**่ไฝid**/
private long positionId;
/**็ฎๅid**/
private long resumeId;
/**ๆ้็ถๆ๏ผ0ๆชๅค็1.ๅพ
้ข่ฏ2ๅพ
็กฎ่ฎค3ๅทฒ่ฝฌๆญฃ4ไธๅ้**/
private int deliveryStatus;
/**ๅๅปบๆถ้ด**/
private Date createDate;
/**ไฟฎๆนๆถ้ด**/
private Date updateDate;
/**็ถๆ๏ผ-1ๅ ้ค๏ผ0ๅๆถ๏ผ1ๆญฃๅธธ**/
private int status;
/**ๅค็จๅญๆฎต1**/
private long data1;
/**ๅค็จๅญๆฎต2**/
private long data2;
/**ๅค็จๅญๆฎต3**/
private String data3;
/**ๅค็จๅญๆฎต4**/
private String data4;
/**ๅค็จๅญๆฎต5**/
private String data5;
/**ๆฏๅฆ่ขซๆฅ็1ๅทฒๆฅ็0ๆชๆฅ็**/
private int isView;
/**ๅค็จๅญๆฎต7**/
private int data7;
/**ๅค็จๅญๆฎต8**/
private Double data8;
public ResumeDelivery() { super(); }
public ResumeDelivery(long id) {
super();
this.id=id;
}
public ResumeDelivery(long id,long memberId,long positionId,long resumeId,int deliveryStatus,Date createDate,Date updateDate,int status,long data1,long data2,String data3,String data4,String data5,int isView,int data7,Double data8){
super();
this.id = id;
this.memberId = memberId;
this.positionId = positionId;
this.resumeId = resumeId;
this.deliveryStatus = deliveryStatus;
this.createDate = createDate;
this.updateDate = updateDate;
this.status = status;
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
this.data4 = data4;
this.data5 = data5;
this.isView = isView;
this.data7 = data7;
this.data8 = data8;
}
public void setId(Long id){
this.id = id;
}
public Long getId(){
return this.id;
}
public void setMemberId(Long memberId){
this.memberId = memberId;
}
public Long getMemberId(){
return this.memberId;
}
public void setPositionId(Long positionId){
this.positionId = positionId;
}
public Long getPositionId(){
return this.positionId;
}
public void setResumeId(Long resumeId){
this.resumeId = resumeId;
}
public Long getResumeId(){
return this.resumeId;
}
public void setDeliveryStatus(Integer deliveryStatus){
this.deliveryStatus = deliveryStatus;
}
public Integer getDeliveryStatus(){
return this.deliveryStatus;
}
public void setCreateDate(Date createDate){
this.createDate = createDate;
}
public Date getCreateDate(){
return this.createDate;
}
public void setUpdateDate(Date updateDate){
this.updateDate = updateDate;
}
public Date getUpdateDate(){
return this.updateDate;
}
public void setStatus(Integer status){
this.status = status;
}
public Integer getStatus(){
return this.status;
}
public void setData1(Long data1){
this.data1 = data1;
}
public Long getData1(){
return this.data1;
}
public void setData2(Long data2){
this.data2 = data2;
}
public Long getData2(){
return this.data2;
}
public void setData3(String data3){
this.data3 = data3;
}
public String getData3(){
return this.data3;
}
public void setData4(String data4){
this.data4 = data4;
}
public String getData4(){
return this.data4;
}
public void setData5(String data5){
this.data5 = data5;
}
public String getData5(){
return this.data5;
}
public void setIsView(Integer isView){
this.isView = isView;
}
public Integer getIsView(){
return this.isView;
}
public void setData7(Integer data7){
this.data7 = data7;
}
public Integer getData7(){
return this.data7;
}
public void setData8(Double data8){
this.data8 = data8;
}
public Double getData8(){
return this.data8;
}
}
| [
"[email protected]"
]
| |
aa354a121165089accc40eecd5787b562a55e36f | 2d4639344e386f0b0b6b3c680c1f5016f523b400 | /src/main/java/basecc/pattern/proxy/dynamicProxy/UserMgr.java | 3e91f45cdc160cc27d5eef204615f3b271fdc3a7 | []
| no_license | liaodingyuan/springmvc | b590cba0d0ffaa78435141ac71f52a03af5e2b3a | c72831189c7b7b00b7ae5df2e2d9dd2d449fd68a | refs/heads/master | 2020-12-02T10:04:05.209586 | 2018-05-08T04:34:33 | 2018-05-08T04:34:33 | 96,685,532 | 2 | 1 | null | null | null | null | GB18030 | Java | false | false | 285 | java | /**
*
*/
package basecc.pattern.proxy.dynamicProxy;
/**
* <p>Title:UserMgr </p>
* <p>Description: ๅจๆไปฃ็่ฆๅฎ็ฐ็ๆฅๅฃ</p>
* <p>Company: </p>
* @author liaody
* @date 2018ๅนด1ๆ21ๆฅ
*/
public interface UserMgr {
void addUser();
void delUser();
}
| [
"[email protected]"
]
| |
57f47c5d65281db2c1034b189b5997df81e0ab8b | 2ca6dfa7d796a247fb3a813cb7e42a20c62544bd | /FDD - utilizandos testes automatizados/CalculadoraTest.java | 062016297c03e08f0422f465cd7ab8d44ac3fd29 | []
| no_license | marcossouz/poo-aulas-java | 061f7ca074fd94f29927933378f444cb0d2d4e31 | a86f3b5a2d3e446c40e5a4da048d7bdd6464958d | refs/heads/master | 2022-01-15T08:18:58.919932 | 2019-05-23T01:47:46 | 2019-05-23T01:47:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package com.company;
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculadoraTest {
@Test
public void testSomar() {
Calculadora c = new Calculadora();
double res = c.somar(10, 50);
assertEquals(60, res, 0);
}
@Test
public void testSubtrair(){
Calculadora c = new Calculadora();
double res = c.subtrair(10, -15);
assertEquals(25, res, 0);
}
@Test
public void testDividir(){
Calculadora c = new Calculadora();
double res = c.dividir(10.0, 0);
assertTrue(Double.isFinite(res));
}
@Test
public void testMultiplicar(){
Calculadora c = new Calculadora();
double res = c.multiplicar(120.115, 12.5465);
assertEquals(1507.01, res, 0.5);
}
} | [
"[email protected]"
]
| |
e6e3f289ce7e9a81a9d555b2f1f6f0381bc2c0b0 | 5ed29f6b231443a79acb01211bd0d141d028c474 | /src/events/EContainerUpdate.java | 06c1840e674749d0748d48863262df470d030c0e | []
| no_license | bloodrizer/NamelessEngine | b16c473e561527648639205369acb8b21257a766 | 3088acca9f0b43f9e949fe8ad56d9ce239386599 | refs/heads/master | 2020-05-31T01:21:47.053005 | 2011-10-20T14:11:28 | 2011-10-20T14:11:28 | 1,640,546 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package events;
import items.ItemContainer;
/**
*
* @author Administrator
*/
public class EContainerUpdate extends Event{
public ItemContainer container;
public EContainerUpdate(ItemContainer container){
this.container = container;
}
}
| [
"[email protected]"
]
| |
0ebf8c71502b0ec23927a7797a38ccb56192b64d | 63c8abf02d738ec62a9ec49fa5d5204d6b3fb2ec | /release/Scope/app/src/main/java/com/nus/scope/Contacts.java | 3d62f8f4da67f89ed09246b7f671a894cc31b846 | []
| no_license | salmangadit/scope | 84c5d5e7a227af3cc015a67e6330728d20d5eac5 | d4d4feae21e30beed513cf3ad55d23d28eeaf06a | refs/heads/master | 2021-01-19T02:44:11.788730 | 2016-06-23T13:13:19 | 2016-06-23T13:13:19 | 26,875,576 | 1 | 0 | null | 2016-06-23T13:13:19 | 2014-11-19T18:35:48 | D | UTF-8 | Java | false | false | 8,568 | java | package com.nus.scope;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.os.RemoteException;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class Contacts extends Activity {
EditText etName;
EditText etMobile;
EditText etFax;
EditText etEmail;
EditText etAddress;
EditText etWebsite;
List<SegmentationResult> ocrResults;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
getActionBar().setDisplayHomeAsUpEnabled(true);
etName = (EditText) findViewById(R.id.et_name);
etMobile = (EditText) findViewById(R.id.et_mobile_phone);
etFax = (EditText) findViewById(R.id.et_home_phone);
etEmail = (EditText) findViewById(R.id.et_home_email);
etAddress = (EditText) findViewById(R.id.et_work_email);
etWebsite = (EditText) findViewById(R.id.et_website);
Globals appState = ((Globals) getApplicationContext());
ocrResults = appState.getSegmentationResult();
ArrayList<String> extractedStrings = this.extractStrings(ocrResults);
StringParser parser = new StringParser();
ParsedResults results = new ParsedResults();
results = parser.CardParse(extractedStrings);
// Update fields
etName.setText(results.name);
etMobile.setText(results.numbers);
etEmail.setText(results.emails);
etFax.setText(results.fax);
etAddress.setText(results.address);
etWebsite.setText(results.website);
// Creating a button click listener for the "Add Contact" button
OnClickListener addClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table
// ContactsContract.RawContacts
ops.add(ContentProviderOperation
.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,
null).withValue(RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert display name in the table ContactsContract.Data
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME,
etName.getText().toString()).build());
// Adding insert operation to operations list
// to insert Mobile Number in the table ContactsContract.Data
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etMobile.getText().toString())
.withValue(Phone.TYPE,
CommonDataKinds.Phone.TYPE_MOBILE).build());
// Adding insert operation to operations list
// to insert Home Phone Number in the table
// ContactsContract.Data
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etFax.getText().toString())
.withValue(Phone.TYPE, Phone.TYPE_FAX_HOME).build());
// Adding insert operation to operations list
// to insert Home Email in the table ContactsContract.Data
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,
Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_HOME).build());
// Adding insert operation to operations list
// to insert Work Email in the table ContactsContract.Data
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(
ContactsContract.Data.MIMETYPE,
CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(
CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
etAddress.getText().toString())
.withValue(CommonDataKinds.StructuredPostal.TYPE,
CommonDataKinds.StructuredPostal.TYPE_WORK)
.build());
// Website
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,
CommonDataKinds.Website.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Website.URL,
etWebsite.getText().toString())
.withValue(CommonDataKinds.Website.TYPE,
CommonDataKinds.Website.TYPE_WORK).build());
try {
// Executing all the insert operations as a single database
// transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY,
ops);
Toast.makeText(getBaseContext(),
"Contact is successfully added", Toast.LENGTH_SHORT)
.show();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
};
// Creating a button click listener for the "Add Contact" button
OnClickListener contactsClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// Creating an intent to open Android's Contacts List
Intent contacts = new Intent(Intent.ACTION_VIEW,
ContactsContract.Contacts.CONTENT_URI);
// Starting the activity
startActivity(contacts);
}
};
final Context a = this.getApplicationContext();
// Creating a button click listener for the "Add Contact" button
OnClickListener doneClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// Creating an intent to open Android's Contacts List
Intent intent = new Intent(a, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
};
// Getting reference to "Add Contact" button
Button btnAdd = (Button) findViewById(R.id.btn_add);
// Getting reference to "Contacts List" button
Button btnContacts = (Button) findViewById(R.id.btn_contacts);
Button btnDone = (Button) findViewById(R.id.btn_home);
// Setting click listener for the "Add Contact" button
btnAdd.setOnClickListener(addClickListener);
// Setting click listener for the "List Contacts" button
btnContacts.setOnClickListener(contactsClickListener);
btnDone.setOnClickListener(doneClickListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_contacts, menu);
return true;
}
private ArrayList<String> extractStrings(List<SegmentationResult> ocr) {
ArrayList<String> extracted = new ArrayList<String>();
for (int i = 0; i < ocr.size(); i++) {
if (ocr.get(i).Result.trim() != "")
extracted.add(ocr.get(i).Result);
}
return extracted;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"[email protected]"
]
| |
668ca67d7711796e8305d004508be00eb901cf2a | fa0f743620c1a9da6b4fa60e2d8f936bb51ed36c | /src/com/binghamton/jhelp/ast/ForStatement.java | 55fb5c3a036220c91d0bc7811a29e8f8b0615c81 | [
"BSD-3-Clause"
]
| permissive | mhems/jhelp | f18addc4b41398f98a5aea83b4a91a7e39c81247 | 4a30e709378defb95b60a83fc9e315a9fd24095b | refs/heads/master | 2021-06-02T02:39:42.059520 | 2021-03-14T00:41:55 | 2021-03-14T00:41:55 | 70,102,789 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,011 | java | package com.binghamton.jhelp.ast;
import java.util.List;
import org.antlr.v4.runtime.Token;
/**
* A class representing a Java for statement
* e.g. {@code for (int i = 0; i < N; i++)}
*/
public class ForStatement extends Statement {
private List<Statement> initializers;
private Expression condition;
private List<Statement> updates;
private Statement body;
/**
* Construct a new for statement
* @param keyword the for keyword Token
* @param initializers the initializing statements of the for statement
* @param condition the iteration condition of the for statement
* @param updates the updating statements of the for statement
* @param statement the body of the for statement
*/
public ForStatement(Token keyword,
List<Statement> initializers,
Expression condition,
List<Statement> updates,
Statement statement) {
super(keyword);
setFirstToken(keyword);
this.initializers = initializers;
this.condition = condition;
this.updates = updates;
this.body = statement;
}
/**
* Gets the statements that initialize this statement
* @return the statements that initialize this statement
*/
public List<Statement> getInitializers() {
return initializers;
}
/**
* Gets a particular initializer of this statement
* @param index the 0-indexed initializer to retrieve
* @return the initializer at index `index`
*/
public Statement getInitializer(int index) {
return initializers.get(index);
}
/**
* Gets the number of initializers of this statement
* @return the number of initializers of this statement
*/
public int getNumInitializers() {
return initializers.size();
}
/**
* Gets the condition this statement is predicated on
* @return the condition this statement is predicated on
*/
public Expression getCondition() {
return condition;
}
/**
* Gets the updater statements that update this statement
* @return the updater statements that update this statement
*/
public List<Statement> getUpdaters() {
return updates;
}
/**
* Gets a particular updater of this for statement
* @param index the 0-indexed updater to retrieve
* @return the update at index `index`
*/
public Statement getUpdate(int index) {
return updates.get(index);
}
/**
* Gets the number of updaters of this for statement
* @return the number of updaters of this for statement
*/
public int getNumUpdaters() {
return updates.size();
}
/**
* Gets the body of this statement
* @return the body of this statement
*/
public Statement getBody() {
return body;
}
public void acceptBody(ASTVisitor v) {
}
/**
* Double dispatch this class on parameter
* @param v the visitor to accept
*/
@Override
public void accept(ASTVisitor v) {
v.visit(this);
// must visit block statements explicitly
}
/**
* Visits the implementor's constituents and then the implementor
* @param visitor the visitor to visit with
* @param order the order to vist the implementor with respect to its constituents
*/
public void acceptRec(ASTVisitor visitor, Visitable.Order order)
{
if (order == Visitable.Order.PRE)
{
visitor.visit(this);
}
for (Statement s : initializers)
{
s.acceptRec(visitor, order);
}
condition.acceptRec(visitor, order);
for (Statement s : updates)
{
s.acceptRec(visitor, order);
}
body.acceptRec(visitor, order);
if (order == Visitable.Order.POST)
{
visitor.visit(this);
}
}
}
| [
"[email protected]"
]
| |
c9fde3bb29799f686c41095b0c58e9e6bd4a74c5 | b2d4f5b9ed1ad6e079c5422767fce584bd906367 | /src/main/java/com/pepper/project/csc/message/controller/SysMessageController.java | 8ad85d7ff2e227d2562d15a34f91082e320207a5 | [
"MIT"
]
| permissive | hanjietao/ops-pro | 6683494ab56c5c0c3432dbd1df09c223a552f28e | a31f37e322da2e5fe3dc0977f2b70332a90c8706 | refs/heads/master | 2022-09-26T06:48:33.506079 | 2020-04-09T03:42:34 | 2020-04-09T03:42:34 | 237,716,491 | 0 | 0 | MIT | 2022-09-01T23:21:26 | 2020-02-02T04:09:49 | TSQL | UTF-8 | Java | false | false | 1,283 | java | package com.pepper.project.csc.message.controller;
import com.pepper.framework.web.controller.BaseController;
import com.pepper.framework.web.page.TableDataInfo;
import com.pepper.project.csc.message.domain.SysMessage;
import com.pepper.project.csc.message.service.ISysMessageService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/csc/message")
public class SysMessageController extends BaseController{
@Autowired
private ISysMessageService sysMessageService;
@ApiOperation("็จๆท็ซๅ
ไฟกๅ่กจ")
@PostMapping("/list")
@ResponseBody
public TableDataInfo userPointList()
{
startPage();
SysMessage sysMessage = new SysMessage();
sysMessage.setUserId(getMerchantId());
List<SysMessage> list = sysMessageService.selectSysMessageList(sysMessage);
new Thread(() -> {
list.stream().forEach(sMsg->{
sMsg.setStatus("1");// read already
sysMessageService.updateSysMessage(sMsg);
});
}).start();
return getDataTable(list);
}
}
| [
"[email protected]"
]
| |
9327960331337ee731b49a6ef382f8452c334164 | 44ae99cc690a2ccd25e22b3dc71343ce3882eee7 | /org/isotc211/x2005/gmd/impl/CIResponsiblePartyDocumentImpl.java | 7b6539f78477d55187a8975ac8a3394f788e1639 | []
| no_license | mcenirm/isotc211-src | 0ee877ddcb0ff71191008311d3ee60d8c4263a70 | c8d68f488500ed4815f1fa9875c0c24f3bda845b | refs/heads/master | 2021-03-12T23:00:39.838690 | 2012-06-16T22:15:48 | 2012-06-16T22:15:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,301 | java | /*
* An XML document type.
* Localname: CI_ResponsibleParty
* Namespace: http://www.isotc211.org/2005/gmd
* Java type: org.isotc211.x2005.gmd.CIResponsiblePartyDocument
*
* Automatically generated - do not modify.
*/
package org.isotc211.x2005.gmd.impl;
/**
* A document containing one CI_ResponsibleParty(@http://www.isotc211.org/2005/gmd) element.
*
* This is a complex type.
*/
public class CIResponsiblePartyDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements org.isotc211.x2005.gmd.CIResponsiblePartyDocument
{
private static final long serialVersionUID = 1L;
public CIResponsiblePartyDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName CIRESPONSIBLEPARTY$0 =
new javax.xml.namespace.QName("http://www.isotc211.org/2005/gmd", "CI_ResponsibleParty");
/**
* Gets the "CI_ResponsibleParty" element
*/
public org.isotc211.x2005.gmd.CIResponsiblePartyType getCIResponsibleParty()
{
synchronized (monitor())
{
check_orphaned();
org.isotc211.x2005.gmd.CIResponsiblePartyType target = null;
target = (org.isotc211.x2005.gmd.CIResponsiblePartyType)get_store().find_element_user(CIRESPONSIBLEPARTY$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "CI_ResponsibleParty" element
*/
public void setCIResponsibleParty(org.isotc211.x2005.gmd.CIResponsiblePartyType ciResponsibleParty)
{
generatedSetterHelperImpl(ciResponsibleParty, CIRESPONSIBLEPARTY$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "CI_ResponsibleParty" element
*/
public org.isotc211.x2005.gmd.CIResponsiblePartyType addNewCIResponsibleParty()
{
synchronized (monitor())
{
check_orphaned();
org.isotc211.x2005.gmd.CIResponsiblePartyType target = null;
target = (org.isotc211.x2005.gmd.CIResponsiblePartyType)get_store().add_element_user(CIRESPONSIBLEPARTY$0);
return target;
}
}
}
| [
"[email protected]"
]
| |
9cabb7b4fc5648488558fc54dd6d6afc6789363f | b3c42f7453fac71af689527e8640e3b5fea5a7c6 | /JDK features/IO/NIO/ScatterGatherTutorial.java | a59afbb78e844b327ac6eaa70a079384c763e5ae | []
| no_license | Reshav-Paul/Java-Roadmap | a94a1fe8a30b9112290317313e33438e8c856b52 | f3127ebb4d127e4485ab924f70d2ef4d32eccb85 | refs/heads/master | 2020-09-23T21:32:34.764035 | 2019-12-27T15:29:15 | 2019-12-27T15:29:15 | 225,592,504 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,563 | java | import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.stream.IntStream;
import java.nio.ByteBuffer;
public class ScatterGatherTutorial {
public static void main(String[] args) throws IOException {
FileInputStream fin = new FileInputStream("Text Files\\InFile.txt");
FileChannel inChannel = fin.getChannel();
FileOutputStream fout = new FileOutputStream("Text Files\\OutFileScattered.txt");
FileChannel outChannel = fout.getChannel();
ByteBuffer bufferArray[] = new ByteBuffer[5];
IntStream.range(0, 5).forEach(e -> bufferArray[e] = ByteBuffer.allocate(1024));
while(true){
//clear buffers before reading data into it from the channel
IntStream.range(0, 5).forEach(e -> bufferArray[e].clear());
//check to see if all data has been read
long bytesRead = inChannel.read(bufferArray);
if(bytesRead == -1)
break;
//flip the buffers to read from the beginning
IntStream.range(0, 5).forEach(e -> bufferArray[e].flip());
//to write the buffers in the same order
//outChannel.write(bufferArray);
//To write the buffers in reverse order
for(int i = bufferArray.length - 1; i >= 0; --i)
outChannel.write(bufferArray[i]);
}
inChannel.close();
outChannel.close();
fin.close();
fout.close();
}
} | [
"[email protected]"
]
| |
a645f91bdef83e4373bc52d9e68c8f4577fde563 | f8e1159322d95ef9a07bc535b7adbdfd84f758ef | /app/src/main/java/com/refknowledgebase/refknowledgebase/model/Language_BaseModel.java | 2891432aff0d277cb6796b59967026544219061d | []
| no_license | DVXakserv/Mobile-knowledgebase | 1e73f99ebbf4394ce13a9fb7a89c9767452ce1b7 | 6e2495d6f3b1d359992fa857d93d4279d0a84b50 | refs/heads/master | 2022-11-25T07:28:42.691822 | 2020-08-03T10:25:22 | 2020-08-03T10:25:22 | 284,663,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 585 | java | package com.refknowledgebase.refknowledgebase.model;
import java.util.List;
public abstract class Language_BaseModel {
abstract public int getid();
abstract public String getname();
abstract public String getacronym();
abstract public int getis_active();
abstract public int getis_default();
abstract public String gettext_direction();
abstract public String getcreated_by();
abstract public String getupdated_by();
abstract public String getcreated_at();
abstract public String getupdated_at();
abstract public String getdeleted_at();
}
| [
"[email protected]"
]
| |
b954e4131a6a3c2d9a55178cd51fae07e5d85d05 | 07ca807b43429d8cc37b0b7e1a48ee20d5b56a59 | /kie-wb-tests/kie-wb-tests-gui/src/test/java/org/kie/wb/selenium/ui/StandalonePerspectivesIntegrationTest.java | ac461f3b2abd4ca4797bc8b01010018ba4babe43 | [
"Apache-2.0"
]
| permissive | spolti/kie-wb-distributions | 416bff9b76c1eefd8d68b4d9cd0c57c700496f6d | a7cfef810ea310d0369a54b27292ed4888e867c1 | refs/heads/master | 2021-04-27T21:44:52.572749 | 2018-02-15T16:29:41 | 2018-02-15T16:29:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,002 | java | /*
* Copyright 2017 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.kie.wb.selenium.ui;
import org.assertj.core.api.Assertions;
import org.jboss.arquillian.graphene.findby.ByJQuery;
import org.junit.Before;
import org.junit.Test;
import org.kie.wb.selenium.model.KieSeleniumTest;
import org.kie.wb.selenium.util.Waits;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverException;
import static org.assertj.core.api.Assertions.assertThat;
public class StandalonePerspectivesIntegrationTest extends KieSeleniumTest {
private final static String
BASE_URL = System.getProperty("kie.wb.url"),
APP_CONTEXT = System.getProperty("app.name") + ".jsp",
STANDALONE_PARAMETER = "?standalone=true",
PERSPECTIVE_ID = "&perspective=AuthoringPerspective",
HEADER_PARAMETER = "&header=AppNavBar",
COMPLETE_URL = BASE_URL + "/" + APP_CONTEXT + STANDALONE_PARAMETER + PERSPECTIVE_ID;
private static final By
EXPLORER_HEADER = ByJQuery.selector("h3:contains('Project Explorer')"),
WORKBENCH_HEADER = By.id("workbenchHeaderPanel");
@Before
public void setUp() {
login.get();
if (login.isDisplayed()) {
login.loginDefaultUser();
}
}
@Test
public void testAuthoringPerspectiveWithoutHeader() {
driver.get(COMPLETE_URL);
verifyPerspectiveIsLoaded();
verifyPresenceOfHeader(false);
}
@Test
public void testAuthoringPerspectiveWithHeader() {
driver.get(COMPLETE_URL + HEADER_PARAMETER);
verifyPerspectiveIsLoaded();
verifyPresenceOfHeader(true);
}
private void verifyPerspectiveIsLoaded() {
try {
Waits.elementPresent(EXPLORER_HEADER, 10);
} catch (WebDriverException exception) {
Assertions.fail("The standalone perspective could not be loaded.", exception);
}
}
private void verifyPresenceOfHeader(boolean headerIncluded) {
int
actualHeaderCount = driver.findElements(WORKBENCH_HEADER).size(),
expectedHeaderCount = headerIncluded ? 1 : 0;
String headerAssertionMessage = String.format("There should %s be AppNavBar on the page.", headerIncluded ? "" : "NOT");
assertThat(actualHeaderCount)
.as(headerAssertionMessage)
.isEqualTo(expectedHeaderCount);
}
}
| [
"[email protected]"
]
| |
4dfa913d110c88a63ae0bed3666451cc5fbf063f | 22d39eeae9c04fdc5e8051ad7699a4874302a833 | /app/src/main/java/net/beaconradar/nearby/RecyclerViewClickListener.java | 1a8cd4fd9fd50940ff5d77841a4a851bda11e514 | [
"Apache-2.0"
]
| permissive | stanleyguevara/beaconradar | 0bde1263ee7239b956862a43a4d0de366b2a5a64 | ce990eb18b941429e7d1ba2d4bfda3e11119e5ee | refs/heads/master | 2020-12-24T18:41:32.202660 | 2016-04-13T01:56:22 | 2016-04-13T01:56:22 | 56,107,389 | 15 | 2 | null | 2016-10-04T21:41:05 | 2016-04-13T00:17:32 | Java | UTF-8 | Java | false | false | 350 | java | package net.beaconradar.nearby;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public interface RecyclerViewClickListener {
public void onClick(View view, int position, int type, RecyclerView.ViewHolder viewHolder);
public void onLongClick(View view, int position, int type, RecyclerView.ViewHolder viewHolder);
}
| [
"[email protected]"
]
| |
bac4d6cac44ecd80668a714a0d5a637b25f7593a | 3950c605ca640b25c18fbc7849fc051f6d5cf859 | /src/main/java/com/labyrinth/mryxlarkbot/scrapper/TextMixer.java | c259aed92ecdde8674267cca39891232bf40ffab | []
| no_license | AnbangYY/LoverBot | 06b2cbe8b7d26b5c82ad5e708b37a67558eb3593 | 8e64df5362209844d4ec4aea064ed27cb906f72a | refs/heads/main | 2023-03-07T20:34:52.305191 | 2021-02-26T07:24:48 | 2021-02-26T07:24:48 | 342,493,288 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,868 | java | package com.labyrinth.mryxlarkbot.scrapper;
import java.io.*;
import java.util.Random;
public class TextMixer {
// public static void main(String[] args) {
// try {
// int indicator = 0;
// BufferedReader readerEn = new BufferedReader(new FileReader(new File("src/main/resources/quote2.txt")));
// BufferedReader readerCn = new BufferedReader(new FileReader(new File("src/main/resources/quotes.txt")));
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/main/resources/repository.txt"));
// Random random = new Random();
// String text = "";
// while (text!=null){
// int a = random.nextInt(100);
// if(isEven(a)){
// bufferedWriter.write(text);
// bufferedWriter.newLine();
// text = readerCn.readLine();
// indicator = 0;
// }else{
// bufferedWriter.write(text);
// bufferedWriter.newLine();
// text = readerEn.readLine();
// indicator = 1;
// }
// }
// if(indicator==0){
// while(text!=null){
// text = readerEn.readLine();
// bufferedWriter.write(text);
// bufferedWriter.newLine();
// }
// }else {
// while(text!=null){
// text = readerCn.readLine();
// bufferedWriter.write(text);
// bufferedWriter.newLine();
// }
// }
//
// }catch (Exception e){
// e.printStackTrace();
// }
// }
static Boolean isEven(int i){
if(i%2==0){
return true;
}
return false;
}
}
| [
"[email protected]"
]
| |
a3740abb4770d65f31b4d00ef4745198694a93af | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/29/29_69c84a3a253b06613a7303c9e6250ea344561111/PersistenceManager/29_69c84a3a253b06613a7303c9e6250ea344561111_PersistenceManager_t.java | 497cd8524c81fae913c766537b01bb7c5887d393 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 33,829 | java | /*
PersistenceManager.java / Frost
Copyright (C) 2007 Frost Project <jtcfrost.sourceforge.net>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.fileTransfer;
import java.beans.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import frost.*;
import frost.fcp.*;
import frost.fcp.fcp07.*;
import frost.fcp.fcp07.persistence.*;
import frost.fileTransfer.download.*;
import frost.fileTransfer.upload.*;
import frost.util.*;
import frost.util.model.*;
/**
* This class starts/stops/monitors the persistent requests on Freenet 0.7.
*/
public class PersistenceManager implements IFcpPersistentRequestsHandler {
private static Logger logger = Logger.getLogger(PersistenceManager.class.getName());
/* FIXME:
* - show if external in table
*/
// this would belong to the models, but not needed for 0.5 or without persistence, hence we maintain it here
private Hashtable<String,FrostUploadItem> uploadModelItems = new Hashtable<String,FrostUploadItem>();
private Hashtable<String,FrostDownloadItem> downloadModelItems = new Hashtable<String,FrostDownloadItem>();
private UploadModel uploadModel;
private DownloadModel downloadModel;
private DirectTransferQueue directTransferQueue;
private DirectTransferThread directTransferThread;
private boolean showExternalItemsDownload;
private boolean showExternalItemsUpload;
private FcpPersistentQueue persistentQueue;
private FcpPersistentConnectionTools fcpTools;
private Set<String> directGETsInProgress = new HashSet<String>();
private Set<String> directPUTsInProgress = new HashSet<String>();
private Set<String> directPUTsWithoutAnswer = new HashSet<String>();
/**
* @return true if Frost is configured to use persistent uploads and downloads, false if not
*/
public static boolean isPersistenceEnabled() {
if( FcpHandler.isFreenet07()
&& Core.frostSettings.getBoolValue(SettingsClass.FCP2_USE_PERSISTENCE) )
{
return true;
} else {
return false;
}
}
public static boolean isDDA() {
if( FcpHandler.isFreenet07()
&& Core.frostSettings.getBoolValue(SettingsClass.FCP2_USE_DDA)
&& FcpPersistentConnection.getInstance().isDDA() )
{
return true;
} else {
return false;
}
}
/**
* Must be called after the upload and download model is initialized!
*/
public PersistenceManager(UploadModel um, DownloadModel dm) {
showExternalItemsDownload = Core.frostSettings.getBoolValue(SettingsClass.GQ_SHOW_EXTERNAL_ITEMS_DOWNLOAD);
showExternalItemsUpload = Core.frostSettings.getBoolValue(SettingsClass.GQ_SHOW_EXTERNAL_ITEMS_UPLOAD);
fcpTools = new FcpPersistentConnectionTools();
Core.frostSettings.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if( evt.getPropertyName().equals(SettingsClass.GQ_SHOW_EXTERNAL_ITEMS_DOWNLOAD) ) {
showExternalItemsDownload = Core.frostSettings.getBoolValue(SettingsClass.GQ_SHOW_EXTERNAL_ITEMS_DOWNLOAD);
if( showExternalItemsDownload ) {
// get external items
showExternalDownloadItems();
}
} else if( evt.getPropertyName().equals(SettingsClass.GQ_SHOW_EXTERNAL_ITEMS_UPLOAD) ) {
showExternalItemsUpload = Core.frostSettings.getBoolValue(SettingsClass.GQ_SHOW_EXTERNAL_ITEMS_UPLOAD);
if( showExternalItemsUpload ) {
// get external items
showExternalUploadItems();
}
}
}
});
uploadModel = um;
downloadModel = dm;
// initially get all items from model
for(int x=0; x < uploadModel.getItemCount(); x++) {
FrostUploadItem ul = (FrostUploadItem) uploadModel.getItemAt(x);
if( ul.getGqIdentifier() != null ) {
uploadModelItems.put(ul.getGqIdentifier(), ul);
}
}
for(int x=0; x < downloadModel.getItemCount(); x++) {
FrostDownloadItem ul = (FrostDownloadItem) downloadModel.getItemAt(x);
if( ul.getGqIdentifier() != null ) {
downloadModelItems.put(ul.getGqIdentifier(), ul);
}
}
// enqueue listeners to keep updated about the model items
uploadModel.addOrderedModelListener(
new SortedModelListener() {
public void modelCleared() {
for( FrostUploadItem ul : uploadModelItems.values() ) {
if( ul.isExternal() == false ) {
fcpTools.removeRequest(ul.getGqIdentifier());
}
}
uploadModelItems.clear();
}
public void itemAdded(int position, ModelItem item) {
FrostUploadItem ul = (FrostUploadItem) item;
uploadModelItems.put(ul.getGqIdentifier(), ul);
if( !ul.isExternal() ) {
// maybe start immediately
startNewUploads();
}
}
public void itemChanged(int position, ModelItem item) {
}
public void itemsRemoved(int[] positions, ModelItem[] items) {
for(ModelItem item : items) {
FrostUploadItem ul = (FrostUploadItem) item;
uploadModelItems.remove(ul.getGqIdentifier());
if( ul.isExternal() == false ) {
fcpTools.removeRequest(ul.getGqIdentifier());
}
}
}
});
downloadModel.addOrderedModelListener(
new SortedModelListener() {
public void modelCleared() {
for( FrostDownloadItem ul : downloadModelItems.values() ) {
if( ul.isExternal() == false ) {
fcpTools.removeRequest(ul.getGqIdentifier());
}
}
downloadModelItems.clear();
}
public void itemAdded(int position, ModelItem item) {
FrostDownloadItem ul = (FrostDownloadItem) item;
downloadModelItems.put(ul.getGqIdentifier(), ul);
if( !ul.isExternal() ) {
// maybe start immediately
startNewDownloads();
}
}
public void itemChanged(int position, ModelItem item) {
}
public void itemsRemoved(int[] positions, ModelItem[] items) {
for(ModelItem item : items) {
FrostDownloadItem ul = (FrostDownloadItem) item;
downloadModelItems.remove(ul.getGqIdentifier());
if( ul.isExternal() == false ) {
fcpTools.removeRequest(ul.getGqIdentifier());
}
}
}
});
directTransferQueue = new DirectTransferQueue();
directTransferThread = new DirectTransferThread();
persistentQueue = new FcpPersistentQueue(new FcpPersistentConnectionTools(), this);
}
public void startThreads() {
directTransferThread.start();
persistentQueue.startThreads();
TimerTask task = new TimerTask() {
public void run() {
maybeStartRequests();
}
};
Core.schedule(task, 3000, 3000);
}
public void removeRequests(List<String> requests) {
for( String id : requests ) {
fcpTools.removeRequest(id);
}
}
public void changeItemPriorites(ModelItem[] items, int newPrio) {
if( items == null || items.length == 0 ) {
return;
}
for( int i = 0; i < items.length; i++ ) {
ModelItem item = items[i];
String gqid = null;
if( item instanceof FrostUploadItem ) {
FrostUploadItem ui = (FrostUploadItem) item;
gqid = ui.getGqIdentifier();
} else if( item instanceof FrostDownloadItem ) {
FrostDownloadItem di = (FrostDownloadItem) item;
gqid = di.getGqIdentifier();
}
if( gqid != null ) {
fcpTools.changeRequestPriority(gqid, newPrio);
}
}
}
/**
* Periodically check if we could start a new request.
* This could be done better if we check if a request finished, but later...
*/
private void maybeStartRequests() {
// start new requests
startNewUploads();
startNewDownloads();
}
/**
* Enqueue a direct GET if not already enqueued, or already downloaded to download dir.
* @return true if item was enqueued
*/
public boolean maybeEnqueueDirectGet(FrostDownloadItem dlItem, long expectedFileSize) {
if( !isDirectTransferInProgress(dlItem) ) {
File targetFile = new File(Core.frostSettings.getValue(SettingsClass.DIR_DOWNLOAD) + dlItem.getFilename());
if( !targetFile.isFile() || targetFile.length() != expectedFileSize ) {
directTransferQueue.appendItemToQueue(dlItem);
return true;
}
}
return false;
}
/**
* Apply the states of FcpRequestGet to the FrostDownloadItem.
*/
private void applyState(FrostDownloadItem dlItem, FcpPersistentGet getReq) {
if( dlItem.getPriority() != getReq.getPriority() ) {
dlItem.setPriority(getReq.getPriority());
}
if( dlItem.isDirect() != getReq.isDirect() ) {
dlItem.setDirect(getReq.isDirect());
}
if( !getReq.isProgressSet() && !getReq.isSuccess() && !getReq.isFailed() ) {
if( dlItem.getState() == FrostDownloadItem.STATE_WAITING ) {
dlItem.setState(FrostDownloadItem.STATE_PROGRESS);
}
return;
}
if( getReq.isProgressSet() ) {
int doneBlocks = getReq.getDoneBlocks();
int requiredBlocks = getReq.getRequiredBlocks();
int totalBlocks = getReq.getTotalBlocks();
boolean isFinalized = getReq.isFinalized();
if( totalBlocks > 0 ) {
dlItem.setDoneBlocks(doneBlocks);
dlItem.setRequiredBlocks(requiredBlocks);
dlItem.setTotalBlocks(totalBlocks);
dlItem.setFinalized(isFinalized);
dlItem.fireValueChanged();
}
if( dlItem.getState() != FrostDownloadItem.STATE_PROGRESS ) {
dlItem.setState(FrostDownloadItem.STATE_PROGRESS);
}
}
if( getReq.isSuccess() ) {
// maybe progress was not completely sent
if( dlItem.getTotalBlocks() > 0 && dlItem.getDoneBlocks() < dlItem.getRequiredBlocks() ) {
dlItem.setDoneBlocks(dlItem.getRequiredBlocks());
}
if( dlItem.isExternal() ) {
dlItem.setState(FrostDownloadItem.STATE_DONE);
dlItem.setFileSize(getReq.getFilesize());
} else {
if( dlItem.isDirect() ) {
maybeEnqueueDirectGet(dlItem, getReq.getFilesize());
} else {
FcpResultGet result = new FcpResultGet(true);
File targetFile = new File(Core.frostSettings.getValue(SettingsClass.DIR_DOWNLOAD) + dlItem.getFilename());
FileTransferManager.inst().getDownloadManager().notifyDownloadFinished(dlItem, result, targetFile);
}
}
}
if( getReq.isFailed() ) {
String desc = getReq.getCodeDesc();
if( dlItem.isExternal() ) {
dlItem.setState(FrostDownloadItem.STATE_FAILED);
dlItem.setErrorCodeDescription(desc);
} else {
int code = getReq.getCode();
boolean isFatal = getReq.isFatal();
FcpResultGet result = new FcpResultGet(false, code, desc, isFatal);
File targetFile = new File(Core.frostSettings.getValue(SettingsClass.DIR_DOWNLOAD) + dlItem.getFilename());
boolean retry = FileTransferManager.inst().getDownloadManager().notifyDownloadFinished(dlItem, result, targetFile);
if( retry ) {
fcpTools.removeRequest(getReq.getIdentifier());
}
}
}
}
/**
* Apply the states of FcpRequestPut to the FrostUploadItem.
*/
private void applyState(FrostUploadItem ulItem, FcpPersistentPut putReq) {
if( directPUTsWithoutAnswer.contains(ulItem.getGqIdentifier()) ) {
// we got an answer
directPUTsWithoutAnswer.remove(ulItem.getGqIdentifier());
}
if( ulItem.getPriority() != putReq.getPriority() ) {
ulItem.setPriority(putReq.getPriority());
}
if( !putReq.isProgressSet() && !putReq.isSuccess() && !putReq.isFailed() ) {
if( ulItem.getState() == FrostUploadItem.STATE_WAITING ) {
ulItem.setState(FrostUploadItem.STATE_PROGRESS);
}
return;
}
if( putReq.isProgressSet() ) {
int doneBlocks = putReq.getDoneBlocks();
int totalBlocks = putReq.getTotalBlocks();
boolean isFinalized = putReq.isFinalized();
if( totalBlocks > 0 ) {
ulItem.setDoneBlocks(doneBlocks);
ulItem.setTotalBlocks(totalBlocks);
ulItem.setFinalized(isFinalized);
ulItem.fireValueChanged();
}
if( ulItem.getState() != FrostUploadItem.STATE_PROGRESS ) {
ulItem.setState(FrostUploadItem.STATE_PROGRESS);
}
}
if( putReq.isSuccess() ) {
// maybe progress was not completely sent
if( ulItem.getTotalBlocks() > 0 && ulItem.getDoneBlocks() != ulItem.getTotalBlocks() ) {
ulItem.setDoneBlocks(ulItem.getTotalBlocks());
}
String chkKey = putReq.getUri();
if( ulItem.isExternal() ) {
ulItem.setState(FrostUploadItem.STATE_DONE);
ulItem.setKey(chkKey);
} else {
FcpResultPut result = new FcpResultPut(FcpResultPut.Success, chkKey);
FileTransferManager.inst().getUploadManager().notifyUploadFinished(ulItem, result);
}
}
if( putReq.isFailed() ) {
String desc = putReq.getCodeDesc();
if( ulItem.isExternal() ) {
ulItem.setState(FrostUploadItem.STATE_FAILED);
ulItem.setErrorCodeDescription(desc);
} else {
int returnCode = putReq.getCode();
boolean isFatal = putReq.isFatal();
FcpResultPut result;
if( returnCode == 9 ) {
result = new FcpResultPut(FcpResultPut.KeyCollision, returnCode, desc, isFatal);
} else if( returnCode == 5 ) {
result = new FcpResultPut(FcpResultPut.Retry, returnCode, desc, isFatal);
} else {
result = new FcpResultPut(FcpResultPut.Error, returnCode, desc, isFatal);
}
FileTransferManager.inst().getUploadManager().notifyUploadFinished(ulItem, result);
}
}
}
private void startNewUploads() {
boolean isLimited = true;
int currentAllowedUploadCount = 0;
{
int allowedConcurrentUploads = Core.frostSettings.getIntValue(SettingsClass.UPLOAD_MAX_THREADS);
if( allowedConcurrentUploads <= 0 ) {
isLimited = false;
} else {
int runningUploads = 0;
for(FrostUploadItem ulItem : uploadModelItems.values() ) {
if( !ulItem.isExternal() && ulItem.getState() == FrostUploadItem.STATE_PROGRESS) {
runningUploads++;
}
}
currentAllowedUploadCount = allowedConcurrentUploads - runningUploads;
if( currentAllowedUploadCount < 0 ) {
currentAllowedUploadCount = 0;
}
}
}
{
while( !isLimited || currentAllowedUploadCount > 0 ) {
FrostUploadItem ulItem = FileTransferManager.inst().getUploadManager().selectNextUploadItem();
if( ulItem == null ) {
break;
}
// start the upload
if( isDDA() ) {
boolean doMime;
if( ulItem.isSharedFile() ) {
doMime = false;
} else {
doMime = true;
}
fcpTools.startPersistentPut(
ulItem.getGqIdentifier(),
ulItem.getFile(),
doMime);
} else {
// if UploadManager selected this file then it is not already in progress!
directTransferQueue.appendItemToQueue(ulItem);
}
ulItem.setState(FrostUploadItem.STATE_PROGRESS);
currentAllowedUploadCount--;
}
}
}
private void startNewDownloads() {
boolean isLimited = true;
int currentAllowedDownloadCount = 0;
{
int allowedConcurrentDownloads = Core.frostSettings.getIntValue(SettingsClass.DOWNLOAD_MAX_THREADS);
if( allowedConcurrentDownloads <= 0 ) {
isLimited = false;
} else {
int runningDownloads = 0;
for(FrostDownloadItem dlItem : downloadModelItems.values() ) {
if( !dlItem.isExternal() && dlItem.getState() == FrostDownloadItem.STATE_PROGRESS) {
runningDownloads++;
}
}
currentAllowedDownloadCount = allowedConcurrentDownloads - runningDownloads;
if( currentAllowedDownloadCount < 0 ) {
currentAllowedDownloadCount = 0;
}
}
}
{
while( !isLimited || currentAllowedDownloadCount > 0 ) {
FrostDownloadItem dlItem = FileTransferManager.inst().getDownloadManager().selectNextDownloadItem();
if (dlItem == null) {
break;
}
// start the download
String gqid = dlItem.getGqIdentifier();
File targetFile = new File(Core.frostSettings.getValue(SettingsClass.DIR_DOWNLOAD) + dlItem.getFilename());
dlItem.setDirect( !fcpTools.isDDA() ); // set before start!
fcpTools.startPersistentGet(
dlItem.getKey(),
gqid,
targetFile);
dlItem.setState(FrostDownloadItem.STATE_PROGRESS);
currentAllowedDownloadCount--;
}
}
}
private void showExternalUploadItems() {
Map<String,FcpPersistentPut> items = persistentQueue.getUploadRequests();
for(FcpPersistentPut uploadRequest : items.values() ) {
if( !uploadModelItems.containsKey(uploadRequest.getIdentifier()) ) {
addExternalItem(uploadRequest);
}
}
}
private void showExternalDownloadItems() {
Map<String,FcpPersistentGet> items = persistentQueue.getDownloadRequests();
for(FcpPersistentGet downloadRequest : items.values() ) {
if( !uploadModelItems.containsKey(downloadRequest.getIdentifier()) ) {
addExternalItem(downloadRequest);
}
}
}
private void addExternalItem(FcpPersistentPut uploadRequest) {
final FrostUploadItem ulItem = new FrostUploadItem();
ulItem.setGqIdentifier(uploadRequest.getIdentifier());
ulItem.setExternal(true);
// direct uploads maybe have no filename, use identifier
String fileName = uploadRequest.getFilename();
if( fileName == null ) {
fileName = uploadRequest.getIdentifier();
}
ulItem.setFile(new File(fileName));
ulItem.setState(FrostUploadItem.STATE_PROGRESS);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
uploadModel.addExternalItem(ulItem);
}
});
applyState(ulItem, uploadRequest);
}
private void addExternalItem(FcpPersistentGet downloadRequest) {
// direct downloads maybe have no filename, use identifier
String fileName = downloadRequest.getFilename();
if( fileName == null ) {
fileName = downloadRequest.getIdentifier();
}
final FrostDownloadItem dlItem = new FrostDownloadItem(
fileName,
downloadRequest.getUri());
dlItem.setExternal(true);
dlItem.setGqIdentifier(downloadRequest.getIdentifier());
dlItem.setState(FrostDownloadItem.STATE_PROGRESS);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadModel.addExternalItem(dlItem);
}
});
applyState(dlItem, downloadRequest);
}
public boolean isDirectTransferInProgress(FrostDownloadItem dlItem) {
String id = dlItem.getGqIdentifier();
return directGETsInProgress.contains(id);
}
public boolean isDirectTransferInProgress(FrostUploadItem ulItem) {
String id = ulItem.getGqIdentifier();
if( directPUTsInProgress.contains(id) ) {
return true;
}
if( directPUTsWithoutAnswer.contains(id) ) {
return true;
}
return false;
}
private class DirectTransferThread extends Thread {
public void run() {
final int maxAllowedExceptions = 5;
int occuredExceptions = 0;
while(true) {
try {
// if there is no work in queue this call waits for a new queue item
ModelItem item = directTransferQueue.getItemFromQueue();
if( item == null ) {
// paranoia, should never happen
Mixed.wait(5*1000);
continue;
}
if( item instanceof FrostUploadItem ) {
// transfer bytes to node
FrostUploadItem ulItem = (FrostUploadItem) item;
// FIXME: provide item, state=Transfer to node, % shows progress
String gqid = ulItem.getGqIdentifier();
File sourceFile = ulItem.getFile();
boolean doMime;
if( ulItem.isSharedFile() ) {
doMime = false;
} else {
doMime = true;
}
NodeMessage answer = fcpTools.startDirectPersistentPut(gqid, sourceFile, doMime);
if( answer == null ) {
String desc = "Could not open a new FCP2 socket for direct put!";
FcpResultPut result = new FcpResultPut(FcpResultPut.Error, -1, desc, false);
FileTransferManager.inst().getUploadManager().notifyUploadFinished(ulItem, result);
logger.severe(desc);
} else {
// wait for an answer, don't start request again
directPUTsWithoutAnswer.add(gqid);
}
directPUTsInProgress.remove(gqid);
} else if( item instanceof FrostDownloadItem ) {
// transfer bytes from node
FrostDownloadItem dlItem = (FrostDownloadItem) item;
// FIXME: provide item, state=Transfer from node, % shows progress
String gqid = dlItem.getGqIdentifier();
File targetFile = new File(Core.frostSettings.getValue(SettingsClass.DIR_DOWNLOAD) + dlItem.getFilename());
NodeMessage answer = fcpTools.startDirectPersistentGet(gqid, targetFile);
if( answer != null ) {
FcpResultGet result = new FcpResultGet(true);
FileTransferManager.inst().getDownloadManager().notifyDownloadFinished(dlItem, result, targetFile);
} else {
logger.severe("Could not open a new fcp socket for direct get!");
FcpResultGet result = new FcpResultGet(false);
FileTransferManager.inst().getDownloadManager().notifyDownloadFinished(dlItem, result, targetFile);
}
directGETsInProgress.remove(gqid);
}
} catch(Throwable t) {
logger.log(Level.SEVERE, "Exception catched",t);
occuredExceptions++;
}
if( occuredExceptions > maxAllowedExceptions ) {
logger.log(Level.SEVERE, "Stopping DirectTransferThread because of too much exceptions");
break;
}
}
}
}
/**
* A queue class that queues items waiting for its direct transfer (put to node or get from node).
*/
private class DirectTransferQueue {
private LinkedList<ModelItem> queue = new LinkedList<ModelItem>();
public synchronized ModelItem getItemFromQueue() {
try {
// let dequeueing threads wait for work
while( queue.isEmpty() ) {
wait();
}
} catch (InterruptedException e) {
return null; // waiting abandoned
}
if( queue.isEmpty() == false ) {
ModelItem item = queue.removeFirst();
return item;
}
return null;
}
public synchronized void appendItemToQueue(FrostDownloadItem item) {
String id = item.getGqIdentifier();
directGETsInProgress.add(id);
queue.addLast(item);
notifyAll(); // notify all waiters (if any) of new record
}
public synchronized void appendItemToQueue(FrostUploadItem item) {
String id = item.getGqIdentifier();
directPUTsInProgress.add(id);
queue.addLast(item);
notifyAll(); // notify all waiters (if any) of new record
}
public synchronized int getQueueSize() {
return queue.size();
}
}
public void persistentRequestAdded(FcpPersistentPut uploadRequest) {
if( uploadModelItems.containsKey(uploadRequest.getIdentifier()) ) {
System.out.println("PUT item already in queue: "+uploadRequest.getIdentifier());
return;
}
FrostUploadItem ulItem = uploadModelItems.get(uploadRequest.getIdentifier());
if( ulItem != null ) {
// own item added to queue
applyState(ulItem, uploadRequest);
} else {
if( showExternalItemsUpload ) {
addExternalItem(uploadRequest);
}
}
}
public void persistentRequestAdded(FcpPersistentGet downloadRequest) {
if( downloadModelItems.containsKey(downloadRequest.getIdentifier()) ) {
System.out.println("GET item already in queue: "+downloadRequest.getIdentifier());
return;
}
FrostDownloadItem dlItem = downloadModelItems.get(downloadRequest.getIdentifier());
if( dlItem != null ) {
// own item added to queue
applyState(dlItem, downloadRequest);
} else {
if ( showExternalItemsDownload ) {
addExternalItem(downloadRequest);
}
}
}
public void persistentRequestModified(FcpPersistentPut uploadRequest) {
if( uploadModelItems.containsKey(uploadRequest.getIdentifier()) ) {
FrostUploadItem ulItem = uploadModelItems.get(uploadRequest.getIdentifier());
ulItem.setPriority(uploadRequest.getPriority());
}
}
public void persistentRequestModified(FcpPersistentGet downloadRequest) {
if( downloadModelItems.containsKey(downloadRequest.getIdentifier()) ) {
FrostDownloadItem dlItem = downloadModelItems.get(downloadRequest.getIdentifier());
dlItem.setPriority(downloadRequest.getPriority());
}
}
public void persistentRequestRemoved(FcpPersistentPut uploadRequest) {
if( uploadModelItems.containsKey(uploadRequest.getIdentifier()) ) {
final FrostUploadItem ulItem = uploadModelItems.get(uploadRequest.getIdentifier());
if( ulItem.isExternal() ) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
uploadModel.removeItems(new ModelItem[] { ulItem });
}
});
} else {
if( ulItem.getState() != FrostUploadItem.STATE_DONE ) {
ulItem.setEnabled(false);
ulItem.setState(FrostUploadItem.STATE_FAILED);
ulItem.setErrorCodeDescription("Disappeared from global queue");
}
}
}
}
public void persistentRequestRemoved(FcpPersistentGet downloadRequest) {
if( downloadModelItems.containsKey(downloadRequest.getIdentifier()) ) {
final FrostDownloadItem dlItem = downloadModelItems.get(downloadRequest.getIdentifier());
if( dlItem.isExternal() ) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadModel.removeItems(new ModelItem[] { dlItem });
}
});
} else {
if( dlItem.getState() != FrostDownloadItem.STATE_DONE ) {
dlItem.setEnabled(false);
dlItem.setState(FrostUploadItem.STATE_FAILED);
dlItem.setErrorCodeDescription("Disappeared from global queue");
}
}
}
}
public void persistentRequestUpdated(FcpPersistentPut uploadRequest) {
FrostUploadItem ui = uploadModelItems.get(uploadRequest.getIdentifier());
if( ui == null ) {
// not (yet) in our model
return;
}
applyState(ui, uploadRequest);
}
public void persistentRequestUpdated(FcpPersistentGet downloadRequest) {
FrostDownloadItem dl = downloadModelItems.get( downloadRequest.getIdentifier() );
if( dl == null ) {
// not (yet) in our model
return;
}
applyState(dl, downloadRequest);
}
}
| [
"[email protected]"
]
| |
b07da29455eae08c1249cb67175f196d00401978 | b2d7b0517bc16e6a0cf281b1424178413b55b947 | /java-basic/src/main/java/ch20/b/Test04.java | 51ccd00ea6a2cc7cb0289c4c35b9fd104f7be12a | []
| no_license | gwanghosong/bitcamp-java-2018-12 | 5ea3035c1beb5b9ce7c5348503daf5ed72304dc9 | 8782553c4505c5943db0009b6a2ebf742c84e38c | refs/heads/master | 2021-08-06T20:30:07.181054 | 2019-06-26T16:18:50 | 2019-06-26T16:18:50 | 163,650,672 | 0 | 0 | null | 2020-04-30T06:28:29 | 2018-12-31T08:00:40 | Java | UTF-8 | Java | false | false | 690 | java | // Stack ํด๋์ค ์ฌ์ฉ๋ฒ - search()
package ch20.b;
import java.util.Stack;
public class Test04 {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
// push() - ์คํ์ ๋งจ ๋ง์ง๋ง์ ๊ฐ์ ์ถ๊ฐํ๋ค.
stack.push("aaa");
stack.push("bbb");
stack.push("ccc");
// search() - ์คํ์ ๋งจ ์์์๋ถํฐ ํด๋น ๊ฐ์ ์ฐพ๋๋ค. ์์น๋ ๋งจ ์๊ฐ 1์ด๋ค.
System.out.println(stack.search(new String("ccc"))); // 1
System.out.println(stack.search(new String("bbb"))); // 2
System.out.println(stack.search(new String("aaa"))); // 3
System.out.println(stack.search(new String("xxx"))); // -1
}
}
| [
"[email protected]"
]
| |
d6e6b6d3ab1ed41e70672812e5709568b9100ba8 | 5ea0b17410de120c026bec33561f13df87839bcc | /transport.http2/src/main/java/io/unreach/israel/transport/Http2Client.java | 61199c1a1b7b98f66e552f4777895d57cf200b4c | [
"Apache-2.0"
]
| permissive | unreach/israel | 455bdbd7a517dcd487fff1e953c622fd16ae3866 | c9e1ba8cc9184d4a052f45a48434ee5feb4b74a9 | refs/heads/master | 2021-07-09T21:13:45.734724 | 2017-10-10T16:04:21 | 2017-10-10T16:04:21 | 104,069,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,765 | java | package io.unreach.israel.transport;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.unreach.israel.ServiceProvider;
import io.unreach.israel.exception.TimeoutException;
import io.unreach.israel.transport.internal.client.Http2ClientInitializer;
import io.unreach.israel.transport.internal.client.Http2SettingsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* netty http2 client
*
* @author joe
*/
public class Http2Client implements Client {
private static final Logger logger = LoggerFactory.getLogger(Http2Client.class);
private final static ConcurrentHashMap<String, EventLoopGroup> eventLoopGroups = new ConcurrentHashMap<>();
@Override
public Channel connect(ServiceProvider provider) throws TimeoutException {
Channel israelChannel = new Channel();
EventLoopGroup workerGroup = new NioEventLoopGroup();
eventLoopGroups.put(provider.getId(), workerGroup);
// Configure the client.
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.remoteAddress(provider.getHost(), provider.getPort() == 0 ? 80 : provider.getPort());
Http2ChannelHandler channelHandler = new Http2ChannelHandler(provider.getId());
Http2ClientInitializer initializer = new Http2ClientInitializer(channelHandler, SslUtils.getClientSsl(), Integer.MAX_VALUE);
b.handler(initializer);
israelChannel.setProvider(provider);
// Start the client.
try {
io.netty.channel.Channel channel = b.connect().syncUninterruptibly().channel();
Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
channelHandler.setChannel(channel);
israelChannel.setHandler(channelHandler);
israelChannel.setStatus(ChannelStatus.CONNECTED);
} catch (Exception e) {
logger.error("connect server " + provider.getId() + " error:", e);
israelChannel.setStatus(ChannelStatus.DISCONNECTED);
}
return israelChannel;
}
@Override
public void destory(Channel channel) {
io.netty.channel.Channel channel1 = (io.netty.channel.Channel) channel.handler.getChannel();
channel1.close().syncUninterruptibly();
eventLoopGroups.get(channel.getProvider().getId()).shutdownGracefully();
}
}
| [
"[email protected]"
]
| |
231081e97cf3c3d2ae7be9477b3d735bcb04c0dc | b7165942830ce589320669f8bd6fcf477764b146 | /FrontEnd/Android Studio/Transit/app/src/main/java/com/example/transit/CustomerPage.java | 343c27de7d1eadd1903c000d8ef0156aeaf8af33 | []
| no_license | skinnyg17/Transit | 69deeb9c684c841c06ff42bc2f76c9e194486785 | 34d282aad36cb7e57216bc944238c804dd70085c | refs/heads/main | 2023-05-21T12:55:08.704435 | 2021-06-07T19:33:33 | 2021-06-07T19:33:33 | 374,775,666 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,810 | java | package com.example.transit;
import android.Manifest;
import android.content.Intent;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class CustomerPage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private String userName;
private DrawerLayout drawer;
private NavigationView navigationView;
private Button scan;
public static final int REQUEST_CODE = 100;
public static final int PERMISSION_REQUEST = 200;
private TableLayout tableLayout;
private JSONArray array;
private String scanResult;
private TextView title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_page);
userName = getIntent().getStringExtra("username");
System.out.println(userName);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title=findViewById(R.id.tv_welcome);
title.setText("Welcome, "+userName);
drawer = findViewById(R.id.drawer_layout_Customer);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST);
}
scan = findViewById(R.id.customer_scan);
scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cus_scan = new Intent(CustomerPage.this, CustomerScan.class);
cus_scan.putExtra("userName", userName);
startActivity(cus_scan);
}
});
tableLayout = findViewById(R.id.request_table);
array = new JSONArray();
setUserName();
getRequestList();
}
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.nav_request){
Intent customer_req = new Intent(this, CustomerRequest.class);
customer_req.putExtra("username", userName);
startActivity(customer_req);
}
else if(id == R.id.nav_chat){
Intent intent = new Intent( CustomerPage.this, GeneralChatPage.class );
intent.putExtra("userName",userName);
intent.putExtra("type","customer");
startActivityForResult(intent,1);
}
else if(id == R.id.nav_track){
Intent intent = new Intent( CustomerPage.this, CustomerTrack.class );
startActivity(intent);
}
else if(id == R.id.C_SignOut){
Intent intent = new Intent( this, MainActivity.class );
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
this.startActivity( intent );
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
if(data != null){
final Barcode barcode = data.getParcelableExtra("barcode");
scanResult = barcode.displayValue;
}
}
}
public void getRequestList() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://" + getString(R.string.ip_address) + ":8080/customerPage/CustomerRequestList";
final customerHelper c = new customerHelper();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject send = new JSONObject(response);
array = c.getJSONFromString(send);
System.out.println(array.toString() + "first");
fillTable();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.fillInStackTrace());
Toast.makeText(CustomerPage.this, "Failed to create request.", Toast.LENGTH_SHORT).show();
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private void fillTable(){
System.out.println(array.toString() + "second");
LinearLayout.LayoutParams tableRowParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(tableRowParams);
/* create cell element - textview */
TextView tv1 = new TextView(this);
tv1.setBackgroundColor(0xff12dd12);
tv1.setText("cost");
TextView tv3 = new TextView(this);
tv3.setBackgroundColor(0xff12dd12);
tv3.setText("destination");
TextView tv4 = new TextView(this);
tv4.setBackgroundColor(0xff12dd12);
tv4.setText("pickup");
TextView tv5 = new TextView(this);
tv5.setBackgroundColor(0xff12dd12);
tv5.setText("box");
TextView tv6 = new TextView(this);
tv6.setBackgroundColor(0xff12dd12);
tv6.setText("status");
tableRow.addView(tv1);
tableRow.addView(tv3);
tableRow.addView(tv4);
tableRow.addView(tv5);
tableRow.addView(tv6);
tableLayout.addView(tableRow, 0);
for (int i = 0; i < array.length(); i++) {
try {
JSONObject request = new JSONObject((String) array.get(i));
LinearLayout.LayoutParams tableRowParams1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
/* create a table row */
TableRow requestlist = new TableRow(this);
requestlist.setLayoutParams(tableRowParams1);
/* create cell element - textview */
TextView cost = new TextView(this);
cost.setBackgroundColor(0xff12dd12);
cost.setText(request.get("cost").toString());
TextView destination = new TextView(this);
destination.setBackgroundColor(0xff12dd12);
destination.setText(request.get("destination").toString());
TextView pickup = new TextView(this);
pickup.setBackgroundColor(0xff12dd12);
pickup.setText(request.get("pickup").toString());
TextView box = new TextView(this);
box.setBackgroundColor(0xff12dd12);
box.setText(request.get("box").toString());
TextView status = new TextView(this);
status.setBackgroundColor(0xff12dd12);
status.setText(request.get("status").toString());
/* add views to the row */
requestlist.addView(cost);
requestlist.addView(destination);
requestlist.addView(pickup);
requestlist.addView(box);
requestlist.addView(status);
/* add the row to the table */
tableLayout.addView(requestlist,i + 1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void setUserName(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://"+getString(R.string.ip_address)+":8080/customerPage/setUserName";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println("user set");
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
System.out.println(error.fillInStackTrace());
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userName",userName);
return params;
}
};
queue.add(postRequest);
}
}
| [
"[email protected]"
]
| |
61d55e898f7f0de2fe44a614994ac0419fadc559 | 4f2b70c5154fa1bc0e0de1c530f000657bf4e3bb | /e08-shop-pay-web-1815/src/main/java/cn/icloudit/callback/service/YinLianCallbackService.java | 537b484a251821c34ca594ccc2a6e66853d519f0 | []
| no_license | 41335735/shop | 2caaeac9c98c70a6e3944ed28943569e648d46a3 | bea9a46f8a488e74f0971214081d1aa9e9e1c96d | refs/heads/master | 2020-05-21T06:31:46.336381 | 2019-04-11T08:19:55 | 2019-04-11T08:19:55 | 185,947,028 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,184 | java | package cn.icloudit.callback.service;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import cn.icloudit.common.api.ShopResult;
import cn.icloudit.common.constants.*;
import cn.icloudit.entity.PaymentInfo;
import cn.icloudit.feign.PaymentInfoFeign;
import cn.icloudit.utils.DateUtils;
import cn.icloudit.utils.ResultUils;
import com.unionpay.acp.sdk.AcpService;
import com.unionpay.acp.sdk.LogUtil;
import com.unionpay.acp.sdk.SDKConstants;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class YinLianCallbackService implements CallbackService {
@Autowired
private PaymentInfoFeign paymentInfoFeign;
@Override
public Map<String, String> syn(HttpServletRequest req) {
LogUtil.writeLog("FrontRcvResponseๅๅฐๆฅๆถๆฅๆ่ฟๅๅผๅง");
try {
String encoding = req.getParameter(SDKConstants.param_encoding);
Map<String, String> valideData = valideData(req, encoding);
return valideData;
} catch (Exception e) {
log.error("#####YinLianCallbackService##syn() ERROR:", e);
return null;
} finally {
LogUtil.writeLog("FrontRcvResponseๅๅฐๆฅๆถๆฅๆ่ฟๅ็ปๆ");
}
}
@SuppressWarnings({ "static-access", "unchecked" })
@Override
public String asyn(HttpServletRequest req) {
LogUtil.writeLog("BackRcvResponseๆฅๆถๅๅฐ้็ฅๅผๅง");
String encoding = req.getParameter(SDKConstants.param_encoding);
Map<String, String> valideData = valideData(req, encoding);
// ้่ฆ๏ผ้ช่ฏ็ญพๅๅไธ่ฆไฟฎๆนreqParamไธญ็้ฎๅผๅฏน็ๅ
ๅฎน๏ผๅฆๅไผ้ช็ญพไธ่ฟ
if (!AcpService.validate(valideData, encoding)) {
LogUtil.writeLog("้ช่ฏ็ญพๅ็ปๆ[ๅคฑ่ดฅ].");
// ้ช็ญพๅคฑ่ดฅ๏ผ้่งฃๅณ้ช็ญพ้ฎ้ข
return "fail";
}
LogUtil.writeLog("้ช่ฏ็ญพๅ็ปๆ[ๆๅ].");
// ใๆณจ๏ผไธบไบๅฎๅ
จ้ช็ญพๆๅๆๅบ่ฏฅๅๅๆท็ๆๅๅค็้ป่พใไบคๆๆๅ๏ผๆดๆฐๅๆท่ฎขๅ็ถๆ
String orderId = valideData.get("orderId"); // ่ทๅๅๅฐ้็ฅ็ๆฐๆฎ๏ผๅ
ถไปๅญๆฎตไนๅฏ็จ็ฑปไผผๆนๅผ่ทๅ
ShopResult byOrderIdPayInfoResult = paymentInfoFeign.getByOrderIdPayInfo(orderId);
if (byOrderIdPayInfoResult != null) {
Map<String, Object> resultMap = (Map<String, Object>) ResultUils.getResultMap(byOrderIdPayInfoResult);
if (resultMap == null) {
return Constants.PAY_FAIL;
}
String json = new JSONObject().toJSONString(resultMap);
PaymentInfo paymentInfo = new JSONObject().parseObject(json, PaymentInfo.class);
Integer state = paymentInfo.getState();
if (state.equals(1)) {
log.error("###asyn() ๅผๆญฅ้็ฅ,่ฎขๅid:{},็ถๆๅทฒ็ปไธบๅทฒๆฏไป,ไธ่ฝๅจไฟฎๆนไธบๅทฒๆฏไป.",orderId);
return Constants.PAY_SUCCESS;
}
paymentInfo.setPlatformorderId(valideData.get("queryId"));
paymentInfo.setUpdated(DateUtils.getTimestamp());
paymentInfo.setPayMessage(new JSONObject().toJSONString(valideData));
paymentInfo.setState(1);
paymentInfoFeign.updatePayInfo(paymentInfo);
log.error("###asyn() ๅผๆญฅ้็ฅ,่ฎขๅid:{},็ถๆๅทฒ็ปไธบๅทฒๆฏไป,ไฟฎๆนๆๅใ",orderId);
}
// ่ฟๅ็ป้ถ่ๆๅกๅจhttp 200 ็ถๆ็
return Constants.PAY_SUCCESS;
}
public static Map<String, String> valideData(final HttpServletRequest req,String encoding){
// ่ทๅ้ถ่้็ฅๆๅกๅจๅ้็ๅๅฐ้็ฅๅๆฐ
Map<String, String> reqParam = getAllRequestParam(req);
LogUtil.printRequestLog(reqParam);
Map<String, String> valideData = null;
if (null != reqParam && !reqParam.isEmpty()) {
Iterator<Entry<String, String>> it = reqParam.entrySet().iterator();
valideData = new HashMap<String, String>(reqParam.size());
while (it.hasNext()) {
Entry<String, String> e = it.next();
String key = (String) e.getKey();
String value = (String) e.getValue();
try {
value = new String(value.getBytes(encoding), encoding);
} catch (Exception e2) {
// TODO: handle exception
}
valideData.put(key, value);
}
}
return valideData;
}
/**
* ่ทๅ่ฏทๆฑๅๆฐไธญๆๆ็ไฟกๆฏ
*
* @param request
* @return
*/
public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
Map<String, String> res = new HashMap<String, String>();
Enumeration<?> temp = request.getParameterNames();
if (null != temp) {
while (temp.hasMoreElements()) {
String en = (String) temp.nextElement();
String value = request.getParameter(en);
res.put(en, value);
// ๅจๆฅๆไธ้ๆถ๏ผๅฆๆๅญๆฎต็ๅผไธบ็ฉบ๏ผๅไธไธ้<ไธ้ข็ๅค็ไธบๅจ่ทๅๆๆๅๆฐๆฐๆฎๆถ๏ผๅคๆญ่ฅๅผไธบ็ฉบ๏ผๅๅ ้ค่ฟไธชๅญๆฎต>
if (res.get(en) == null || "".equals(res.get(en))) {
// System.out.println("======ไธบ็ฉบ็ๅญๆฎตๅ===="+en);
res.remove(en);
}
}
}
return res;
}
}
| [
"Administrator@hp-PC"
]
| Administrator@hp-PC |
70669f7de3b87a5d0726a99b1b8853f2321195c5 | 30b9b5b13857406bc3bccd2c223a4ef0f7763bda | /src/main/java/com/example/login/Servletupdate.java | 6094179843f9009ef4f16ca3df8460a9838ede4d | []
| no_license | Getting-123/login | 80b8f39753898b649a2abe07016f19c492c4d0a9 | 711912cdb5e2d068f9e63f730621629b046fd63b | refs/heads/master | 2023-04-19T10:18:28.096404 | 2021-04-26T06:33:02 | 2021-04-26T06:37:18 | 361,642,427 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,017 | java | package com.example.login;
import Database.JDBCUtils;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebServlet(name = "Servletupdate", value = "/Servletupdate")
public class Servletupdate extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
HttpSession session=request.getSession();
String username= (String) session.getAttribute("ResetUsername");
String password=request.getParameter("password");
if ( update(password,username)){
response.sendRedirect("login.jsp");
}else {
response.sendRedirect("Reset_failure.jsp");
}
}
private boolean update(String password,String username){
Connection conn = null;
PreparedStatement pstmt = null;
if (password == null){
return false;
}
try {
conn = JDBCUtils.getConnection();
//ๅฎไนsql
String sql = "UPDATE `user` SET `password` = ? WHERE user.name=? ";
//่ทๅsqlๅฏน่ฑก
pstmt = conn.prepareStatement(sql);
//็ป๏ผ่ตๅผ
pstmt.setString(1,password);
pstmt.setString(2,username);
//ๆง่กsqlๆฅ่ฏข
int cout=pstmt.executeUpdate();
if (cout>0)
return true;
else
return false;
} catch (SQLException e) {
e.printStackTrace();
}finally {
//้ๆพ่ตๆบ
JDBCUtils.Close(conn);
}
return false;
}
}
| [
"[email protected]"
]
| |
506446acf02f420172419c7c2be8b30ae0ab9af4 | d3d8d0c62994d8436b6e84c405169ce851f17236 | /Recv2.java | 7ee8cdb40025b6b32ce5115c31816beaa2c66a64 | []
| no_license | 15711071337/RabbitMQStudy | 50186f6c8efc925da9cfe00b51d5d535b9ab731a | cf3ae00448c308402a9ec3902ba74fbf21b25312 | refs/heads/master | 2020-05-30T21:21:53.353595 | 2019-06-11T09:20:22 | 2019-06-11T09:20:22 | 189,970,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,356 | java | package com.zyf.workqueue;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.zyf.help.ConnectHelp;
/**
* ๆถ่ดน่
2
* @author zhang
*
*/
public class Recv2 {
public static final String QUEUE_NAME="test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException {
//่ทๅ้พๆฅ
Connection connect=ConnectHelp.getConnect();
//ๅปบ็ซ้้
Channel channel=connect.createChannel();
//ๅปบ็ซ้ๅ
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//ๆฅๅๆถๆฏ
DefaultConsumer consumer=new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String msg=new String(body,"utf-8");
System.out.println("Recv2 :"+msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
System.out.println("Recv2 done๏ผ");
}
}
};
//็ๅฌ
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
| [
"[email protected]"
]
| |
68366a587e5e07351385ec9bb73f1ff786437109 | c513d8ac06a9f04f0f8198b1ad0bc93330a8db53 | /HomeworkThreadConsole/src/thr/restaurant_4/HandlerClients.java | 0f95d97f032e3eacb0dee743a961900b61e978d6 | []
| no_license | makmen/Java | ed0ba16d4d55a40065bd4c5f7a66a2920fef9d76 | 8659f056fa7c8b3ff43457263138a0a2623812fb | refs/heads/master | 2022-12-26T16:40:46.014253 | 2017-05-06T16:58:56 | 2017-05-06T16:58:56 | 90,475,709 | 1 | 0 | null | 2022-12-16T10:57:36 | 2017-05-06T16:21:15 | HTML | UTF-8 | Java | false | false | 497 | java | package thr.restaurant_4;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by AMakas on 31.01.2017.
*/
public class HandlerClients implements Runnable {
private CashBox cashBox;
public CashBox getCashBox() {
return cashBox;
}
public HandlerClients(CashBox cashBox) {
this.cashBox = cashBox;
}
public void run() {
while(true) {
cashBox.handlerClients();
}
}
}
| [
"[email protected]"
]
| |
5c229f358999ccd6068d358d74cf45dc78fe8467 | 0fdd3d2c0c4672b024f99e1588be4a6f7516874b | /jpbl.java | f1dd999360e5cf4d95092f8b66d158698087cda2 | []
| no_license | svgreddy/svg-java | 13df99f623b2dbc09ef7cb82e3fe314d58b76b25 | ccf1036ebccfd08433d2547c88199676d6f07de4 | refs/heads/master | 2022-04-25T03:50:27.701029 | 2020-05-01T10:45:50 | 2020-05-01T10:45:50 | 260,433,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 913 | java | import java.awt.*;
import javax.swing.*;
class jpbl
{
public static void main(String args[])
{
JFrame f= new JFrame("Mini project");
JLabel l1,l2,l3,l4;
JTextField t1,t2,t3,t4;
f.setLayout(new BorderLayout());
t1=new JTextField("Name");
f.getContentPane().add(BorderLayout.NORTH, t1);
t2=new JTextField("e mail");
f.getContentPane().add(BorderLayout.SOUTH, t2);
t3=new JTextField("password");
f.getContentPane().add(BorderLayout.EAST, t3);
t4=new JTextField("confirm password");
f.getContentPane().add(BorderLayout.WEST, t4);
JButton b1=new JButton("Register");
f.getContentPane().add(BorderLayout.CENTER, b1);
f.pack();
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
| [
"[email protected]"
]
| |
92960492baac36ab9c6ac2417b23e0e26d1a9360 | 097df92ce1bfc8a354680725c7d10f0d109b5b7d | /com/amazon/ws/emr/hadoop/fs/shaded/com/amazonaws/services/identitymanagement/model/UntagRoleResult.java | aa9d7dcd33a684f662eca1f6242e558b551ab46a | []
| no_license | cozos/emrfs-hadoop | 7a1a1221ffc3aa8c25b1067cf07d3b46e39ab47f | ba5dfa631029cb5baac2f2972d2fdaca18dac422 | refs/heads/master | 2022-10-14T15:03:51.500050 | 2022-10-06T05:38:49 | 2022-10-06T05:38:49 | 233,979,996 | 2 | 2 | null | 2022-10-06T05:41:46 | 2020-01-15T02:24:16 | Java | UTF-8 | Java | false | false | 1,417 | java | package com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.identitymanagement.model;
import com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.AmazonWebServiceResult;
import com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.ResponseMetadata;
import java.io.Serializable;
public class UntagRoleResult
extends AmazonWebServiceResult<ResponseMetadata>
implements Serializable, Cloneable
{
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof UntagRoleResult)) {
return false;
}
UntagRoleResult other = (UntagRoleResult)obj;
return true;
}
public int hashCode()
{
int prime = 31;
int hashCode = 1;
return hashCode;
}
public UntagRoleResult clone()
{
try
{
return (UntagRoleResult)super.clone();
}
catch (CloneNotSupportedException e)
{
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() even though we're Cloneable!", e);
}
}
}
/* Location:
* Qualified Name: com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.identitymanagement.model.UntagRoleResult
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"[email protected]"
]
| |
dae62f2bf2682f603eb4695fa64c1fb1879f13ca | 4c3ab1a347dcb6d52e83b2ab2209872d6c374131 | /src/main/java/io/asfjava/ui/core/schema/CustomNumberSchema.java | cf6dbb7098c1e0cdb1b7032a5b1f1f7d2f5c01c6 | [
"MIT"
]
| permissive | almirus/sf-java-ui | 2e4031ad4e9f729d328243ed2cf2877f1732a15b | 1a9a127b013d81393c435b5995ff54ed11c13c6c | refs/heads/master | 2021-09-08T18:52:05.857457 | 2018-03-11T18:48:13 | 2018-03-11T18:48:13 | 124,784,945 | 0 | 0 | MIT | 2018-03-11T18:17:06 | 2018-03-11T18:17:06 | null | UTF-8 | Java | false | false | 389 | java | package io.asfjava.ui.core.schema;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.module.jsonSchema.types.NumberSchema;
class CustomNumberSchema extends NumberSchema {
@Override
public void enrichWithBeanProperty(BeanProperty beanProperty) {
super.enrichWithBeanProperty(beanProperty);
SchemaDecoratorUtil.get().decorate(beanProperty, this);
}
}
| [
"[email protected]"
]
| |
d1c10b8bd0675b9630ac21b769304fde87f4082e | 1576982a374f88d5f3731e6a17ac34c732870a82 | /src/test/java/stepLibrary/CommonStepLib.java | 9055383e39990460154b0c920b70349b8f445621 | []
| no_license | avnishpatel26/Expleo | 6c621deadb42443f72d8f21d47fdacbefaa86096 | 2518d3c142c5b73ab1e97b360e270c3942d6bd76 | refs/heads/main | 2023-04-25T17:16:42.129253 | 2021-05-30T14:57:08 | 2021-05-30T14:57:08 | 372,175,991 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,208 | java | package stepLibrary;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import com.vimalselvam.cucumber.listener.Reporter;
import helper.Browser;
import helper.ConfigFileReader;
import po.HomePage;
public class CommonStepLib {
public static WebDriver driver;
public static String amount, fromCurrency, toCurrency;
public static HomePage homePO;
public CommonStepLib()
{
ConfigFileReader.loadConfigs();
}
public void navigateToHomePage()
{
driver = Browser.createDriver();
driver.navigate().to(ConfigFileReader.URL);
Assert.assertEquals("Xe Currency Converter | Foreign Exchange Rates Calculator", driver.getTitle());
}
public void enterAmountAndCurrencies(String amt, String fromCCY, String toCCY)
{
amount = amt;
fromCurrency = fromCCY;
toCurrency = toCCY;
homePO = new HomePage(driver);
homePO.acceptCookies();
homePO.fillDetails(amt, fromCCY, toCCY);
}
public void clickOnConvertButton()
{
homePO = new HomePage(driver);
homePO.clickOnConvertBtn();
}
public void verifyCurrencyConversion()
{
homePO = new HomePage(driver);
String rate = homePO.getConversionRate(fromCurrency);
BigDecimal conversionRate = new BigDecimal(rate.split("=")[1].trim().split(" ")[0]);
Reporter.addStepLog("Amount : " + amount + " " + fromCurrency);
Reporter.addStepLog("Conversion Rate: " + rate);
BigDecimal actualConvertedAmount = new BigDecimal(homePO.getConvertedAmount().replace(",","").trim().split(" ")[0]).setScale(2, RoundingMode.FLOOR);
Reporter.addStepLog("Actual Converted Amount : " + actualConvertedAmount + " " + toCurrency);
//BigDecimal expectedConvertedAmount = new BigDecimal(amount).multiply(new BigDecimal(conversionRate)).round(m);
BigDecimal expectedConvertedAmount = new BigDecimal(amount).multiply(conversionRate).setScale(2, RoundingMode.FLOOR);
Reporter.addStepLog("Expected Converted Amount : " + expectedConvertedAmount + " " + toCurrency);
Assert.assertEquals(expectedConvertedAmount, actualConvertedAmount);
}
public void closeBrowser()
{
Browser.closeDriver();
}
}
| [
"[email protected]"
]
| |
5829af11bfb3926e22f56222a0a51be6aa202a90 | 15422997e8d9284bd2401d04d822fa2f076a77ea | /src/com/cjx913/mybatis/test/OrderTest.java | 36435ce989f2e27860c3c50edc2c9c9ada3a8796 | []
| no_license | cjx913/MybatisDemo | 68059736ee0572e30278eb8bd812fc2dc411302d | 303141194bd3d8bc66d7958f93b06b5cb3a1db9d | refs/heads/master | 2021-04-12T04:32:40.131321 | 2018-03-22T04:00:56 | 2018-03-22T04:00:56 | 125,738,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,477 | java | package com.cjx913.mybatis.test;
import com.cjx913.mybatis.mapper.OrderMapper;
import com.cjx913.mybatis.mapper.UserMapper;
import com.cjx913.mybatis.pojo.Order;
import com.cjx913.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class OrderTest {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void init() throws IOException {
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findOrderWithUserById(){
SqlSession session = sqlSessionFactory.openSession();
OrderMapper orderMapper = session.getMapper(OrderMapper.class);
Order order= null;
try {
order = orderMapper.findOrderWithUserById(1);
} catch (Exception e) {
session.rollback();
e.printStackTrace();
}finally {
session.close();
}
System.out.println(order.toString());
System.out.println(order.getUser().toString());
}
@After
public void release(){
}
}
| [
"[email protected]"
]
| |
52cf493c741c56601325e69825fda0c95363202d | 517cc5ffffa654fb3ce1804a5f91616946250df4 | /sb-demo-1-portlet/WEB-INF/service/com/liferay/live/sb/demo/service/StudentGPALocalServiceWrapper.java | 492478f8eaea0c0f3f539e47ed87849076392af7 | []
| no_license | jj110178/sb | 56a416eec0b60a5c888d6a77ebf282b132dc1c34 | dd4aa92f0a0059d48a9327371a658ac5769f1ba7 | refs/heads/master | 2021-01-01T17:37:36.655371 | 2013-07-19T21:10:24 | 2013-07-19T21:10:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,683 | java | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.live.sb.demo.service;
import com.liferay.portal.service.ServiceWrapper;
/**
* <p>
* This class is a wrapper for {@link StudentGPALocalService}.
* </p>
*
* @author dnebinger
* @see StudentGPALocalService
* @generated
*/
public class StudentGPALocalServiceWrapper implements StudentGPALocalService,
ServiceWrapper<StudentGPALocalService> {
public StudentGPALocalServiceWrapper(
StudentGPALocalService studentGPALocalService) {
_studentGPALocalService = studentGPALocalService;
}
/**
* Adds the student g p a to the database. Also notifies the appropriate model listeners.
*
* @param studentGPA the student g p a
* @return the student g p a that was added
* @throws SystemException if a system exception occurred
*/
public com.liferay.live.sb.demo.model.StudentGPA addStudentGPA(
com.liferay.live.sb.demo.model.StudentGPA studentGPA)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.addStudentGPA(studentGPA);
}
/**
* Creates a new student g p a with the primary key. Does not add the student g p a to the database.
*
* @param studentId the primary key for the new student g p a
* @return the new student g p a
*/
public com.liferay.live.sb.demo.model.StudentGPA createStudentGPA(
long studentId) {
return _studentGPALocalService.createStudentGPA(studentId);
}
/**
* Deletes the student g p a with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param studentId the primary key of the student g p a
* @return the student g p a that was removed
* @throws PortalException if a student g p a with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.liferay.live.sb.demo.model.StudentGPA deleteStudentGPA(
long studentId)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.deleteStudentGPA(studentId);
}
/**
* Deletes the student g p a from the database. Also notifies the appropriate model listeners.
*
* @param studentGPA the student g p a
* @return the student g p a that was removed
* @throws SystemException if a system exception occurred
*/
public com.liferay.live.sb.demo.model.StudentGPA deleteStudentGPA(
com.liferay.live.sb.demo.model.StudentGPA studentGPA)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.deleteStudentGPA(studentGPA);
}
public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() {
return _studentGPALocalService.dynamicQuery();
}
/**
* Performs a dynamic query on the database and returns the matching rows.
*
* @param dynamicQuery the dynamic query
* @return the matching rows
* @throws SystemException if a system exception occurred
*/
@SuppressWarnings("rawtypes")
public java.util.List dynamicQuery(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.dynamicQuery(dynamicQuery);
}
/**
* Performs a dynamic query on the database and returns a range of the matching rows.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param dynamicQuery the dynamic query
* @param start the lower bound of the range of model instances
* @param end the upper bound of the range of model instances (not inclusive)
* @return the range of matching rows
* @throws SystemException if a system exception occurred
*/
@SuppressWarnings("rawtypes")
public java.util.List dynamicQuery(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
int end) throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.dynamicQuery(dynamicQuery, start, end);
}
/**
* Performs a dynamic query on the database and returns an ordered range of the matching rows.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param dynamicQuery the dynamic query
* @param start the lower bound of the range of model instances
* @param end the upper bound of the range of model instances (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching rows
* @throws SystemException if a system exception occurred
*/
@SuppressWarnings("rawtypes")
public java.util.List dynamicQuery(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
int end,
com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.dynamicQuery(dynamicQuery, start, end,
orderByComparator);
}
/**
* Returns the number of rows that match the dynamic query.
*
* @param dynamicQuery the dynamic query
* @return the number of rows that match the dynamic query
* @throws SystemException if a system exception occurred
*/
public long dynamicQueryCount(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.dynamicQueryCount(dynamicQuery);
}
public com.liferay.live.sb.demo.model.StudentGPA fetchStudentGPA(
long studentId)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.fetchStudentGPA(studentId);
}
/**
* Returns the student g p a with the primary key.
*
* @param studentId the primary key of the student g p a
* @return the student g p a
* @throws PortalException if a student g p a with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.liferay.live.sb.demo.model.StudentGPA getStudentGPA(
long studentId)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.getStudentGPA(studentId);
}
public com.liferay.portal.model.PersistedModel getPersistedModel(
java.io.Serializable primaryKeyObj)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.getPersistedModel(primaryKeyObj);
}
/**
* Returns a range of all the student g p as.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of student g p as
* @param end the upper bound of the range of student g p as (not inclusive)
* @return the range of student g p as
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.liferay.live.sb.demo.model.StudentGPA> getStudentGPAs(
int start, int end)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.getStudentGPAs(start, end);
}
/**
* Returns the number of student g p as.
*
* @return the number of student g p as
* @throws SystemException if a system exception occurred
*/
public int getStudentGPAsCount()
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.getStudentGPAsCount();
}
/**
* Updates the student g p a in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
*
* @param studentGPA the student g p a
* @return the student g p a that was updated
* @throws SystemException if a system exception occurred
*/
public com.liferay.live.sb.demo.model.StudentGPA updateStudentGPA(
com.liferay.live.sb.demo.model.StudentGPA studentGPA)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.updateStudentGPA(studentGPA);
}
/**
* Updates the student g p a in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
*
* @param studentGPA the student g p a
* @param merge whether to merge the student g p a with the current session. See {@link com.liferay.portal.service.persistence.BatchSession#update(com.liferay.portal.kernel.dao.orm.Session, com.liferay.portal.model.BaseModel, boolean)} for an explanation.
* @return the student g p a that was updated
* @throws SystemException if a system exception occurred
*/
public com.liferay.live.sb.demo.model.StudentGPA updateStudentGPA(
com.liferay.live.sb.demo.model.StudentGPA studentGPA, boolean merge)
throws com.liferay.portal.kernel.exception.SystemException {
return _studentGPALocalService.updateStudentGPA(studentGPA, merge);
}
/**
* Returns the Spring bean ID for this bean.
*
* @return the Spring bean ID for this bean
*/
public java.lang.String getBeanIdentifier() {
return _studentGPALocalService.getBeanIdentifier();
}
/**
* Sets the Spring bean ID for this bean.
*
* @param beanIdentifier the Spring bean ID for this bean
*/
public void setBeanIdentifier(java.lang.String beanIdentifier) {
_studentGPALocalService.setBeanIdentifier(beanIdentifier);
}
public java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable {
return _studentGPALocalService.invokeMethod(name, parameterTypes,
arguments);
}
/**
* getStudentGPA: Returns the gpa for the given student in the given class.
*
* @param courseId
* @param studentId
* @return StudentGPA The gpa or <code>null</code> if it could not be calculated.
*/
public com.liferay.live.sb.demo.model.StudentGPA getStudentGPA(
long courseId, long studentId) {
return _studentGPALocalService.getStudentGPA(courseId, studentId);
}
/**
* getAllStudentGPAs: Returns the list of gpas for all students.
*
* @return List The list of gpas.
*/
public java.util.List<com.liferay.live.sb.demo.model.StudentGPA> getAllStudentGPAs() {
return _studentGPALocalService.getAllStudentGPAs();
}
/**
* getPoints: Returns the points for the given grade.
*
* @param grade
* @return double The points.
*/
public double getPoints(double grade) {
return _studentGPALocalService.getPoints(grade);
}
/**
* getLetterGrade: Returns the letter grade for the given gpa value.
*
* @param gpa
* @return String The letter grade.
*/
public java.lang.String getLetterGrade(double gpa) {
return _studentGPALocalService.getLetterGrade(gpa);
}
/**
* @deprecated Renamed to {@link #getWrappedService}
*/
public StudentGPALocalService getWrappedStudentGPALocalService() {
return _studentGPALocalService;
}
/**
* @deprecated Renamed to {@link #setWrappedService}
*/
public void setWrappedStudentGPALocalService(
StudentGPALocalService studentGPALocalService) {
_studentGPALocalService = studentGPALocalService;
}
public StudentGPALocalService getWrappedService() {
return _studentGPALocalService;
}
public void setWrappedService(StudentGPALocalService studentGPALocalService) {
_studentGPALocalService = studentGPALocalService;
}
private StudentGPALocalService _studentGPALocalService;
} | [
"[email protected]"
]
| |
db9be292f21b86902d7400545d9ef2967d944cb8 | 04466e52222819a5d6be7bae288cc8452693f3ad | /week-06/day-1_InterfacesAndAbstracts/Printable/src/Fleet.java | 0960cf87fda4fdf59c0a865691691a2d99fb7511 | []
| no_license | lorinczkinga/lorinczkinga | e9cc7f912f15a60fd895b659312c0e0dec01dd4f | a96ea9d80f76ac592d9b8b1d775f2d1134cfdd17 | refs/heads/master | 2020-06-07T23:18:18.528714 | 2018-08-23T18:40:14 | 2018-08-23T18:40:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 557 | java | import java.util.ArrayList ;
/**
* Created by aze on 2017.03.29..
*/
public class Fleet {
private ArrayList<Thing> things;
public Fleet() {
things = new ArrayList<>();
}
public void add(Thing thing) {
things.add(thing);
}
public ArrayList<Thing> getThings() {
return things;
}
@Override
public String toString() {
String result = "";
for(int i = 0; i < things.size(); i++) {
result += (i+1) + ". " + things.get(i) + "\n";
}
return result;
}
} | [
"[email protected]"
]
| |
fd41295802ef452a0c6fc78485723bfccabc93cc | a8b5f7c286860112d6cbe02423fc46626a8bd10b | /test2.java | 2cfe0106ebc00cf0405e48fd06f346e92c9de41c | []
| no_license | Tkizzy/gitTestingToLearn | d3ef5474138d9b4a660b348a55514739e0c061af | 55cd1aa1991d3c7703754ecb0afacd636f76a1ad | refs/heads/master | 2020-05-31T06:29:35.163110 | 2014-07-10T23:54:17 | 2014-07-10T23:54:17 | 21,714,339 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 389 | java | import java.io.*;
public class test2 {
// Given a day number in 2008, an integer between 1 and 366,
// as a command-line argument, prints the date in month/day format.
// Example:
// java DateConverter 365
// should print
// 12/30
// The code is missing two assignment statements.
public static void main (String [ ] args) {
test testObject = new test();
}
} | [
"[email protected]"
]
| |
5eb362c6395cb7db17b7e2e52091c232d4e42c6f | 4e1d73a46a6f4a94fea5bdd7d3ae3341848cede5 | /toggle-first-core/src/main/java/com/mageddo/togglefirst/activation/GradualActivationStrategy.java | fe8177f74d3f2fcdd9bc8efd2166da94b825fbf0 | [
"Apache-2.0"
]
| permissive | mageddo-projects/toggle-first | c4cb3a8f595e1f672b801e7ba015f8776cbeb2b0 | 5f83244607a6a3dcfeb65e3d77e74cdcd6a6f411 | refs/heads/master | 2020-05-09T16:09:53.086718 | 2019-11-30T12:10:49 | 2019-11-30T12:10:49 | 181,260,847 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,501 | java | package com.mageddo.togglefirst.activation;
import com.mageddo.commons.Validate;
import com.mageddo.togglefirst.FeatureMetadata;
import java.util.*;
public class GradualActivationStrategy implements ActivationStrategy {
public static final UUID ID = UUID.fromString("d781b1cb-2eab-46d5-9c12-db8b4dd53d98");
public static final String PARAM_PERCENTAGE = "percentage";
@Override
public UUID id() {
return ID;
}
@Override
public String description() {
return "Activate feature by percentage chance";
}
@Override
public boolean isActive(FeatureMetadata featureMetadata, String user) {
Validate.notNull(featureMetadata, "user is required");
final int percentage = featureMetadata.asInteger(PARAM_PERCENTAGE, 10);
if (percentage > 0) {
final int calculatedPercentage = Math.abs(calculateHashCode(featureMetadata, user)) % 100;
return calculatedPercentage < percentage;
}
return false;
}
protected int calculateHashCode(FeatureMetadata metadata, String user) {
return new StringBuilder()
.append(String.valueOf(user).toLowerCase(Locale.ENGLISH).trim())
.append(":")
.append(metadata.feature().name())
.toString().hashCode();
}
@Override
public Collection<Parameter> parameters() {
return Collections.singletonList(
ParameterBuilder
.create(PARAM_PERCENTAGE)
.label("Percentage")
.matching("\\d{1,3}")
.description(
"Percentage of users for which the feature should be active (i.e. '25' for every fourth user).")
);
}
}
| [
"[email protected]"
]
| |
8a0250ba8d2e540e3569fd31b19fc9f10c5a5cf3 | 4856284d9c7f49f9b7991fd5f116292ea602211a | /spring-cloud-alibaba-examples/reksai_cloud/oauth2/oauth2-server-by-rbac/src/main/java/red/reksai/server/mapper/TbRoleMapper.java | a1a23aae9a84d0628b6b784c6f673dc1c285a484 | [
"Apache-2.0"
]
| permissive | gnehcgnaw/spring-cloud-alibaba | 816a00bd762d333690bd9e5ede90dd3243c5d7fe | 645f6b0df88344f5f58ae7c34587f91f0ff0fbf4 | refs/heads/master | 2020-04-21T12:22:36.555226 | 2019-10-31T17:13:42 | 2019-10-31T17:13:42 | 169,559,982 | 0 | 0 | Apache-2.0 | 2019-02-07T11:18:08 | 2019-02-07T11:18:08 | null | UTF-8 | Java | false | false | 193 | java | package red.reksai.server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import red.reksai.server.daomain.TbRole;
public interface TbRoleMapper extends BaseMapper<TbRole> {
} | [
"[email protected]"
]
| |
386de8339cb9ccfa5fad128eaf63c7fc1803cf9f | 6aed6a10c724fb611a9eb8f895dfc4f026931f02 | /src/main/java/models/Titem.java | b07513bb14eac66ae30471a23da863e8980af073 | []
| no_license | alexcaas/equizapp | bc9ce990b2c2f22bcd8250e7c719421f8b4bf8e3 | 55094683dbcc87f82b0dc28f35bde2c652cb079b | refs/heads/master | 2021-01-20T03:36:35.413265 | 2014-10-08T12:27:59 | 2014-10-08T12:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,326 | java | /*
*/
package models;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Size;
/**
*
* @author alex
*/
@Entity
@Table(name = "titem")
@NamedQueries({
@NamedQuery(name = "Titem.findAll", query = "SELECT t FROM Titem t"),
@NamedQuery(name = "Titem.findByItemid", query = "SELECT t FROM Titem t WHERE t.itemid = :itemid"),
@NamedQuery(name = "Titem.findByItemstring", query = "SELECT t FROM Titem t WHERE t.itemstring = :itemstring"),
@NamedQuery(name = "Titem.findByItemdifficulty", query = "SELECT t FROM Titem t WHERE t.itemdifficulty = :itemdifficulty"),
@NamedQuery(name = "Titem.findByGroupcode", query = "SELECT t FROM Titem t WHERE t.tgroup = :tgroup")})
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class Titem implements Serializable {
@Transient
private Boolean changes;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "itemid")
private Long itemid;
@Basic(optional = false)
@Size(min = 1, max = 2147483647)
@Column(name = "itemstring")
private String itemstring;
@Basic(optional = false)
@Column(name = "itemdifficulty")
private short itemdifficulty;
@JoinColumn(name = "groupcode", referencedColumnName = "groupcode")
@ManyToOne(optional = false, fetch=FetchType.EAGER)
private Tgroup tgroup;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "titem", fetch=FetchType.EAGER, orphanRemoval=true)
private Collection<Tanswer> tanswerCollection;
public Titem() {
this.changes = false;
}
public Titem(String itemstring, short itemdifficulty , Tgroup group) {
this.itemstring = itemstring;
this.itemdifficulty = itemdifficulty;
this.tgroup = group;
this.changes = false;
}
public Long getItemid() {
return itemid;
}
public void setItemid(Long itemid) {
this.itemid = itemid;
}
public String getItemstring() {
return itemstring;
}
public void setItemstring(String itemstring) {
this.itemstring = itemstring;
}
public short getItemdifficulty() {
return itemdifficulty;
}
public void setItemdifficulty(short itemdifficulty) {
this.itemdifficulty = itemdifficulty;
}
public Tgroup getGroup() {
return tgroup;
}
public void setGroup(Tgroup group) {
this.tgroup = group;
}
public Collection<Tanswer> getTanswerCollection() {
return tanswerCollection;
}
public void setTanswerCollection(Collection<Tanswer> tanswerCollection) {
this.tanswerCollection = tanswerCollection;
}
public Boolean isChanges() {
return changes;
}
public void setChanges(Boolean changes) {
this.changes = changes;
}
@Override
public int hashCode() {
int hash = 0;
hash += (itemid != null ? itemid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Titem)) {
return false;
}
Titem other = (Titem) object;
if ((this.itemid == null && other.itemid != null) || (this.itemid != null && !this.itemid.equals(other.itemid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "models.Titem[ itemid=" + itemid + " ]";
}
}
| [
"[email protected]"
]
| |
0613c5818655c1de6b21977a7df24af17f6a527d | e05fcd9dbf340db0205da0fd548a15a87571f1ea | /src/test/java/org/sagebionetworks/migration/MigrationClientTest.java | 29238b10b385ad59bcfbb275f173eee78a0b484d | []
| no_license | hhu94/Synapse-Migration-Utility | c680d50b69173f52169a885ae6ddd99eae8e3668 | 5e739672f612126d5f2b7dad7c69bf7d96ec313f | refs/heads/develop | 2021-06-29T04:10:41.873702 | 2017-03-13T06:15:11 | 2017-03-13T06:15:11 | 103,991,151 | 0 | 0 | null | 2017-09-18T20:57:57 | 2017-09-18T20:57:57 | null | UTF-8 | Java | false | false | 9,393 | java | package org.sagebionetworks.migration;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import org.sagebionetworks.client.SynapseAdminClient;
import org.sagebionetworks.client.SynapseAdminClientImpl;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.client.exceptions.SynapseServerException;
import org.sagebionetworks.migration.utils.TypeToMigrateMetadata;
import org.sagebionetworks.repo.model.asynch.AsynchJobState;
import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus;
import org.sagebionetworks.repo.model.migration.*;
import org.sagebionetworks.repo.model.status.StackStatus;
import org.sagebionetworks.repo.model.status.StatusEnum;
import org.sagebionetworks.simpleHttpClient.SimpleHttpClientConfig;
import org.sagebionetworks.migration.factory.SynapseClientFactory;
/**
* Migration client test.
*
* @author jmhill
*
*/
public class MigrationClientTest {
private SynapseAdminClientMockState mockDestination;
private SynapseAdminClient destSynapse;
private SynapseAdminClientMockState mockSource;
private SynapseAdminClient sourceSynapse;
private SynapseClientFactory mockClientFactory;
private MigrationClient migrationClient;
@Before
public void before() throws Exception {
// Create the two stubs
mockDestination = new SynapseAdminClientMockState();
mockDestination.endpoint = "destination";
destSynapse = SynapseAdminClientMocker.createMock(mockDestination);
mockSource = new SynapseAdminClientMockState();
mockSource.endpoint = "source";
sourceSynapse = SynapseAdminClientMocker.createMock(mockSource);
mockClientFactory = Mockito.mock(SynapseClientFactory.class);
when(mockClientFactory.getDestinationClient()).thenReturn(destSynapse);
when(mockClientFactory.getSourceClient()).thenReturn(sourceSynapse);
migrationClient = new MigrationClient(mockClientFactory, 1000);
}
// Used to fail after moving to SimpleHttpClient
@Test
public void testLogging() throws Exception {
SimpleHttpClientConfig config = new SimpleHttpClientConfig();
config.setConnectTimeoutMs(1000*60);
config.setSocketTimeoutMs(1000*60*10);
SynapseAdminClientImpl synapse = new SynapseAdminClientImpl(config);
}
@Test
public void testSetDestinationStatus() throws Exception {
// Set the status to down
migrationClient.setDestinationStatus(StatusEnum.READ_ONLY, "Test message");
// Only the destination should be changed
StackStatus status = destSynapse.getCurrentStackStatus();
StackStatus expected = new StackStatus();
expected.setCurrentMessage("Test message");
expected.setStatus(StatusEnum.READ_ONLY);
assertEquals(expected, status);
// The source should remain unmodified
status = sourceSynapse.getCurrentStackStatus();
expected = new StackStatus();
expected.setCurrentMessage("Synapse is read for read/write");
expected.setStatus(StatusEnum.READ_WRITE);
assertEquals(expected, status);
}
@Test
public void testGetCommonMigrationTypes() throws Exception {
MigrationTypeNames expectedSrcTypeNames = new MigrationTypeNames();
expectedSrcTypeNames.setList(Arrays.asList("PRINCIPAL", "GROUP_MEMBERS", "CREDENTIAL"));
MigrationTypeNames expectedDestTypeNames = new MigrationTypeNames();
expectedDestTypeNames.setList(Arrays.asList("PRINCIPAL", "CREDENTIAL", "PRINCIPAL_ALIAS"));
List<MigrationType> expectedCommonTypes = Arrays.asList(MigrationType.PRINCIPAL, MigrationType.CREDENTIAL);
SynapseAdminClient mockSrc = Mockito.mock(SynapseAdminClient.class);
when(mockSrc.getMigrationTypeNames()).thenReturn(expectedSrcTypeNames);
SynapseAdminClient mockDest = Mockito.mock(SynapseAdminClient.class);
when(mockDest.getMigrationTypeNames()).thenReturn(expectedDestTypeNames);
SynapseClientFactory mf = Mockito.mock(SynapseClientFactory.class);
when(mf.getSourceClient()).thenReturn(mockSrc);
when(mf.getDestinationClient()).thenReturn(mockDest);
MigrationClient migClient = new MigrationClient(mf, 1000);
List<MigrationType> commonTypes = migClient.getCommonMigrationTypes();
assertEquals(expectedCommonTypes, commonTypes);
}
/**
* Test the full migration of data from the source to destination.
*/
@Test
public void testMigrateTypes() throws Exception{
// Setup the destination
// The first element should get deleted and second should get updated.
List<RowMetadata> list = createRowMetadataList(new Long[]{1L, 2L}, new String[]{"e1","e2"}, new Long[]{null, null});
mockDestination.metadata.put(MigrationType.values()[0], list);
// Setup a second type with no values
list = createRowMetadataList(new Long[]{}, new String[]{}, new Long[]{});
mockDestination.metadata.put(MigrationType.values()[1], list);
mockDestination.currentChangeNumberStack.push(11L);
mockDestination.currentChangeNumberStack.push(0L);
mockDestination.maxChangeNumber = 11L;
// setup the source
// The first element should get trigger an update and the second should trigger an add
list = createRowMetadataList(new Long[]{2L, 3L}, new String[]{"e2changed","e3"}, new Long[]{null, 1l});
mockSource.metadata.put(MigrationType.values()[0], list);
// both values should get added
list = createRowMetadataList(new Long[]{5L, 6L}, new String[]{"e5","e6"}, new Long[]{null, 6L});
mockSource.metadata.put(MigrationType.values()[1], list);
List<TypeToMigrateMetadata> typesToMigrateMetadata = createTypeToMigrateMetadataList(
Arrays.copyOfRange(MigrationType.values(), 0, 2),
new Long[]{2L, 5L}, new Long[]{3L, 6L}, new Long[]{2L, 2L},
new Long[]{1L, 0L}, new Long[]{2L, 0L}, new Long[]{1L, 0L});
// Migrate the data
migrationClient.migrateTypes(typesToMigrateMetadata, 10L, 10L, 1000*60);
// Now validate the results
List<RowMetadata> expected0 = createRowMetadataList(new Long[]{2L, 3L}, new String[]{"e2changed","e3"}, new Long[]{null, 1l});
List<RowMetadata> expected1 = createRowMetadataList(new Long[]{5L, 6L}, new String[]{"e5","e6"}, new Long[]{null, 6L});
// check the state of the destination.
assertEquals(expected0, mockDestination.metadata.get(MigrationType.values()[0]));
assertEquals(expected1, mockDestination.metadata.get(MigrationType.values()[1]));
// Check the state of the source
assertEquals(expected0, mockSource.metadata.get(MigrationType.values()[0]));
assertEquals(expected1, mockSource.metadata.get(MigrationType.values()[1]));
// no messages should have been played on the destination.
assertEquals(0, mockDestination.replayChangeNumbersHistory.size());
// No messages should have been played on the source
assertEquals(0, mockSource.replayChangeNumbersHistory.size());
}
@Test
public void testGetTypeCountRetryAsync() throws Exception {
SynapseAdminClient mockConn = Mockito.mock(SynapseAdminClient.class);
MigrationType t = MigrationType.values()[0];
SynapseException e = new SynapseServerException(503);
when(mockConn.getTypeCount(any(MigrationType.class))).thenThrow(e);
AsynchronousJobStatus expectedStatus = Mockito.mock(AsynchronousJobStatus.class);;
when(expectedStatus.getJobId()).thenReturn("1");
when(expectedStatus.getJobState()).thenReturn(AsynchJobState.COMPLETE);
AsyncMigrationResponse resp = Mockito.mock(AsyncMigrationResponse.class);
when(expectedStatus.getResponseBody()).thenReturn(resp);
when(mockConn.startAdminAsynchronousJob(any(AsyncMigrationRequest.class))).thenReturn(expectedStatus);
when(mockConn.getAdminAsynchronousJobStatus(anyString())).thenReturn(expectedStatus);
// Call under test
migrationClient.getTypeCount(mockConn, t);
verify(mockConn).startAdminAsynchronousJob(any(AsyncMigrationRequest.class));
}
/**
* Helper to build up lists of metadata
*/
public static List<RowMetadata> createRowMetadataList(Long[] ids, String[] etags, Long[] parentId){
List<RowMetadata> list = new LinkedList<RowMetadata>();
for (int i=0; i<ids.length; i++) {
if (ids[i] == null) {
list.add(null);
} else {
RowMetadata row = new RowMetadata();
row.setId(ids[i]);
row.setEtag(etags[i]);
row.setParentId(parentId[i]);
list.add(row);
}
}
return list;
}
public static List<TypeToMigrateMetadata> createTypeToMigrateMetadataList(MigrationType[] types, Long[] srcMins, Long[] srcMaxs, Long[] srcCounts, Long[] destMins, Long[] destMaxs, Long[] destCounts) {
List<TypeToMigrateMetadata> l = new LinkedList<TypeToMigrateMetadata>();
for (int i = 0; i < types.length; i++) {
if (types[i] == null) {
l.add(null);
} else {
TypeToMigrateMetadata tm = new TypeToMigrateMetadata();
tm.setType(types[i]);
tm.setSrcMinId(srcMins[i]);
tm.setSrcMaxId(srcMaxs[i]);
tm.setSrcCount(srcCounts[i]);
tm.setDestMinId(destMins[i]);
tm.setDestMaxId(destMaxs[i]);
tm.setDestCount(destCounts[i]);
l.add(tm);
}
}
return l;
}
}
| [
"[email protected]"
]
| |
ba68c26bac18ae9d598a1832eab321070723cdf2 | becd6812e96d93afbfd966bede99dce60e3f3036 | /plugin-crossref/src/main/java/combine/plugin/crossref/model/citeproc/CRPubReference.java | d5260573a7403c3332ec8c40930eccbbd2b3f5e5 | [
"Apache-2.0"
]
| permissive | grahamtriggs/combine | afc9cfe10a7d6638066d0b74515302e3b26fd1a0 | 6d170361ed5c3e435f4f6091ac3781a719025147 | refs/heads/master | 2021-01-15T11:30:37.090153 | 2017-09-04T22:22:59 | 2017-09-04T22:22:59 | 99,621,990 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,576 | java | package combine.plugin.crossref.model.citeproc;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CRPubReference {
// Required
@JsonProperty
private String key;
// Optional
@JsonProperty("DOI")
private String doi;
@JsonProperty("doi-asserted-by")
private String doiAssertedBy;
@JsonProperty
private String issue;
@JsonProperty("first-page")
private String firstPage;
@JsonProperty
private String volume;
@JsonProperty
private String edition;
@JsonProperty
private String component;
@JsonProperty("standard-designator")
private String standardDesignator;
@JsonProperty("standards-body")
private String standardsBody;
@JsonProperty
private String author;
@JsonProperty
private String year;
@JsonProperty
private String unstructured;
@JsonProperty("journal-title")
private String journalTitle;
@JsonProperty("article-title")
private String articleTtile;
@JsonProperty("series-title")
private String seriesTitle;
@JsonProperty("volume-title")
private String volumeTitle;
@JsonProperty("ISSN")
private String issn;
@JsonProperty("issn-type")
private String issnType;
@JsonProperty("ISBN")
private String isbn;
@JsonProperty("isbn-type")
private String isbnType;
}
| [
"[email protected]"
]
| |
4a353f0ab1296655146f096c222c3b751b41273f | 916aa7acb7ef7b2967200d6bf4432626b200dc7d | /src/main/java/com/tmorency/edu/entity/UserBills.java | 9fbb389e203fd76348d76e854fca3cc2efc5f828 | []
| no_license | TimMorency/Roomie | 7a697ebcb35e690591cf79358d483a9d45379123 | 67c3ef1477d6a62c2dd7df152af672098ad19f50 | refs/heads/master | 2020-09-23T23:33:10.775189 | 2016-12-07T01:05:38 | 2016-12-07T01:05:38 | 67,530,787 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,472 | java | package com.tmorency.edu.entity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Tim on 10/11/2016.
*/
@Entity
@Table(name = "user_bills")
public class UserBills {
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
@Column(name = "id")
private int id;
@Column(name = "roommate_id")
private int roommate_id;
@Column(name = "bill_id")
private int bill_id;
@Column(name = "split_amt")
private int split_amt;
@Column(name = "pay_by")
private Date pay_by;
@Column(name = "paid_amt")
private int paid_amt;
@Column(name = "paid")
private boolean paid;
public UserBills() {
}
public UserBills(int bill_id, int roommate_id, int split_amt, Date pay_by, int paid_amt, boolean paid) {
this.bill_id = bill_id;
this.roommate_id = roommate_id;
this.split_amt = split_amt;
this.pay_by = pay_by;
this.paid_amt = paid_amt;
this.paid = paid;
}
public int getPaid_amt() {
return paid_amt;
}
public void setPaid_amt(int paid_amt) {
this.paid_amt = paid_amt;
}
public boolean isPaid() {
return paid;
}
public void setPaid(boolean paid) {
this.paid = paid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRoommate_id() {
return roommate_id;
}
public void setRoommate_id(int roommate_id) {
this.roommate_id = roommate_id;
}
public int getBill_id() {
return bill_id;
}
public void setBill_id(int bill_id) {
this.bill_id = bill_id;
}
public int getSplit_amt() {
return split_amt;
}
public void setSplit_amt(int split_amt) {
this.split_amt = split_amt;
}
public Date getPay_by() {
return pay_by;
}
public void setPay_by(Date pay_by) {
this.pay_by = pay_by;
}
@Override
public String toString() {
return "UserBills{" +
"id=" + id +
", roommate_id=" + roommate_id +
", bill_id=" + bill_id +
", split_amt=" + split_amt +
", pay_by=" + pay_by +
", paid_amt=" + paid_amt +
", paid=" + paid +
'}';
}
}
| [
"[email protected]"
]
| |
c2db2027882d7bcf26c8c11a036091399cce372f | b513bd2163dfefd933460ca35869e948b3c566c2 | /sandbox/src/hackerrank/WeightedStrings.java | 476142137a841ecc574e313a7c72cab6434e1260 | []
| no_license | acho-bacho/java | db7ee605e14aa39944bddd912c4ce6007e75b001 | f0e7a506ddf4f7229a501a8e227aa2b963041a40 | refs/heads/master | 2020-05-30T23:10:36.393631 | 2019-10-03T03:21:10 | 2019-10-03T03:21:10 | 62,704,011 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,637 | java | package hackerrank;
import java.util.ArrayList;
import java.util.Arrays;
public class WeightedStrings {
char[] alphabet = "ABCDEFGHIJ".toCharArray();
long[] weights = new long[alphabet.length];
public String smallestString(long weight) {
String answer = "";
//char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
//char[] alphabet = "ABCDEFGHIJ".toCharArray();
//long[] weights = new long[alphabet.length];
//ะ 1
//B 2*A
//C 3*B
//D 4*C
// ...or something like that
weights[0] = 1;
for (int i = 1; i < weights.length; i++) {
// How to check for Long overflow ?? Long.MAX_VALUE
weights[i] = (long) (i + 1) * weights[i - 1];
}
System.out.println(Arrays.toString(alphabet));
System.out.println(Arrays.toString(weights));
ArrayList<String> allStrings = find(weight);
System.out.println("RESULT");
System.out.println(allStrings);
return answer;
}
private ArrayList<String> find(long weight) {
ArrayList<String> allResults = new ArrayList<String>();
for (int i = weights.length-1; i >= 0; i--) {
findHelper(weight,0, weights.length-1);
}
return allResults;
}
private ArrayList<String> findHelper(long weight, int start, int end) {
ArrayList<String> allResults = new ArrayList<String>();
for (int i = end; i >= start; i--) {
if(weights[i] == weight){
ArrayList<String> result = new ArrayList<String>();
result.add(String.valueOf(alphabet[i]));
return result;
} else if(weights[i] < weight){
//start here
int repeat = (int) (weight/weights[i]);
System.out.println(repeat + " * " + alphabet[i]);
System.out.println("weights[i] = " + weights[i] + ", start = " + start + ", end = " + end);
ArrayList<String> result = findHelper(weight-weights[i]*repeat, start,i);
if(result!=null) {
String toAdd = String.valueOf(alphabet[i]);//.repeat(repeat);
for (int j = 0; j < result.size(); j++) {
result.set(j, toAdd+result.get(j));
}
return result;
}
}
}
return allResults;
}
public static void main(String[] args) {
WeightedStrings a = new WeightedStrings();
a.smallestString(25);
//System.out.println(test);
}
}
| [
"[email protected]"
]
| |
04d368935f4656ff673230761166db3e1d7c23d3 | 91db32615d081f5367d09becc61e8dd0abd647a3 | /Model/src/com/bawaweb/grid/templates/data/cursors/SortingCriteriaValuesDataSet.java | 4965e9ea9efa9518cb50f270fc0d761eae39ab25 | []
| no_license | nonnymedhora/OffDaaGrid | 5b272c90efbe9175665ecba619b52908d5442b6d | 8904bf52dbe9357a4874f10a2b07134dd87f3a1b | refs/heads/master | 2020-04-22T06:51:15.642768 | 2019-02-11T21:42:39 | 2019-02-11T21:42:39 | 134,166,507 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,050 | java | /**
* @author Nonny Medhora
*/
package com.bawaweb.grid.templates.data.cursors;
public class SortingCriteriaValuesDataSet implements SortingCriteriaValuesDataSetInfo {
/**
* maps to cursor
* -- Cursor to fetch sorting criteria values for source
CURSOR cur_scv(p_rps_id bawaweb_source_sorting_criteria.ssc_rps_id%TYPE,
p_srt_id bawaweb_sorting_criteria.srt_id%TYPE) IS
*/
private String scv_name;
private int ssc_rps_id;
private int scv_srt_id;
public SortingCriteriaValuesDataSet() {
}
public String getScv_name() {
return this.scv_name;
}
public void setScv_name(String scv_name) {
}
public int getScv_rps_id() {
return this.ssc_rps_id;
}
public void setScv_rps_id(int id) {
this.ssc_rps_id = id;
}
public int getScv_srt_id() {
return this.scv_srt_id;
}
public void setScv_srt_id(int id) {
this.scv_srt_id = id;
}
}
| [
"w84meto"
]
| w84meto |
8d481b0346617e6aee4548c99432c45d5bcdd620 | c0f0bc28f8ba3dd880d8046bb97b68edadf0aa87 | /src/com/moneyball/storage/DiskStorage.java | d21130a10670bf98fd3030a15e457d4a834a433f | []
| no_license | pengligen/Moneyball | 4e5abd9e1413fd120234a309b68a9f0802c0e9ae | 5b2fda420c418c2de468dbd91016357c9864d14b | refs/heads/master | 2021-01-21T13:29:27.911179 | 2018-04-12T23:49:00 | 2018-04-12T23:49:00 | 102,128,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 62 | java | package com.moneyball.storage;
public class DiskStorage {
}
| [
"[email protected]"
]
| |
1fb66c79368908c33271cfbd7108bd94bf7baf32 | 93249ac332c0f24bf7642caa21f27058ba99189b | /core/plugins/org.csstudio.utility.singlesource.rap/src/org/csstudio/utility/singlesource/rap/RAPResourceHelper.java | 26da16a07b3eb7dc66f2267a973a5c6827574e56 | []
| no_license | crispd/cs-studio | 0678abd0db40f024fbae4420eeda87983f109382 | 32dd49d1eb744329dc1083b4ba30b65155000ffd | refs/heads/master | 2021-01-17T23:59:55.878433 | 2014-06-20T17:55:02 | 2014-06-20T17:55:02 | 21,135,201 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 175 | java | package org.csstudio.utility.singlesource.rap;
import org.csstudio.utility.singlesource.ResourceHelper;
public class RAPResourceHelper extends ResourceHelper {
}
| [
"[email protected]"
]
| |
7172057ace1d171e5e87487a8145c983c36e8828 | 10296e0547c49c2389f93dc47285501dee2921dd | /src/main/java/com/example/demo/controller/AttestationGroupController.java | 2d5cb376180a6ac0dc04b78c84b00ece0d539118 | []
| no_license | hkem/springbootlayui | d0a08defbbb6ccde322e6f319218c3e5e7d1473a | a8ed4d56d617cf96471cf19e7d01eaa1685e6d6b | refs/heads/master | 2023-07-10T11:24:29.034662 | 2021-08-29T01:26:30 | 2021-08-29T01:26:30 | 388,394,961 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,624 | java | package com.example.demo.controller;
import com.example.demo.common.ReturnJson;
import com.example.demo.entity.Attestation;
import com.example.demo.entity.AttestationAdmin;
import com.example.demo.entity.AttestationGroup;
import com.example.demo.service.AttestationAdminService;
import com.example.demo.service.AttestationGroupService;
import com.example.demo.service.AttestationService;
import com.example.demo.validator.AttestationGroupValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class AttestationGroupController {
SimpleDateFormat silptime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//่ฟๅ
private ReturnJson returnJson;
@Autowired
private AttestationService attestationService;
@Autowired
private AttestationGroupService attestationGroupService;
@Autowired
private AttestationAdminService attestationAdminService;
//ๅ่กจ
@RequestMapping("/admin/attestationgroup/index")
public String index(HttpServletRequest request, Model model){
AttestationGroup attestationGroup = new AttestationGroup();
List<AttestationGroup> list = attestationGroupService.allattestationgroup(attestationGroup);
model.addAttribute("attestationgrouplist",list);
CommonController commonController = new CommonController();
commonController.menucomm(request,model);
return "admin/attestationgroup/index";
}
//ๆทปๅ ้กต้ข
@RequestMapping("/admin/attestationgroup/insertview")
public String insertview(HttpServletRequest request,Model model){
Attestation attestation = new Attestation();
attestation.setParent_id(0);
List<Attestation> list = attestationService.allattestation(attestation);
for (int a=0;a<list.size();a++){
//ๆฅ2็บง
Attestation attestation2 = new Attestation();
attestation2.setParent_id(list.get(a).getAttestation_id());
List<Attestation> list2 = attestationService.allattestation(attestation2);
for (int b =0;b<list2.size();b++){
//ๆฅ3็บง
Attestation attestation3 = new Attestation();
attestation3.setParent_id(list2.get(b).getAttestation_id());
List<Attestation> list3 = attestationService.allattestation(attestation3);
list2.get(b).setParent3(list3);
}
list.get(a).setParent2(list2);
}
model.addAttribute("attestationlist",list);
CommonController commonController = new CommonController();
commonController.menucomm(request,model);
return "admin/attestationgroup/insertview";
}
//ๆทปๅ ๆไบค
@RequestMapping("/admin/attestationgroup/attestationgroupinsertpost")
@ResponseBody
public Map attestationgroupinsertpost(@Validated @RequestBody AttestationGroupValidator attestationAroupValidator, BindingResult bindingResult, HttpServletRequest request){
if(bindingResult.hasErrors()){
return returnJson.returndata(0,bindingResult.getFieldError().getDefaultMessage(),new HashMap());
}
AttestationGroup attestationAroup = new AttestationGroup();
//ๅคๆญๅ็งฐ
attestationAroup.setGroup_name(attestationAroupValidator.getGroup_name());
List<AttestationGroup> onelistname = attestationGroupService.oneattestationgroup(attestationAroup);
if(onelistname.size() > 0){
return returnJson.returndata(0,"ๅ็งฐๅทฒๅญๅจ",new HashMap());
}
String time = silptime.format(new Date());
AttestationGroup attestationAroup1 = new AttestationGroup();
attestationAroup1.setGroup_name(attestationAroupValidator.getGroup_name());
attestationAroup1.setAttestation_id(attestationAroupValidator.getAttestation_id());
attestationAroup1.setCreated_at(time);
attestationAroup1.setUpdated_at(time);
int suee = attestationGroupService.insertattestationaroup(attestationAroup1);
if(suee > 0){
return returnJson.returndata(1,"ๆทปๅ ๆๅ",new HashMap());
}else{
return returnJson.returndata(0,"ๆทปๅ ๅคฑ่ดฅ",new HashMap());
}
}
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
//ไฟฎๆน้กต้ข
@RequestMapping("/admin/attestationgroup/updateview")
public String updateview(HttpServletRequest request,Model model){
String id = request.getParameter("id");
AttestationGroup attestationGroup = new AttestationGroup();
attestationGroup.setAttestation_group_id(Integer.parseInt(id));
List<AttestationGroup> attestationgroup = attestationGroupService.oneattestationgroup(attestationGroup);
if(attestationgroup.size() <= 0){
model.addAttribute("error_str","id้่ฏฏ๏ผๆฐๆฎไธๅญๅจ");
return "admin/public/error";
}
String attestation_id = attestationgroup.get(0).getAttestation_id();
String[] attestation_idarr=attestation_id.split(",");
Attestation attestation = new Attestation();
attestation.setParent_id(0);
List<Attestation> list = attestationService.allattestation(attestation);
for (int a=0;a<list.size();a++){
//ๆฅ2็บง
Attestation attestation2 = new Attestation();
attestation2.setParent_id(list.get(a).getAttestation_id());
List<Attestation> list2 = attestationService.allattestation(attestation2);
for (int b =0;b<list2.size();b++){
//ๆฅ3็บง
Attestation attestation3 = new Attestation();
attestation3.setParent_id(list2.get(b).getAttestation_id());
List<Attestation> list3 = attestationService.allattestation(attestation3);
for(int c=0;c<list3.size();c++){
//ๅคๆญๆฏๅฆๅญๅจ
boolean cunc = useLoop(attestation_idarr,(list3.get(c).getAttestation_id()+""));
if(cunc){
list3.get(c).setExistence(1);
}else{
list3.get(c).setExistence(0);
}
}
//ๅคๆญๆฏๅฆๅญๅจ
boolean cunb = useLoop(attestation_idarr,(list2.get(b).getAttestation_id()+""));
if(cunb){
list2.get(b).setExistence(1);
}else{
list2.get(b).setExistence(0);
}
list2.get(b).setParent3(list3);
}
//ๅคๆญๆฏๅฆๅญๅจ
boolean cuna = useLoop(attestation_idarr,(list.get(a).getAttestation_id()+""));
if(cuna){
list.get(a).setExistence(1);
}else{
list.get(a).setExistence(0);
}
list.get(a).setParent2(list2);
}
model.addAttribute("attestationlist",list);
model.addAttribute("attestationgroup",attestationgroup.get(0));
CommonController commonController = new CommonController();
commonController.menucomm(request,model);
return "admin/attestationgroup/updateview";
}
//ไฟฎๆนๆไบค
@RequestMapping("/admin/attestationgroup/attestationgroupupdatepost")
@ResponseBody
public Map attestationgroupupdatepost(@Validated @RequestBody AttestationGroupValidator attestationAroupValidator, BindingResult bindingResult, HttpServletRequest request){
if(bindingResult.hasErrors()){
return returnJson.returndata(0,bindingResult.getFieldError().getDefaultMessage(),new HashMap());
}
AttestationGroup attestationAroup = new AttestationGroup();
//ๅคๆญๅ็งฐ
attestationAroup.setGroup_name(attestationAroupValidator.getGroup_name());
attestationAroup.setAttestation_group_id(attestationAroupValidator.getAttestation_group_id());
List<AttestationGroup> onelistname = attestationGroupService.oneupdateattestationgroup(attestationAroup);
if(onelistname.size() > 0){
return returnJson.returndata(0,"ๅ็งฐๅทฒๅญๅจ",new HashMap());
}
String time = silptime.format(new Date());
AttestationGroup attestationAroup1 = new AttestationGroup();
attestationAroup1.setAttestation_group_id(attestationAroupValidator.getAttestation_group_id());
attestationAroup1.setGroup_name(attestationAroupValidator.getGroup_name());
attestationAroup1.setAttestation_id(attestationAroupValidator.getAttestation_id());
attestationAroup1.setUpdated_at(time);
int suee = attestationGroupService.updateattestationgroup(attestationAroup1);
if(suee > 0){
return returnJson.returndata(1,"ๆดๆฐๆๅ",new HashMap());
}else{
return returnJson.returndata(0,"ๆดๆฐๅคฑ่ดฅ",new HashMap());
}
}
//ๅ ้ค
@RequestMapping("/admin/attestationgroup/deleteattestationgroup")
@ResponseBody
public Map deleteattestation(HttpServletRequest request){
String id = request.getParameter("id");
//ๅคๆญๆฏๅฆๆไธ็บง
AttestationAdmin attestationAdmin = new AttestationAdmin();
attestationAdmin.setAttestation_group_id(Integer.parseInt(id));
List<AttestationAdmin> list = attestationAdminService.oneattestationadmin(attestationAdmin);
if(list.size() > 0){
return returnJson.returndata(0,"ๅญๅจไธ็บง๏ผๅ ้คๅคฑ่ดฅ",new HashMap());
}
AttestationGroup attestationGroup1 = new AttestationGroup();
attestationGroup1.setAttestation_group_idstr(id);
int suee = attestationGroupService.deleteattestationgroup(attestationGroup1);
if(suee > 0){
return returnJson.returndata(1,"ๅ ้คๆๅ",new HashMap());
}else{
return returnJson.returndata(0,"ๅ ้คๅคฑ่ดฅ",new HashMap());
}
}
}
| [
"[email protected]"
]
| |
97ea63d065bd2d6e590765727c666b89cb043048 | 1044d13ad946176682f1c475fc867d86e8813482 | /src/java/stockviewer/ui/StockViewerView.java | 4ec3938030943715035772bba400fd12b8ce9138 | []
| no_license | nayakhilesh/stock-viewer | 332fc170da120981c699285fc254c1ce90d2e0e6 | 6b5e4bbf7cd6ab5cfd10194aa10f02e05678324b | refs/heads/master | 2020-05-27T07:50:19.500430 | 2013-08-22T04:49:25 | 2013-08-22T04:49:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,866 | java | package stockviewer.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stockviewer.controller.Controller;
import stockviewer.stock.StockDao;
import stockviewer.stock.StockDataException;
import stockviewer.stock.StockDataSource;
import stockviewer.stock.StockInfo;
import stockviewer.stock.StockPriceType;
import stockviewer.ui.custom.ColorChooser;
import stockviewer.ui.custom.InfiniteProgressPanel;
import stockviewer.ui.custom.StockAutoCompleter;
import stockviewer.ui.custom.TextPrompt;
import stockviewer.util.ChartUtility;
import stockviewer.util.DateUtil;
import com.toedter.calendar.JDateChooser;
public class StockViewerView implements View {
private static final Logger LOG = LoggerFactory
.getLogger(StockViewerView.class);
private static final String JDATECHOOSER_DATE_PATTERN = "MM/dd/yyyy";
private static final String JDATECHOOSER_MASK_PATTERN = "##/##/####";
private static final char JDATECHOOSER_PLACEHOLDER = '_';
private static final String ERROR = "ERROR";
private static final int STOCK_FIELD_WIDTH = 10;
private ChartUtility chartUtility;
private ExecutorService threadPool;
private Controller controller;
private JDateChooser fromDateChooser;
private JDateChooser toDateChooser;
private JTextField stock1Field;
private JTextField stock2Field;
private JComboBox stockPriceTypeBox;
private JComboBox colorChooser1;
private JComboBox colorChooser2;
private final JButton createButton;
private final InfiniteProgressPanel glassPane;
public StockViewerView(final Controller controller, StockDataSource ds,
final StockDao dao, final boolean shutDownDbOnExit) {
LOG.info("Initializing GUI");
this.controller = controller;
this.threadPool = Executors.newFixedThreadPool(1);
chartUtility = new ChartUtility();
glassPane = new InfiniteProgressPanel();
final JFrame frame = new JFrame("Stock Viewer");
frame.setLocation(310, 130);
frame.setGlassPane(glassPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
if (dao != null && shutDownDbOnExit) {
try {
dao.shutDown();
LOG.info("DB successfully shutdown");
} catch (SQLException e) {
LOG.error("Error shutting down DB", e);
}
}
LOG.info("Application exiting...");
}
});
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel dateRangeSelectionPanel = new JPanel();
JLabel from = new JLabel("From:");
JLabel to = new JLabel("To:");
fromDateChooser = new JDateChooser(JDATECHOOSER_DATE_PATTERN,
JDATECHOOSER_MASK_PATTERN, JDATECHOOSER_PLACEHOLDER);
toDateChooser = new JDateChooser(JDATECHOOSER_DATE_PATTERN,
JDATECHOOSER_MASK_PATTERN, JDATECHOOSER_PLACEHOLDER);
dateRangeSelectionPanel.add(from);
dateRangeSelectionPanel.add(fromDateChooser);
dateRangeSelectionPanel.add(to);
dateRangeSelectionPanel.add(toDateChooser);
JPanel stockPickerPanel = new JPanel();
stock1Field = new JTextField(STOCK_FIELD_WIDTH);
new StockAutoCompleter(stock1Field, ds, dao);
decorateWithPrompt(stock1Field);
stockPickerPanel.add(stock1Field);
colorChooser1 = new ColorChooser();
colorChooser1.setSelectedItem(Color.BLUE);
stockPickerPanel.add(colorChooser1);
stock2Field = new JTextField(STOCK_FIELD_WIDTH);
new StockAutoCompleter(stock2Field, ds, dao);
decorateWithPrompt(stock2Field);
stockPickerPanel.add(stock2Field);
colorChooser2 = new ColorChooser();
colorChooser2.setSelectedItem(Color.RED);
stockPickerPanel.add(colorChooser2);
JPanel controls = new JPanel();
createButton = new JButton("Create Plot");
stockPriceTypeBox = new JComboBox(StockPriceType.values());
createButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
createButton.setEnabled(false);
glassPane.start();
threadPool.execute(new Runnable() {
@Override
public void run() {
generateChart();
}
});
}
});
controls.add(stockPriceTypeBox);
controls.add(createButton);
mainPanel.add(dateRangeSelectionPanel, BorderLayout.NORTH);
mainPanel.add(stockPickerPanel, BorderLayout.CENTER);
mainPanel.add(controls, BorderLayout.SOUTH);
frame.add(mainPanel, BorderLayout.CENTER);
// Put the frame on the screen
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
LOG.info("GUI initialization complete");
}
private void decorateWithPrompt(JTextField textField) {
TextPrompt tp = new TextPrompt("Enter Ticker", textField);
tp.changeAlpha(128);
tp.changeStyle(Font.ITALIC);
}
private void generateChart() {
Date fromDate = DateUtil.treatAsGmt(fromDateChooser.getDate());
Date toDate = DateUtil.treatAsGmt(toDateChooser.getDate());
String tickerSymbol1 = stock1Field.getText();
String tickerSymbol2 = stock2Field.getText();
try {
if (isValid(fromDate, toDate, tickerSymbol1, tickerSymbol2)) {
controller.onCreateChart(fromDate, toDate, tickerSymbol1,
tickerSymbol2);
}
} catch (StockDataException e) {
if (e.getType() != null) {
String message;
switch (e.getType()) {
case NETWORK:
message = "Error, check network connectivity";
LOG.error(message, e);
errorMessagePopup(message, JOptionPane.ERROR_MESSAGE, null);
break;
case DATA_NOT_FOUND:
message = e.getLocalizedMessage()
+ ", check ticker validity";
errorMessagePopup(message, JOptionPane.ERROR_MESSAGE, null);
break;
case OTHER:
defaultErrorMessagePopup(e);
break;
default:
defaultErrorMessagePopup(e);
break;
}
} else {
defaultErrorMessagePopup(e);
}
} catch (Exception e) {
defaultErrorMessagePopup(e);
} finally {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
glassPane.stop();
createButton.setEnabled(true);
}
});
}
}
private void defaultErrorMessagePopup(Exception e) {
String message = "Error creating chart";
LOG.error(message, e);
errorMessagePopup(message, JOptionPane.ERROR_MESSAGE, null);
}
private boolean isValid(Date fromDate, Date toDate, String tickerSymbol1,
String tickerSymbol2) {
if (fromDate == null) {
String message = "Invalid From Date";
errorMessagePopup(message, JOptionPane.WARNING_MESSAGE,
fromDateChooser);
return false;
}
if (toDate == null) {
String message = "Invalid To Date";
errorMessagePopup(message, JOptionPane.WARNING_MESSAGE,
toDateChooser);
return false;
}
if (!toDate.after(fromDate)) {
String message = "To Date must be after From Date";
errorMessagePopup(message, JOptionPane.WARNING_MESSAGE,
toDateChooser);
return false;
}
if (tickerSymbol1 == null || tickerSymbol1.isEmpty()) {
String message = "Stock ticker not filled in";
errorMessagePopup(message, JOptionPane.WARNING_MESSAGE, stock1Field);
return false;
}
if (tickerSymbol2 == null || tickerSymbol2.isEmpty()) {
String message = "Stock ticker not filled in";
errorMessagePopup(message, JOptionPane.WARNING_MESSAGE, stock2Field);
return false;
}
return true;
}
private void errorMessagePopup(final String message, final int messageType,
final JComponent toFocus) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane
.showMessageDialog(null, message, ERROR, messageType);
if (toFocus != null)
toFocus.grabFocus();
}
});
}
@Override
public void onReceivingNewStockInfo(Date from, Date to, StockInfo stock1,
StockInfo stock2) {
LOG.info("Received stock info for tickers:" + stock1.getTickerSymbol()
+ " & " + stock2.getTickerSymbol());
final JPanel chartPanel = chartUtility.createChart(from, to, stock1,
stock2, (Color) colorChooser1.getSelectedItem(),
(Color) colorChooser2.getSelectedItem(),
(StockPriceType) stockPriceTypeBox.getSelectedItem());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame chartFrame = new JFrame();
chartFrame.add(chartPanel);
chartFrame.pack();
chartFrame.setVisible(true);
}
});
}
}
| [
"[email protected]"
]
| |
e035516f822d4741a0a690cd1e513694a77c903d | 720bfa347eee8146d58b77c721953873095cce39 | /JavaSource/org/unitime/timetable/model/base/BaseDesignator.java | e60fda6ecb47a9f7b57f4af3d612ce92b06c79a2 | []
| no_license | jaliste/unitime | 4022542b6952a2d540fc9136826578863f9b6565 | 0da1aa959132fdce85acc3b1ba4071491957c7a0 | refs/heads/master | 2020-05-17T13:23:34.569363 | 2012-07-13T19:36:17 | 2012-07-13T19:36:17 | 5,088,726 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,727 | java | /*
* UniTime 3.2 (University Timetabling Application)
* Copyright (C) 2010, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.model.base;
import java.io.Serializable;
import org.unitime.timetable.model.DepartmentalInstructor;
import org.unitime.timetable.model.Designator;
import org.unitime.timetable.model.SubjectArea;
public abstract class BaseDesignator implements Serializable {
private static final long serialVersionUID = 1L;
private Long iUniqueId;
private String iCode;
private SubjectArea iSubjectArea;
private DepartmentalInstructor iInstructor;
public static String PROP_UNIQUEID = "uniqueId";
public static String PROP_CODE = "code";
public BaseDesignator() {
initialize();
}
public BaseDesignator(Long uniqueId) {
setUniqueId(uniqueId);
initialize();
}
protected void initialize() {}
public Long getUniqueId() { return iUniqueId; }
public void setUniqueId(Long uniqueId) { iUniqueId = uniqueId; }
public String getCode() { return iCode; }
public void setCode(String code) { iCode = code; }
public SubjectArea getSubjectArea() { return iSubjectArea; }
public void setSubjectArea(SubjectArea subjectArea) { iSubjectArea = subjectArea; }
public DepartmentalInstructor getInstructor() { return iInstructor; }
public void setInstructor(DepartmentalInstructor instructor) { iInstructor = instructor; }
public boolean equals(Object o) {
if (o == null || !(o instanceof Designator)) return false;
if (getUniqueId() == null || ((Designator)o).getUniqueId() == null) return false;
return getUniqueId().equals(((Designator)o).getUniqueId());
}
public int hashCode() {
if (getUniqueId() == null) return super.hashCode();
return getUniqueId().hashCode();
}
public String toString() {
return "Designator["+getUniqueId()+"]";
}
public String toDebugString() {
return "Designator[" +
"\n Code: " + getCode() +
"\n Instructor: " + getInstructor() +
"\n SubjectArea: " + getSubjectArea() +
"\n UniqueId: " + getUniqueId() +
"]";
}
}
| [
"tomas13@cc804148-bb53-fe5c-6b9d-7ba62d325a45"
]
| tomas13@cc804148-bb53-fe5c-6b9d-7ba62d325a45 |
24248064082d92f8c89806706cd042bfdc9c21bf | b27747d180e2e8ecb2a5f561cf502b8bf840071d | /src/main/java/TestTask/Model/CoffeeType.java | 88aa7c6643eeae6029be1c97ea01e96a89f76b6a | []
| no_license | MarinaSapitonDev/Internet-cafe | 4801923119e6879a8a26410cf9355413cbc2ef10 | fee16a46cc7b18ac0f6942ae2a22efa7940ea462 | refs/heads/master | 2021-04-29T13:16:19.330639 | 2018-02-16T12:37:05 | 2018-02-16T12:37:05 | 121,747,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 729 | java | package TestTask.Model;
public class CoffeeType {
private Integer id;
private String type_name;
private double price;
private char disabled;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public String getType_name() {
return type_name;
}
public void setType_name(String type_name) {
this.type_name = type_name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public void setDisabled(char disabled) {
this.disabled = disabled;
}
public char getDisabled() {
return disabled;
}
}
| [
"[email protected]"
]
| |
5e65385f6ba118bbe3d800e9f69a3ad21a894b39 | e3965b3ecb8e941a8335f9dda9d5eb768d160e62 | /Bootstreping-hibernate-legacy-programetic-app-35/src/main/java/com/hibs/utility/HBNutility.java | 4347e1a77588e662d7f737322dceb744232cfad9 | []
| no_license | deepndra9755/hibernate | 59de895ac431c9b9361e83fb803168607424ce56 | 9baf5c8e4efd755b2405b4151148d6fab2a181ad | refs/heads/master | 2023-07-02T16:45:56.730295 | 2021-08-08T00:04:56 | 2021-08-08T00:04:56 | 387,090,574 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,098 | java | package com.hibs.utility;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.Entity.ProductInfo;
public class HBNutility {
static Configuration cg;
static SessionFactory sf;
static
{
cg=new Configuration();
cg.setProperty("hibernate.connection.driver_class","com.mysql.cj.jdbc.Driver");
cg.setProperty("hibernate.connection.url","jdbc:mysql://@localhost:3306/emp");
cg.setProperty("hibernate.connection.username","root");
cg.setProperty("hibernate.connection.password","root");
cg.setProperty("hibernate.show_sql","true");
cg.setProperty("hibernate.hbm2ddl.auto","update");
System.out.println(cg);
cg.addAnnotatedClass(com.hibernate.Entity.ProductInfo.class);
sf=cg.buildSessionFactory();
if(sf==null)
{
new HibernateException("session-factory not created");
}
}
public static Session getSession()
{
return sf.openSession();
}
public static void CloseSES()
{
sf.close();
}
}
| [
"cotlin@DESKTOP-RNJ3PV0"
]
| cotlin@DESKTOP-RNJ3PV0 |
aaa0442603d25ce51ed869fd133a12fb7743aeb4 | a135bab33e8fc750cec9ed65db37bd56d663af4b | /WikiImageApplication/app/src/main/java/utils/DictionaryResponseDeserializer.java | 23009841d1de52a82c6dbd5070b4de5a6b3eea37 | []
| no_license | aryan007/Microsoft | 5d609cc43f8cf6d8b0852fb2ecb1b69fba3a96ef | 0fb863bb3a99d605688146d94065a7b73806ca61 | refs/heads/master | 2021-01-21T01:44:46.021705 | 2016-06-08T21:36:22 | 2016-06-08T21:36:22 | 60,732,174 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,517 | java | package utils;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import model.Page;
import model.QueryResults;
import model.WicktionarySearchResponse;
/**
* Created by thukralp on 09/06/16.
*/
public class DictionaryResponseDeserializer implements JsonDeserializer<WicktionarySearchResponse> {
@Override
public WicktionarySearchResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonElement value = null;
WicktionarySearchResponse response = new WicktionarySearchResponse();
if(json!=null) {
value = json.getAsJsonObject().get("query").getAsJsonObject().get("pages");
if (value != null) {
Iterable<Map.Entry<String, JsonElement>> entries = value.getAsJsonObject().entrySet();
QueryResults query = new QueryResults();
List<Page> resultPages = new ArrayList<Page>();
for (Map.Entry<String, JsonElement> entry : entries) {
resultPages.add(new Gson().fromJson(entry.getValue(), Page.class));
}
query.setPages(resultPages);
response.setQuery(query);
}
}
return response;
}
}
| [
"[email protected]"
]
| |
6ffb6f70cac750ca0894a7f239a606e43d1760cb | f95f719eae358a54f3930b188193d4f1ae9d6b95 | /src/main/java/com/shop/dto/UserTransactionDTO.java | 425811e2128e767b903b3ec4b4cee8f12e4a4931 | []
| no_license | Snowenik/Spring-Backend-Shop-App | 545f1b1a1d654e1aa87360f12aa1b15529bf00cb | 2f84d56df5addc673d623d4f6025f24f14d697d4 | refs/heads/master | 2023-07-31T15:39:29.614339 | 2021-09-17T14:04:03 | 2021-09-17T14:04:03 | 407,555,796 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 145 | java | package com.shop.dto;
public class UserTransactionDTO {
private Long userId;
public Long getUserId() {
return userId;
}
}
| [
"[email protected]"
]
| |
91c0c10500957dbe6da18ea3c34a0366a0d89609 | 80901ae21649c7c15c571d0ef03f443d32de07a4 | /src/LoggerRateLimiter.java | ce51e1b62284d5a4917765963344ad55498a20c7 | [
"MIT"
]
| permissive | yi-juchung/codingPractice | fcb09fe0f572f7d4049832f2906e557707bad765 | e1336df6824800b85531e16e46413f71da23b553 | refs/heads/master | 2021-01-19T02:07:50.748717 | 2016-08-04T23:45:03 | 2016-08-04T23:45:03 | 26,622,531 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,232 | java | import java.util.HashMap;
import java.util.Map;
public class LoggerRateLimiter {
public static class Logger {
Map<String, Integer> limitMap;
public Logger() {
limitMap = new HashMap<>();
}
public boolean shouldPrintMessage(int timestamp, String message) {
boolean ablePrint = true;
if (limitMap.containsKey(message) && limitMap.get(message)+10 > timestamp) {
ablePrint = false;
} else {
limitMap.put(message,timestamp);
}
return ablePrint;
}
}
public static void main(String [ ] args) {
Logger logger = new Logger();
System.out.println(logger.shouldPrintMessage(1,"foo"));
//returns true;
System.out.println(logger.shouldPrintMessage(2,"bar"));
//returns true;
System.out.println(logger.shouldPrintMessage(3,"foo"));
//returns false;
System.out.println(logger.shouldPrintMessage(8,"bar"));
//returns false;
System.out.println(logger.shouldPrintMessage(10,"foo"));
//returns false;
System.out.println(logger.shouldPrintMessage(11,"foo"));
//returns true;
}
}
| [
"[email protected]"
]
| |
fe9161ac1cf0f60b5a30270abcbec2fd32d2c4ff | 659c39eb06bed2ed46ec099c9134bed512df692c | /src/main/java/bob/home/catalogUTMnou/repositories/ProfesorRepository.java | 2a234ef150c5271ed06b153eb2971503df23e318 | []
| no_license | bgtrifan/ProiectUTM | 60a2f0058a0005e051796358020228dbf2d1d826 | 6fbd96f11166a12fd2becab1c81755e93ff1aac1 | refs/heads/master | 2020-03-14T10:38:11.798713 | 2018-05-03T10:38:35 | 2018-05-03T10:38:35 | 131,571,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 276 | java | package bob.home.catalogUTMnou.repositories;
import bob.home.catalogUTMnou.model.Profesor;
import org.springframework.data.repository.CrudRepository;
public interface ProfesorRepository extends CrudRepository<Profesor, Long> {
Profesor findProfesorByCnp(String cnp);
}
| [
"[email protected]"
]
| |
4a37cccab4e42cd23edbe9eb4f5959ad3342dcf9 | c5ca465832467888bcd3467067db4ffd1056ddb0 | /Assignment4b/src/Assignment4b/Mammal.java | 3689fb9e30ed2c178a1d199a69f87b8bed1ba7b6 | []
| no_license | JoakimWinsgard/Pfi2 | 0160b074f63b01fe99e0690a40caf1571f47b0d4 | f1b5ac10689424c91a1365723373e0ba1a8db234 | refs/heads/master | 2020-04-22T03:27:42.151503 | 2015-04-15T19:15:03 | 2015-04-15T19:15:03 | 31,765,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java |
package Assignment4b;
public abstract class Mammal extends Animal{
public int nursingTime;
public Mammal(String latinName, String friendlyName, int nursingTime) {
super(latinName, friendlyName);
this.nursingTime = nursingTime;
}
public int getnursingTime(){
return nursingTime;
}
}
| [
"[email protected]"
]
| |
f0a0f1e159acbb31229e076f015a6b066b041902 | 5ac8eda62793d329756b4340e6faf0ac8621b212 | /src/book/headfirst/ch6/command/simpleremote/RemoteControlTest.java | e5da35e66844de99df7065c495cf87c37a58f4df | []
| no_license | talhaanik/DesignPattern | 807980f28bf1a4b333122a62c34e8ee8e8c872e5 | be9a859e1b7203604f07b89677de323204c3602e | refs/heads/master | 2022-09-25T12:15:11.106089 | 2020-06-07T17:47:17 | 2020-06-07T17:47:17 | 255,363,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package book.headfirst.ch6.command.simpleremote;
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
GarageDoor garageDoor = new GarageDoor();
LightOnCommand lightOn = new LightOnCommand(light);
GarageDoorOpenCommand garageOpen =
new GarageDoorOpenCommand(garageDoor);
remote.setCommand(lightOn);
remote.buttonWasPressed();
remote.setCommand(garageOpen);
remote.buttonWasPressed();
}
}
| [
"[email protected]"
]
| |
9256c37843940cd3431e55facb5f2006b6448361 | 73437a5c0a0cc60f73d3a1b1047b3f5adcb748fc | /calc/CalculadoraServerImpl.java | a8c427eb96e019dd5bc7937b8a70755af283ada2 | [
"MIT"
]
| permissive | leodeliyannis/soap-webservice | c44824b9b3a61ab745f47f5b6ee18c0288458160 | d571c31c187fb151b03afe6b2c9bf85f37d5b0c8 | refs/heads/master | 2020-03-18T04:53:28.636856 | 2018-05-26T19:55:32 | 2018-05-26T19:55:32 | 134,311,889 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 884 | java | /*
Implementaรงรฃo da interface CalculadoraServer seguindo o tutorial em
https://www.devmedia.com.br/desenvolvendo-e-usando-web-services-em-java/37261
### GLOSSรRIO ###
SIB:
Service Implementation Bean
endpointInterface:
Faz com que a classe atual, a SIB, ligue-se com a SEI
especificada anteriormente (calc.CalculadoraServer).
*/
package calc;
import java.util.Date;
import javax.jws.WebService;
@WebService(endpointInterface = "calc.CalculadoraServer")
public class CalculadoraServerImpl implements CalculadoraServer {
public float soma(float num1, float num2){
return num1 + num2;
}
public float subtracao(float num1, float num2){
return num1 - num2;
}
public float multiplicacao(float num1, float num2){
return num1 * num2;
}
public float divisao(float num1, float num2){
return num1 / num2;
}
}
| [
"[email protected]"
]
| |
77729bb4cec0f23d0082e6bd38270d4f883bf84a | 9f10e127b60cfc3e1c27a8b2960a4528c90d8458 | /src/main/java/com/spring/boot/rest/example/demo/repository/UserDao.java | 552400bad71ec19116a4d88ed4d4feb830bea328 | []
| no_license | KristinVishanov/SpringBootRest | 0aa0932a8d2256ded85bfa0568ed68370f61bc11 | 6f9c96f795e827d9ed7ac2e334a05c18aade949a | refs/heads/master | 2018-10-29T19:22:30.435513 | 2018-09-19T11:48:08 | 2018-09-19T11:48:08 | 117,386,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package com.spring.boot.rest.example.demo.repository;
import com.spring.boot.rest.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface UserDao extends JpaRepository<User, Long> {
}
| [
"[email protected]"
]
| |
9f571fd8ec6331e2ba57a744c2964ca72da11811 | 671853f3e29b94aa071c3a37786a88e3dc559227 | /src/com/company/FitnessCalc.java | f2b242b10700a71e076a1a9ab694a3ceab98f658 | [
"Apache-2.0"
]
| permissive | VassilisMp/WaspsAndBombs | 7c86a1850c4f19b4efb5011c7208d5126a77a074 | bc316221cdfb4a3098fb3a958e902036f5ff356e | refs/heads/master | 2020-04-15T22:13:42.008041 | 2019-07-05T19:45:11 | 2019-07-05T19:45:11 | 165,064,575 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,174 | java | package com.company;
import com.google.common.base.Splitter;
public class FitnessCalc {
public static final int maxFitness= getMaxFitness();
public static final double dMax= Main.z>0 ? Math.sqrt(Math.pow(Main.x, 2) + Math.pow(Main.y, 2)) :
Math.sqrt(Math.pow(Main.x, 2) + Math.pow(Main.y, 2) + Math.pow(Main.z, 2));// ฮผฮญฮณฮนฯฯฮท ฮฑฯฯฯฯฮฑฯฮท ฮผฮตฯฮฑฮพฯ ฮดฯฮฟ ฯฯฮปฮนฯฮฝ
private static final double xyMaxBitsValue = Math.pow(2, Individual.defaultGeneLength/Main.bombsNum/2);
public static final double factor = Main.x/(xyMaxBitsValue-1);
static int getFitness(Individual individual) {
// ฮฮทฮผฮนฮฟฯ
ฯฮณฮฏฮฑ ฮฑฮฝฯฮนฮณฯฮฌฯฮฟฯ
ฯฮฟฯ
ฯฮฏฮฝฮฑฮบฮฑ ฮผฮต ฯฮนฯ ฯฯฮทฮบฮฟฯฯฮปฮนฮญฯ ฮณฮนฮฑ ฮผฮทฮฝ ฮฑฮปฮปฮฟฮนฯฮธฮตฮฏ ฮฟ ฮฑฯฯฮนฮบฯฯ ฯฮฏฮฝฮฑฮบฮฑฯ
Nest[] nests = Nest.cloneArray();
// ฯฮฑ ฮณฮฟฮฝฮฏฮดฮนฮฑ ฮดฮนฮทฯฮทฮผฮญฮฝฮฑ ฯฮต 6 ฮบฮฟฮผฮผฮฌฯฮนฮฑ ฯฯฮฝ 8 bit ฮบฮฑฮน ฮผฮต ฮผฮตฯฮฑฯฯฮฟฯฮฎ ฯฮต ฮดฮตฮบฮฑฮดฮนฮบฯ ฯฯฯฯฮทฮผฮฑ ฮผฮฑฯ ฮดฮฏฮฝฮฟฯ
ฮฝ ฯฮนฯ ฯฯ
ฮฝฯฮตฯฮฑฮณฮผฮญฮฝฮตฯ ฯฯฮฝ ฮฒฮฟฮผฮฒฯฮฝ
/*
ฯ.ฯ. x1 y1 x2 y2 x3 y3
00010001 00100000 01010010 00001011 11010111 00001001
*/
// ฮดฯ
ฮฟ ฯฮฏฮฝฮฑฮบฮตฯ ฮผฮต ฯฮนฯ ฯฯ
ฮฝฯฮตฯฮฑฮณฮผฮญฮฝฮตฯ ฯฯฮฝ ฮฒฮฟฮผฮฒฯฮฝ, ฯฮฑ 3 x ฮบฮฑฮน ฯฮฑ 3 y
int [][] coords = new int [Main.bombsNum][2];
// ฮผฮตฯฯฮทฯฮฎฯ, ฯฮฑฯ
ฯฮฏฮถฮตฯฮฑฮน ฮผฮต ฯฮฟฮฝ ฮฑฯฮนฮธฮผฯ ฯฯฮฝ ฮฒฮฟฮผฮฒฯฮฝ ฮผฮตฯฮฌ ฯฮฟ for loop
int z = 0;
// ฮฃฯฮฌฮตฮน ฯฮต 3 ฮฏฯฮฑ ฮบฮฟฮผฮผฮฌฯฮนฮฑ ฯฯฮฝ 16 bit, ฯฮฟฯ
ฯฮตฯฮนฮญฯฮฟฯ
ฮฝ ฯฮนฯ ฯฯ
ฮฝฯฮตฯฮฑฮณฮผฮญฮฝฮตฯ ฯฯฮฝ ฯฯฮนฯฮฝ ฮฒฮฟฮผฮฒฯฮฝ
for(final String token : Splitter.fixedLength(Individual.defaultGeneLength/Main.bombsNum).split(individual.toString())){
// ฮฃฯฮฌฮตฮน ฯฮฟ ฮบฮฟฮผฮผฮฌฯฮน ฯฯฮฝ 16 bit ฯฮต 2 ฯฯฮฝ 8 bit, ฮดฮทฮปฮฑฮดฮฎ ฯฯฮฑ x ฮบฮฑฮน y ฮบฮฑฮน ฯฮฑ ฮผฮตฯฮฑฯฯฮญฯฮตฮน ฯฮต ฮดฮตฮบฮฑฮดฮนฮบฮฟฯฯ
// ฮ ฮฟฮปฮปฮฑฯฮปฮฑฯฮนฮฑฯฮผฯฯ ฮผฮต (100/255) ฮณฮนฮฑฯฮฏ ฯฮฑ 8 bit ฮฒฮณฮฌฮถฮฟฯ
ฮฝ ฮผฮญฯฯฮน ฯฮฟฮฝ ฮฑฯฮนฮธฮผฯ 255 ฯฮต ฮดฮตฮบฮฑฮดฮนฮบฯ, ฮตฮฝฯ ฮฟฮน ฯฯ
ฮฝฯฮตฯฮฑฮณฮผฮญฮฝฮตฯ ฮผฯฮฟฯฮฟฯฮฝ ฮฝฮฑ ฮตฮฏฮฝฮฑฮน ฮฑฯฯ 0 ฮผฮญฯฯฮน 100
coords[z][0] = (int)(((double)Integer.parseInt(token.substring(0, token.length() / 2), 2)) * factor);
coords[z++][1] = (int)(((double)Integer.parseInt(token.substring(token.length() / 2), 2)) * factor);
//System.out.println(x1[z] + "\n" + y1[z]);
}
//ฮฅฯฮฟฮปฮฟฮณฮฏฮถฮตฯฮฑฮน ฮท ฮฑฯฯฯฯฮฑฯฮท ฯฯฮฝ ฮฒฮฟฮผฮฒฯฮฝ ฮฑฯฯ ฯฮนฯ ฯฯฮปฮนฮญฯ ฮบฮฑฮน ฯฮฟ ฯฮปฮฎฮธฮฟฯ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฯฮบฮฟฯฯฮฝฮฟฯ
ฮฝ
double n=nests.length; // ฮฮฎฮบฮฟฯ ฯฮฏฮฝฮฑฮบฮฑ ฯฯฮปฮนฯฮฝ
double d; // ฮฑฯฯฯฯฮฑฯฮท ฮฒฯฮผฮฒฮฑฯ ฮฑฯฯ ฯฮท ฯฯฮปฮนฮฌ
double K; // ฯฮปฮฎฮธฮฟฯ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฮต ฮผฮนฮฑ ฯฯฮปฮนฮฌ
int T = 0; // ฯฮปฮฎฮธฮฟฯ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฮต ฯฮปฮตฯ ฯฮนฯ ฯฯฮปฮนฮญฯ, ฮฑฯฯ ฯฮปฮตฯ ฯฮนฯ ฮฒฯฮผฮฒฮตฯ ฮผฮฑฮถฮฏ
// loop ฮฑฯฯ 0 ฮตฯฯ ฮณฮนฮฑ ฮฝฮฑ ฯ
ฯฮฟฮปฮฟฮณฮฏฯฮฟฯ
ฮผฮต ฮณฮนฮฑ ฯฮปฮตฯ ฯฮนฯ ฮฒฯฮผฮฒฮตฯ
for(int j=0; j < Main.bombsNum; j++) {
for (Nest nest : nests) {
// ฮฑฮฝ ฮดฮตฮฝ ฯ
ฯฮฌฯฯฮฟฯ
ฮฝ ฮฌฮปฮปฮตฯ ฯฯฮฎฮบฮตฯ ฯฯฮท ฯฯฮปฮนฮฌ, ฯฮตฯฮฝฮฌฮผฮต ฯฯฮทฮฝ ฮตฯฯฮผฮตฮฝฮท ฮณฮนฮฑฯฮฏ ฯฮต ฮฑฯ
ฯฮฎ ฮดฮตฮฝ ฮธฮฑ ฯฮบฮฟฯฯฮธฮตฮฏ ฮบฮฑฮผฮฏฮฑ
if (nest.getHosesNum() == 0)
continue;
// ฯ
ฯฮฟฮปฮฟฮณฮนฯฮผฯฯ ฮฑฯฯฯฯฮฑฯฮทฯ ฮฒฯฮผฮฒฮฑฯ j ฮฑฯฯ ฯฮท ฯฯฮปฮนฮฌ
d = Math.sqrt(Math.pow(coords[j][0] - nest.getX(), 2) + Math.pow(coords[j][1] - nest.getY(), 2));
//System.out.println("d[" + (i+1) + "]: " + d);
// ฮฅฯฮฟฮปฮฟฮณฮนฯฮผฯฯ ฯฮปฮฎฮธฮฟฯ
ฯ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฯฮท ฯฯฮปฮนฮฌ i ฮฑฯฯ ฯฮท ฮฒฯฮผฮฒฮฑ j
K = n * (dMax / (20 * d + 0.00001));
/* ฮฮฝ ฮฟ ฮฑฯฮนฮธฮผฯฯ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฯฮบฮฟฯฯฮฝฮตฮน ฮท ฮฒฯฮผฮฒฮฑ ฯฯฮท ฯฯฮปฮนฮฌ ฮตฮฏฮฝฮฑฮน ฮผฮตฮณฮฑฮปฯฯฮตฯฮฟฯ ฮฑฯฯ ฯฮฟ ฯฮปฮฎฮธฮฟฯ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฯ
ฯฮฌฯฯฮฟฯ
ฮฝ,
ฯฯฮฟฯฯฮฏฮธฮตฯฮฑฮน ฯฯฮฟ ฯฯฮฝฮฟฮปฮฟ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฮท ฮฑฯฮฝฮทฯฮนฮบฮฎ ฮดฮนฮฑฯฮฟฯฮฌ.
*/
if ((nest.getHosesNum() - (int) K) < 0)
K += nest.getHosesNum() - (int) K;
// ฮฯฮฑฮนฯฮตฮฏฯฮฑฮน ฮฑฯฯ ฯฯฮฝ ฮฑฯฮนฮธฮผฯ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮทฯ ฯฯฮปฮนฮฌฯ ฮฟ ฮฑฯฮนฮธฮผฯฯ ฮฑฯ
ฯฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ
nest.setHosesNum(nest.getHosesNum() - (int) K);
//System.out.println("Hoses num: [" + (i+1) + "]: " + nestsC[i].getHosesNum());
//System.out.println("K[" + (i + 1) + "]: " + (int)K + "\n");
// ฮ ฯฮฟฯฯฮฏฮธฮตฯฮฑฮน ฯฯฮฟ ฯฮปฮฎฮธฮฟฯ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฮต ฯฮปฮตฯ ฯฮนฯ ฯฯฮปฮนฮญฯ ฮฟ ฮฑฯฮนฮธฮผฯฯ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฯฮทฮฝ i ฯฯฮปฮนฮฌ
T += (int) K;
}
}
return T;
}
/*static int getFitness(String genes) throws CloneNotSupportedException {
Nest[] nests = Nest.cloneArray();
int [][] coords = new int [Main.bombsNum][2];
int z = 0;
for(final String token : Splitter.fixedLength(Individual.defaultGeneLength/Main.bombsNum).split(genes)){
System.out.println(token);
coords[z][0] = (int)(((double)Integer.parseInt(token.substring(0, token.length() / 2), 2)) * factor);
coords[z++][1] = (int)(((double)Integer.parseInt(token.substring(token.length() / 2), 2)) * factor);
}
double n=nests.length; // ฮฮฎฮบฮฟฯ ฯฮฏฮฝฮฑฮบฮฑ ฯฯฮปฮนฯฮฝ
double d; // ฮฑฯฯฯฯฮฑฯฮท ฮฒฯฮผฮฒฮฑฯ ฮฑฯฯ ฯฮท ฯฯฮปฮนฮฌ
double K; // ฯฮปฮฎฮธฮฟฯ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฮต ฮผฮนฮฑ ฯฯฮปฮนฮฌ
int T = 0; // ฯฮปฮฎฮธฮฟฯ ฯฯฮทฮบฯฮฝ ฯฮฟฯ
ฮธฮฑ ฯฮบฮฟฯฯฮธฮฟฯฮฝ ฯฮต ฯฮปฮตฯ ฯฮนฯ ฯฯฮปฮนฮญฯ, ฮฑฯฯ ฯฮปฮตฯ ฯฮนฯ ฮฒฯฮผฮฒฮตฯ ฮผฮฑฮถฮฏ
for(int j=0; j < Main.bombsNum; j++) {
for (Nest nest : nests) {
if (nest.getHosesNum() == 0) continue;
d = Math.sqrt(Math.pow(coords[j][0] - nest.getX(), 2) + Math.pow(coords[j][1] - nest.getY(), 2));
K = n * (dMax / (20 * d + 0.00001));
if ((nest.getHosesNum() - (int) K) < 0) K += nest.getHosesNum() - (int) K;
nest.setHosesNum(nest.getHosesNum() - (int) K);
T += (int) K;
}
}
return T;
}*/
// ฮตฯฮนฯฯฯฮญฯฮตฮน ฯฮท ฮผฮญฮณฮนฯฯฮท ฯฮฟฮนฯฯฮทฯฮฑ
private static int getMaxFitness() {
int maxFitness = 0;
// ฮฑฮธฯฮฟฮฏฮถฮตฮน ฯฮฟ ฯฯฮฝฮฟฮปฮฟ ฯฯฮฝ ฯฯฮทฮบฯฮฝ ฯฮปฯฮฝ ฯฯฮฝ ฯฯฮปฮนฯฮฝ
for (Nest nest: Main.nests) {
maxFitness+=nest.getHosesNum();
}
return maxFitness;
}
}
| [
"[email protected]"
]
| |
59fd47686f75d6e807b543f9798b179083c6692b | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/6/6_c7ecf6f4917790db7bd54bf6e1857f3b0d3a185c/HRMController/6_c7ecf6f4917790db7bd54bf6e1857f3b0d3a185c_HRMController_s.java | 74f5d7e535d4987a5b6054937c4da7e0a0102b70 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 189,879 | java | /*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package de.tuilmenau.ics.fog.routing.hierarchical;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Observer;
import de.tuilmenau.ics.fog.FoGEntity;
import de.tuilmenau.ics.fog.IEvent;
import de.tuilmenau.ics.fog.application.Application;
import de.tuilmenau.ics.fog.application.util.ServerCallback;
import de.tuilmenau.ics.fog.application.util.Service;
import de.tuilmenau.ics.fog.eclipse.GraphViewer;
import de.tuilmenau.ics.fog.facade.Binding;
import de.tuilmenau.ics.fog.facade.Connection;
import de.tuilmenau.ics.fog.facade.Description;
import de.tuilmenau.ics.fog.facade.Identity;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.Namespace;
import de.tuilmenau.ics.fog.facade.NetworkException;
import de.tuilmenau.ics.fog.facade.RequirementsException;
import de.tuilmenau.ics.fog.facade.RoutingException;
import de.tuilmenau.ics.fog.facade.Signature;
import de.tuilmenau.ics.fog.facade.events.ConnectedEvent;
import de.tuilmenau.ics.fog.facade.events.ErrorEvent;
import de.tuilmenau.ics.fog.facade.events.Event;
import de.tuilmenau.ics.fog.facade.properties.CommunicationTypeProperty;
import de.tuilmenau.ics.fog.packets.hierarchical.clustering.RequestClusterMembership;
import de.tuilmenau.ics.fog.routing.Route;
import de.tuilmenau.ics.fog.routing.RouteSegmentPath;
import de.tuilmenau.ics.fog.routing.RoutingServiceLink;
import de.tuilmenau.ics.fog.routing.hierarchical.election.ElectionPriority;
import de.tuilmenau.ics.fog.routing.hierarchical.election.Elector;
import de.tuilmenau.ics.fog.routing.hierarchical.management.*;
import de.tuilmenau.ics.fog.routing.hierarchical.properties.*;
import de.tuilmenau.ics.fog.routing.naming.HierarchicalNameMappingService;
import de.tuilmenau.ics.fog.routing.naming.NameMappingEntry;
import de.tuilmenau.ics.fog.routing.naming.NameMappingService;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMName;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address;
import de.tuilmenau.ics.fog.topology.AutonomousSystem;
import de.tuilmenau.ics.fog.topology.NetworkInterface;
import de.tuilmenau.ics.fog.topology.Node;
import de.tuilmenau.ics.fog.transfer.TransferPlaneObserver.NamingLevel;
import de.tuilmenau.ics.fog.transfer.gates.GateID;
import de.tuilmenau.ics.fog.ui.Decoration;
import de.tuilmenau.ics.fog.ui.Logging;
import de.tuilmenau.ics.fog.ui.eclipse.NodeDecorator;
import de.tuilmenau.ics.fog.util.BlockingEventHandling;
import de.tuilmenau.ics.fog.util.SimpleName;
import edu.uci.ics.jung.graph.util.Pair;
/**
* This is the main HRM controller. It provides functions that are necessary to build up the hierarchical structure - every node contains such an object
*/
public class HRMController extends Application implements ServerCallback, IEvent
{
/**
* Stores the node specific graph decorator for HRM coordinators and HRMIDs
*/
private NodeDecorator mDecoratorForCoordinatorsAndHRMIDs = null;
/**
* Stores the node specific graph decorator for HRM coordinators and clusters
*/
private NodeDecorator mDecoratorForCoordinatorsAndClusters = null;
/**
* Stores the node specific graph decorator for NMS entries
*/
private NodeDecorator mDecoratorForNMSEntries = null;
/**
* Stores the node specific graph decorator for the active HRM infrastructure
*/
private NodeDecorator mDecoratorActiveHRMInfrastructure = null;
/**
* Stores the node specific graph decorator for HRM node base priority
*/
private NodeDecorator mDecoratorForNodePriorities = null;
/**
* Stores the GUI observable, which is used to notify possible GUIs about changes within this HRMController instance.
*/
private HRMControllerObservable mGUIInformer = new HRMControllerObservable(this);
/**
* Stores the HRG-GUI observable, which is used to notify possible HRG-GUI about changes within the HRG of the HRMController instance.
*/
private HRMControllerObservable mHRGGUIInformer = new HRMControllerObservable(this);
/**
* The name under which the HRMController application is registered on the local node.
*/
private SimpleName mApplicationName = null;
/**
* Reference to physical node.
*/
private Node mNode;
/**
* Stores a reference to the local autonomous system instance.
*/
private AutonomousSystem mAS = null;
/**
* Stores the registered HRMIDs.
* This is used within the GUI and during "share phase".
*/
private LinkedList<HRMID> mRegisteredOwnHRMIDs = new LinkedList<HRMID>();
/**
* Stores a database about all registered coordinators.
* For example, this list is used for the GUI.
*/
private LinkedList<Coordinator> mLocalCoordinators = new LinkedList<Coordinator>();
/**
* Stores all former known Coordinator IDs
*/
private LinkedList<Long> mFormerLocalCoordinatorIDs = new LinkedList<Long>();
/**
* Stores a database about all registered coordinator proxies.
*/
private LinkedList<CoordinatorProxy> mLocalCoordinatorProxies = new LinkedList<CoordinatorProxy>();
/**
* Stores a database about all registered clusters.
* For example, this list is used for the GUI.
*/
private LinkedList<Cluster> mLocalClusters = new LinkedList<Cluster>();
/**
* Stores a database about all registered cluster members (including Cluster objects).
*/
private LinkedList<ClusterMember> mLocalClusterMembers = new LinkedList<ClusterMember>();
/**
* Stores a database about all registered L0 cluster members (including Cluster objects).
* This list is used for deriving connectivity data for the distribution of topology data.
*/
private LinkedList<ClusterMember> mLocalL0ClusterMembers = new LinkedList<ClusterMember>();
/**
* Stores a database about all registered CoordinatorAsClusterMemeber instances.
*/
private LinkedList<CoordinatorAsClusterMember> mLocalCoordinatorAsClusterMemebers = new LinkedList<CoordinatorAsClusterMember>();
/**
* Stores a database about all registered comm. sessions.
*/
private LinkedList<ComSession> mCommunicationSessions = new LinkedList<ComSession>();
/**
* Stores a reference to the local instance of the hierarchical routing service.
*/
private HRMRoutingService mHierarchicalRoutingService = null;
/**
* Stores if the application was already started.
*/
private boolean mApplicationStarted = false;
/**
* Stores a database including all HRMControllers of this physical simulation machine
*/
public static LinkedList<HRMController> mRegisteredHRMControllers = new LinkedList<HRMController>();
/**
* Stores the amount of registered coordinators globally
*/
public static long sRegisteredCoordinators = 0;
/**
* Stores the amount of unregistered coordinators globally
*/
public static long sUnregisteredCoordinators = 0;
/**
* Stores an abstract routing graph (ARG), which provides an abstract overview about logical links between clusters/coordinator.
*/
private AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> mAbstractRoutingGraph = new AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink>();
/**
* Stores the hierarchical routing graph (HRG), which provides a hierarchical overview about the network topology.
*/
private AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> mHierarchicalRoutingGraph = new AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink>(true);
/**
* Count the outgoing connections
*/
private int mCounterOutgoingConnections = 0;
/**
* Stores if the entire FoGSiEm simulation was already created.
* This is only used for debugging purposes. This is NOT a way for avoiding race conditions in signaling.
*/
private static boolean mFoGSiEmSimulationCreationFinished = false;
/**
* Stores the node priority per hierarchy level.
* Level 0 isn't used here. (see "mNodeConnectivityPriority")
*/
private long mNodeHierarchyPriority[] = new long[HRMConfig.Hierarchy.HEIGHT + 2];
/**
* Stores the connectivity node priority
*/
private long mNodeConnectivityPriority = HRMConfig.Election.DEFAULT_PRIORITY;
/**
* Stores the central node for the ARG
*/
private CentralNodeARG mCentralARGNode = null;
/**
* Stores a description about all connectivity priority updates
*/
private String mDesriptionConnectivityPriorityUpdates = new String();
/**
* Stores a description about all HRMID updates
*/
private String mDescriptionHRMIDUpdates = new String();
/**
* Stores a description about all HRG updates
*/
private String mDescriptionHRGUpdates = new String();
/**
* Stores a description about all hierarchy priority updates
*/
private String mDesriptionHierarchyPriorityUpdates = new String();
/**
* Stores the thread for clustering tasks and packet processing
*/
private HRMControllerProcessor mProcessorThread = null;
/**
* Stores a database about all known superior coordinators
*/
private LinkedList<ClusterName> mSuperiorCoordinators = new LinkedList<ClusterName>();
/**
* Stores a database about all known network interfaces of this node
*/
private LinkedList<NetworkInterface> mLocalNetworkInterfaces = new LinkedList<NetworkInterface>();
/**
* Stores a counter for the references per known network interface
*/
private HashMap<NetworkInterface, Integer> mLocalNetworkInterfacesRefCount = new HashMap<NetworkInterface, Integer>();
/**
* Stores the node-global election state
*/
private Object mNodeElectionState = null;
/**
* Stores the node-global election state change description
*/
private String mDescriptionNodeElectionState = new String();
/**
* Stores if the GUI user has selected to deactivate topology reports.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_REPORT_TOPOLOGY = HRMConfig.Routing.REPORT_TOPOLOGY_AUTOMATICALLY;
/**
* Stores if the GUI user has selected to deactivate address distribution.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_ADDRESS_DISTRUTION = HRMConfig.Addressing.ASSIGN_AUTOMATICALLY;
/**
* Stores if the GUI user has selected to deactivate topology reports.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_SHARE_ROUTES = HRMConfig.Routing.SHARE_ROUTES_AUTOMATICALLY;
/**
* Stores if the GUI user has selected to deactivate announcements.
* This function is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
public static boolean GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = true;
/**
* Stores the simulation time of the last AnnounceCoordinator, which had impact on the current hierarchy structure
* This value is not part of the concept. It is only used for debugging purposes and measurement speedup.
*/
private static double mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = 0;
/**
* Stores if the simulation was restarted and the global NMS should be reset
*/
private static boolean sResetNMS = false;
/**
* @param pAS the autonomous system at which this HRMController is instantiated
* @param pNode the node on which this controller was started
* @param pHRS is the hierarchical routing service that should be used
*/
public HRMController(AutonomousSystem pAS, Node pNode, HRMRoutingService pHierarchicalRoutingService)
{
// initialize the application context
super(pNode, null, pNode.getIdentity());
/**
* Reset FoGSiEm configuration
*/
GUI_USER_CTRL_REPORT_TOPOLOGY = HRMConfig.Routing.REPORT_TOPOLOGY_AUTOMATICALLY;
GUI_USER_CTRL_SHARE_ROUTES = HRMConfig.Routing.SHARE_ROUTES_AUTOMATICALLY;
GUI_USER_CTRL_ADDRESS_DISTRUTION = HRMConfig.Addressing.ASSIGN_AUTOMATICALLY;
resetAnnounceCoordinatorGUI();
// define the local name "routing://"
mApplicationName = new SimpleName(ROUTING_NAMESPACE, null);
// reference to the physical node
mNode = pNode;
// reference to the AutonomousSystem object
mAS = pAS;
// set the node-global election state
mNodeElectionState = Elector.createNodeElectionState();
/**
* Create the node specific decorator for HRM coordinators and HRMIDs
*/
mDecoratorForCoordinatorsAndHRMIDs = new NodeDecorator();
/**
* Create the node specific decorator for HRM coordinators and clusters
*/
mDecoratorForCoordinatorsAndClusters = new NodeDecorator();
/**
* Create the node specific decorator for NMS entries
*/
mDecoratorForNMSEntries = new NodeDecorator();
/**
* Create the node specific decorator for HRM node priorities
*/
mDecoratorForNodePriorities = new NodeDecorator();
/**
* Create the node specific decorator for the active HRM infrastructure
*/
mDecoratorActiveHRMInfrastructure = new NodeDecorator();
/**
* Initialize the node hierarchy priority
*/
for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){
mNodeHierarchyPriority[i] = i;//HRMConfig.Election.DEFAULT_BULLY_PRIORITY;
}
/**
* Set the node decorations
*/
Decoration tDecoration = null;
// create own decoration for HRM coordinators & HRMIDs
tDecoration = Decoration.getInstance(DECORATION_NAME_COORDINATORS_AND_HRMIDS);
tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndHRMIDs);
// create own decoration for HRM coordinators and clusters
tDecoration = Decoration.getInstance(DECORATION_NAME_COORDINATORS_AND_CLUSTERS);
tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndClusters);
// create own decoration for NMS entries
tDecoration = Decoration.getInstance(DECORATION_NAME_NMS_ENTRIES);
tDecoration.setDecorator(mNode, mDecoratorForNMSEntries);
// create own decoration for HRM node priorities
tDecoration = Decoration.getInstance(DECORATION_NAME_NODE_PRIORITIES);
tDecoration.setDecorator(mNode, mDecoratorForNodePriorities);
// create own decoration for HRM node priorities
tDecoration = Decoration.getInstance(DECORATION_NAME_ACTIVE_HRM_INFRASTRUCTURE);
tDecoration.setDecorator(mNode, mDecoratorActiveHRMInfrastructure);
// overwrite default decoration
tDecoration = Decoration.getInstance(GraphViewer.DEFAULT_DECORATION);
tDecoration.setDecorator(mNode, mDecoratorForNMSEntries);
/**
* Create clusterer thread
*/
mProcessorThread = new HRMControllerProcessor(this);
/**
* Start the clusterer thread
*/
mProcessorThread.start();
/**
* Create communication service
*/
// bind the HRMController application to a local socket
Binding tServerSocket=null;
// enable simple datagram based communication
Description tServiceReq = getDescription();
tServiceReq.set(CommunicationTypeProperty.DATAGRAM);
tServerSocket = getLayer().bind(null, mApplicationName, tServiceReq, getIdentity());
if (tServerSocket != null){
// create and start the socket service
Service tService = new Service(false, this);
tService.start(tServerSocket);
}else{
Logging.err(this, "Unable to start the HRMController service");
}
// store the reference to the local instance of hierarchical routing service
mHierarchicalRoutingService = pHierarchicalRoutingService;
// create central node in the local ARG
mCentralARGNode = new CentralNodeARG(this);
// create local loopback session
ComSession.createLoopback(this);
// fire the first "report/share phase" trigger
reportAndShare();
Logging.log(this, "CREATED");
// start the application
start();
}
/**
* Reset the AnnounceCoordinator handling.
* This function is not part of the concept. It is only useful for debugging purposes and user control.
*/
public void resetAnnounceCoordinatorGUI()
{
Logging.log(this, "##### Reseting AnnounceCoordinator mechanism");
GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = true;
mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = 0;
}
/**
* Returns the local instance of the hierarchical routing service
*
* @return hierarchical routing service of this entity
*/
public HRMRoutingService getHRS()
{
return mHierarchicalRoutingService;
}
/**
* Returns the local physical node object.
*
* @return the physical node running this coordinator
*/
public Node getNode()
{
return mNode;
}
/**
* Return the actual GUI name description of the physical node;
* However, this function should only be used for debug outputs, e.g., GUI outputs.
*
* @return the GUI name
*/
@SuppressWarnings("deprecation")
public String getNodeGUIName()
{
return mNode.getName();
}
/**
* Notifies the GUI about essential updates within the HRM system
*/
private void notifyGUI(Object pArgument)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Got notification with argument " + pArgument);
}
mGUIInformer.notifyObservers(pArgument);
}
/**
* Notifies the HRGViewer about essential updates within the HRG graph
*/
private void notifyHRGGUI(Object pArgument)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Got HRG notification with argument " + pArgument);
}
mHRGGUIInformer.notifyObservers(pArgument);
}
/**
* Registers a GUI for being notified about HRMController internal changes.
*/
public void registerGUI(Observer pGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Registering GUI " + pGUI);
}
mGUIInformer.addObserver(pGUI);
}
/**
* Registers a HRG-GUI for being notified about HRG internal changes.
*/
public void registerHRGGUI(Observer pHRGGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Registering HRG-GUI " + pHRGGUI);
}
mHRGGUIInformer.addObserver(pHRGGUI);
}
/**
* Unregisters a GUI for being notified about HRMController internal changes.
*/
public void unregisterGUI(Observer pGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Unregistering GUI " + pGUI);
}
mGUIInformer.deleteObserver(pGUI);
}
/**
* Unregisters a HRG-GUI for being notified about HRG internal changes.
*/
public void unregisterHRGGUI(Observer pHRGGUI)
{
if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){
Logging.log(this, "Unregistering HRG-GUI " + pHRGGUI);
}
mHRGGUIInformer.deleteObserver(pHRGGUI);
}
/**
* Registers a coordinator proxy at the local database.
*
* @param pCoordinatorProxy the coordinator proxy for a defined coordinator
*/
public synchronized void registerCoordinatorProxy(CoordinatorProxy pCoordinatorProxy)
{
Logging.log(this, "Registering coordinator proxy " + pCoordinatorProxy + " at level " + pCoordinatorProxy.getHierarchyLevel().getValue());
synchronized (mLocalCoordinatorProxies) {
// register as known coordinator proxy
mLocalCoordinatorProxies.add(pCoordinatorProxy);
}
// increase hierarchy node priority
increaseHierarchyNodePriority_KnownCoordinator(pCoordinatorProxy);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the coordinator prxy in the local ARG
registerNodeARG(pCoordinatorProxy);
// it's time to update the GUI
notifyGUI(pCoordinatorProxy);
}
/**
* Unregisters a coordinator proxy from the local database.
*
* @param pCoordinatorProxy the coordinator proxy for a defined coordinator
*/
public synchronized void unregisterCoordinatorProxy(CoordinatorProxy pCoordinatorProxy)
{
Logging.log(this, "Unregistering coordinator proxy " + pCoordinatorProxy + " at level " + pCoordinatorProxy.getHierarchyLevel().getValue());
synchronized (mLocalCoordinatorProxies) {
// unregister as known coordinator proxy
mLocalCoordinatorProxies.remove(pCoordinatorProxy);
}
// increase hierarchy node priority
decreaseHierarchyNodePriority_KnownCoordinator(pCoordinatorProxy);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the coordinator prxy in the local ARG
unregisterNodeARG(pCoordinatorProxy);
// it's time to update the GUI
notifyGUI(pCoordinatorProxy);
}
/**
* Registers a coordinator at the local database.
*
* @param pCoordinator the coordinator for a defined cluster
*/
public synchronized void registerCoordinator(Coordinator pCoordinator)
{
Logging.log(this, "Registering coordinator " + pCoordinator + " at level " + pCoordinator.getHierarchyLevel().getValue());
Coordinator tFoundAnInferiorCoordinator = getCoordinator(pCoordinator.getHierarchyLevel().getValue() - 1);
/**
* Check if the hierarchy is continuous
*/
if((!pCoordinator.getHierarchyLevel().isBaseLevel()) && (tFoundAnInferiorCoordinator == null)){
Logging.err(this, "Hierarchy is temporary non continuous, detected an error in the Matrix!?");
Logging.err(this, " ..registered a coordinator at hierarchy level: " + pCoordinator.getHierarchyLevel().getValue() + " and haven't found a coordinator at level: " + (pCoordinator.getHierarchyLevel().getValue() - 1));
}
synchronized (mLocalCoordinators) {
// register as known coordinator
mLocalCoordinators.add(pCoordinator);
}
sRegisteredCoordinators++;
// increase hierarchy node priority
increaseHierarchyNodePriority_KnownCoordinator(pCoordinator);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the coordinator in the local ARG
registerNodeARG(pCoordinator);
registerLinkARG(pCoordinator, pCoordinator.getCluster(), new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
// it's time to update the GUI
notifyGUI(pCoordinator);
}
/**
* Unregisters a coordinator from the internal database.
*
* @param pCoordinator the coordinator which should be unregistered
*/
public synchronized void unregisterCoordinator(Coordinator pCoordinator)
{
Logging.log(this, "Unregistering coordinator " + pCoordinator + " at level " + pCoordinator.getHierarchyLevel().getValue());
synchronized (mLocalCoordinators) {
// unregister from list of known coordinators
mLocalCoordinators.remove(pCoordinator);
synchronized (mFormerLocalCoordinatorIDs) {
mFormerLocalCoordinatorIDs.add(pCoordinator.getGUICoordinatorID());
}
}
sUnregisteredCoordinators++;
// increase hierarchy node priority
decreaseHierarchyNodePriority_KnownCoordinator(pCoordinator);
// updates the GUI decoration for this node
updateGUINodeDecoration();
// unregister from the ARG
unregisterNodeARG(pCoordinator);
// it's time to update the GUI
notifyGUI(pCoordinator);
}
/**
* Registers an HRMID at local database
*
* @param pEntity the entity for which the HRMID should be registered
* @param pCause the cause for the registration
*/
private void registerHRMID(ControlEntity pEntity, String pCause)
{
/**
* Get the new HRMID
*/
HRMID tHRMID = pEntity.getHRMID();
if((tHRMID != null) && (!tHRMID.isZero())){
registerHRMID(pEntity, tHRMID, pCause);
}
}
/**
* Registers an HRMID at local database
*
* @param pEntity the entity for which the HRMID should be registered
* @param pHRMID the new HRMID
* @param pCause the cause for the registration
*/
@SuppressWarnings("unchecked")
public void registerHRMID(ControlEntity pEntity, HRMID pHRMID, String pCause)
{
/**
* Some validations
*/
if(pHRMID != null){
// ignore "0.0.0"
if(!pHRMID.isZero()){
/**
* Register the HRMID
*/
synchronized(mRegisteredOwnHRMIDs){
if (!mRegisteredOwnHRMIDs.contains(pHRMID)){
/**
* Update the local address DB with the given HRMID
*/
if(!pHRMID.isClusterAddress()){
/**
* Register a local loopback route for the new address
*/
// register a route to the cluster member as addressable target
addHRMRoute(RoutingEntry.createLocalhostEntry(pHRMID, pCause + ", " + this + "::registerHRMID()"));
/**
* Update the DNS
*/
// register the HRMID in the hierarchical DNS for the local router
HierarchicalNameMappingService<HRMID> tNMS = null;
try {
tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation());
} catch (RuntimeException tExc) {
HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation());
}
// get the local router's human readable name (= DNS name)
Name tLocalRouterName = getNodeName();
// register HRMID for the given DNS name
Logging.log(this, "Registering NMS entry: " + tLocalRouterName + " => " + pHRMID);
tNMS.registerName(tLocalRouterName, pHRMID, NamingLevel.NAMES);
// give some debug output about the current DNS state
String tString = new String();
for(NameMappingEntry<HRMID> tEntry : tNMS.getAddresses(tLocalRouterName)) {
if (!tString.isEmpty()){
tString += ", ";
}
tString += tEntry;
}
Logging.log(this, "HRM router " + tLocalRouterName + " is now known under: " + tString);
}
}else{
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Found a HRMID duplicate for " + pHRMID.toString() + ", additional registration is triggered by " + pEntity);
}
}
/**
* Add the HRMID
*/
if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){
Logging.log(this, "Adding the HRMID to: " + pHRMID.toString() + " for: " + pEntity);
}
// register the new HRMID as local one -> allow duplicates here because two local entities might register the same HRMID and afterwards one of them unregisters its HRMID -> in case one HRMID registration remains!
mRegisteredOwnHRMIDs.add(pHRMID);
mDescriptionHRMIDUpdates += "\n + " + pHRMID.toString() + " <== " + pEntity + ", cause=" + pCause;
/**
* Update the GUI
*/
// updates the GUI decoration for this node
updateGUINodeDecoration();
// it's time to update the GUI
notifyGUI(pEntity);
}
}else{
throw new RuntimeException(this + "registerHRMID() got a zero HRMID " + pHRMID.toString() + " for: " + pEntity);
}
}else{
Logging.err(this, "registerHRMID() got an invalid HRMID for: " + pEntity);
}
}
/**
* Unregisters an HRMID at local database
*
* @param pEntity the entity for which the HRMID should be registered
* @param pOldHRMID the old HRMID which should be unregistered
* @param pCause the cause for this call
*/
public void unregisterHRMID(ControlEntity pEntity, HRMID pOldHRMID, String pCause)
{
/**
* Some validations
*/
if(pOldHRMID != null){
// ignore "0.0.0"
if(!pOldHRMID.isZero()){
/**
* Unregister the HRMID
*/
synchronized(mRegisteredOwnHRMIDs){
/**
* Remove the HRMID
*/
if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){
Logging.log(this, "Revoking the HRMID: " + pOldHRMID.toString() + " of: " + pEntity);
}
// unregister the HRMID as local one
mRegisteredOwnHRMIDs.remove(pOldHRMID);
mDescriptionHRMIDUpdates += "\n - " + pOldHRMID.toString() + " <== " + pEntity + ", cause=" + pCause;
if (!mRegisteredOwnHRMIDs.contains(pOldHRMID)){
/**
* Update the local address DB with the given HRMID
*/
if(!pOldHRMID.isClusterAddress()){
/**
* Unregister the local loopback route for the address
*/
// unregister a route to the cluster member as addressable target
delHRMRoute(RoutingEntry.createLocalhostEntry(pOldHRMID, pCause + ", " + this + "::unregisterHRMID()"));
/**
* Update the DNS
*/
// register the HRMID in the hierarchical DNS for the local router
HierarchicalNameMappingService<HRMID> tNMS = null;
try {
tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation());
} catch (RuntimeException tExc) {
HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation());
}
// get the local router's human readable name (= DNS name)
Name tLocalRouterName = getNodeName();
// register HRMID for the given DNS name
Logging.log(this, "Unregistering NMS entry: " + tLocalRouterName + " => " + pOldHRMID);
tNMS.unregisterName(tLocalRouterName, pOldHRMID);
// give some debug output about the current DNS state
String tString = new String();
for(NameMappingEntry<HRMID> tEntry : tNMS.getAddresses(tLocalRouterName)) {
if (!tString.isEmpty()){
tString += ", ";
}
tString += tEntry;
}
Logging.log(this, "HRM router " + tLocalRouterName + " is now known under: " + tString);
}
}else{
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Found duplicated HRMID " + pOldHRMID.toString() + ", an unregistration is triggered by " + pEntity);
}
}
/**
* Update the GUI
*/
// updates the GUI decoration for this node
updateGUINodeDecoration();
// it's time to update the GUI
notifyGUI(pEntity);
}
}else{
throw new RuntimeException(this + "unregisterHRMID() got a zero HRMID " + pOldHRMID.toString() + " for: " + pEntity);
}
}else{
Logging.err(this, "unregisterHRMID() got an invalid HRMID for: " + pEntity);
}
}
/**
* Updates the registered HRMID for a defined coordinator.
*
* @param pCluster the cluster whose HRMID is updated
* @param pOldHRMID the old HRMID which should be unregistered
*/
private int mCallsUpdateCoordinatorAddress = 0;
public void updateCoordinatorAddress(Coordinator pCoordinator, HRMID pOldHRMID)
{
mCallsUpdateCoordinatorAddress++;
HRMID tHRMID = pCoordinator.getHRMID();
if((pOldHRMID == null) || (!pOldHRMID.equals(tHRMID))){
/**
* Unregister old
*/
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
unregisterHRMID(pCoordinator, pOldHRMID, "updateCoordinatorAddress()(" + mCallsUpdateCoordinatorAddress + ") for " + pCoordinator + ", old HRMID=" + pOldHRMID);
}
/**
* Register new
*/
Logging.log(this, "Updating address from " + pOldHRMID + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for Coordinator " + pCoordinator + ", old HRMID=" + pOldHRMID);
registerHRMID(pCoordinator, "updateCoordinatorAddress()(" + mCallsUpdateCoordinatorAddress + ") for " + pCoordinator);
}
}
/**
* Returns if a coordinator ID is a formerly known one
*
* @param pCoordinatorID the coordinator ID
*
* @return true or false
*/
public boolean isGUIFormerCoordiantorID(long pCoordinatorID)
{
boolean tResult = false;
synchronized (mFormerLocalCoordinatorIDs) {
tResult = mFormerLocalCoordinatorIDs.contains(pCoordinatorID);
}
return tResult;
}
/**
* Revokes a coordinator address
*
* @param pCoordinator the coordinator for which the address is revoked
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void revokeCoordinatorAddress(Coordinator pCoordinator, HRMID pOldHRMID)
{
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for coordinator " + pCoordinator);
unregisterHRMID(pCoordinator, pOldHRMID, "revokeCoordinatorAddress()");
}
}
/**
* Updates the decoration of the node (image and label text)
*/
private void updateGUINodeDecoration()
{
/**
* Set the decoration texts
*/
String tActiveHRMInfrastructureText = "";
for (int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){
LinkedList<Cluster> tClusters = getAllClusters(i);
for(Cluster tCluster : tClusters){
if(tCluster.hasLocalCoordinator()){
if (tActiveHRMInfrastructureText != ""){
tActiveHRMInfrastructureText += ", ";
}
tActiveHRMInfrastructureText += "<" + Long.toString(tCluster.getGUIClusterID()) + ">";
for(int j = 0; j < tCluster.getHierarchyLevel().getValue(); j++){
tActiveHRMInfrastructureText += "^";
}
}
}
}
LinkedList<ClusterName> tSuperiorCoordiantors = getAllSuperiorCoordinators();
for(ClusterName tSuperiorCoordinator : tSuperiorCoordiantors){
if (tActiveHRMInfrastructureText != ""){
tActiveHRMInfrastructureText += ", ";
}
tActiveHRMInfrastructureText += Long.toString(tSuperiorCoordinator.getGUIClusterID());
for(int i = 0; i < tSuperiorCoordinator.getHierarchyLevel().getValue(); i++){
tActiveHRMInfrastructureText += "^";
}
}
mDecoratorActiveHRMInfrastructure.setText("- [Active clusters: " + tActiveHRMInfrastructureText + "]");
String tHierPrio = "";
for(int i = 1; i < HRMConfig.Hierarchy.HEIGHT; i++){
if (tHierPrio != ""){
tHierPrio += ", ";
}
tHierPrio += Long.toString(mNodeHierarchyPriority[i]) +"@" + i;
}
mDecoratorForNodePriorities.setText(" [Hier.: " + tHierPrio + "/ Conn.: " + Long.toString(getConnectivityNodePriority()) + "]");
String tNodeText = "";
synchronized (mRegisteredOwnHRMIDs) {
for (HRMID tHRMID: mRegisteredOwnHRMIDs){
if (((!tHRMID.isRelativeAddress()) || (HRMConfig.DebugOutput.GUI_SHOW_RELATIVE_ADDRESSES)) && ((!tHRMID.isClusterAddress()) || (HRMConfig.DebugOutput.GUI_SHOW_CLUSTER_ADDRESSES))){
if (tNodeText != ""){
tNodeText += ", ";
}
tNodeText += tHRMID.toString();
}
}
}
mDecoratorForCoordinatorsAndHRMIDs.setText("- " + tNodeText);
String tClustersText = "";
tClustersText = "";
LinkedList<ClusterMember> tAllClusterMembers = getAllClusterMembers();
for (ClusterMember tClusterMember : tAllClusterMembers){
if (tClustersText != ""){
tClustersText += ", ";
}
// is this node the cluster head?
if (tClusterMember instanceof Cluster){
Cluster tCluster = (Cluster)tClusterMember;
if(tCluster.hasLocalCoordinator()){
tClustersText += "<" + Long.toString(tClusterMember.getGUIClusterID()) + ">";
}else{
tClustersText += "(" + Long.toString(tClusterMember.getGUIClusterID()) + ")";
}
}else{
tClustersText += Long.toString(tClusterMember.getGUIClusterID());
}
for(int i = 0; i < tClusterMember.getHierarchyLevel().getValue(); i++){
tClustersText += "^";
}
}
mDecoratorForCoordinatorsAndClusters.setText("- clusters: " + tClustersText);
NameMappingService tNMS = null;
try {
tNMS = HierarchicalNameMappingService.getGlobalNameMappingService(mNode.getAS().getSimulation());
} catch (RuntimeException tExc) {
tNMS = HierarchicalNameMappingService.createGlobalNameMappingService(mNode.getAS().getSimulation());
}
String tRegisterNMSEntriesText = "";
try {
for(NameMappingEntry<?> tNMSEntry : tNMS.getAddresses(getNodeName())) {
if(tNMSEntry.getAddress() instanceof HRMID) {
// get the HRMID of the target node
HRMID tNodeHRMID = (HRMID)tNMSEntry.getAddress();
if(tRegisterNMSEntriesText != "")
tRegisterNMSEntriesText += ", ";
tRegisterNMSEntriesText += tNodeHRMID.toString();
}
}
} catch (RemoteException e) {
}
mDecoratorForNMSEntries.setText("- " + tRegisterNMSEntriesText);
/**
* Set the decoration images
*/
LinkedList<Coordinator> tAllCoordinators = getAllCoordinators();
int tHighestCoordinatorLevel = -1;
for (Coordinator tCoordinator : tAllCoordinators){
int tCoordLevel = tCoordinator.getHierarchyLevel().getValue();
if (tCoordLevel > tHighestCoordinatorLevel){
tHighestCoordinatorLevel = tCoordLevel;
}
}
mDecoratorForNodePriorities.setImage(tHighestCoordinatorLevel);
mDecoratorForCoordinatorsAndHRMIDs.setImage(tHighestCoordinatorLevel);
mDecoratorForCoordinatorsAndClusters.setImage(tHighestCoordinatorLevel);
mDecoratorActiveHRMInfrastructure.setImage(tHighestCoordinatorLevel);
mDecoratorForNMSEntries.setImage(tHighestCoordinatorLevel);
}
/**
* Returns a list of all known network interfaces
*
* @return the list of known network interfaces
*/
@SuppressWarnings("unchecked")
public LinkedList<NetworkInterface> getAllNetworkInterfaces()
{
LinkedList<NetworkInterface> tResult = null;
synchronized (mLocalNetworkInterfaces) {
tResult = (LinkedList<NetworkInterface>) mLocalNetworkInterfaces.clone();
}
return tResult;
}
/**
* Returns a list of all known local coordinators.
*
* @return the list of known local coordinators
*/
@SuppressWarnings("unchecked")
public LinkedList<Coordinator> getAllCoordinators()
{
LinkedList<Coordinator> tResult;
synchronized (mLocalCoordinators) {
tResult = (LinkedList<Coordinator>) mLocalCoordinators.clone();
}
return tResult;
}
/**
* Returns all known coordinators for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level for which all coordinators have to be determined
*
* @return the list of coordinators on the defined hierarchy level
*/
public LinkedList<Coordinator> getAllCoordinators(int pHierarchyLevel)
{
LinkedList<Coordinator> tResult = new LinkedList<Coordinator>();
// get a list of all known coordinators
LinkedList<Coordinator> tAllCoordinators = getAllCoordinators();
// iterate over all known coordinators
for (Coordinator tCoordinator : tAllCoordinators){
// have we found a matching coordinator?
if (tCoordinator.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tCoordinator);
}
}
return tResult;
}
/**
* Returns a list of all known local coordinator proxies.
*
* @return the list of known local coordinator proxies
*/
@SuppressWarnings("unchecked")
public LinkedList<CoordinatorProxy> getAllCoordinatorProxies()
{
LinkedList<CoordinatorProxy> tResult;
synchronized (mLocalCoordinatorProxies) {
tResult = (LinkedList<CoordinatorProxy>) mLocalCoordinatorProxies.clone();
}
return tResult;
}
/**
* Returns all known coordinator proxies for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level for which all coordinator proxies have to be determined
*
* @return the list of coordinator proies at the defined hierarchy level
*/
public LinkedList<CoordinatorProxy> getAllCoordinatorProxies(int pHierarchyLevel)
{
//Logging.log(this, "Searching for coordinator proxies at hierarchy level: " + pHierarchyLevel);
LinkedList<CoordinatorProxy> tResult = new LinkedList<CoordinatorProxy>();
// get a list of all known coordinator proxies
LinkedList<CoordinatorProxy> tAllCoordinatorProxies = getAllCoordinatorProxies();
// iterate over all known coordinator proxies
for (CoordinatorProxy tCoordinatorProxy : tAllCoordinatorProxies){
// have we found a matching coordinator proxy?
if (tCoordinatorProxy.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator proxy to the result
tResult.add(tCoordinatorProxy);
}
}
//Logging.log(this, " ..found: " + tResult);
return tResult;
}
/**
* Registers a coordinator-as-cluster-member at the local database.
*
* @param pCoordinatorAsClusterMember the coordinator-as-cluster-member which should be registered
*/
public synchronized void registerCoordinatorAsClusterMember(CoordinatorAsClusterMember pCoordinatorAsClusterMember)
{
int tLevel = pCoordinatorAsClusterMember.getHierarchyLevel().getValue();
Logging.log(this, "Registering coordinator-as-cluster-member " + pCoordinatorAsClusterMember + " at level " + tLevel);
boolean tNewEntry = false;
synchronized (mLocalCoordinatorAsClusterMemebers) {
// make sure the Election priority is the right one, avoid race conditions here
pCoordinatorAsClusterMember.setPriority(ElectionPriority.create(this, getHierarchyNodePriority(pCoordinatorAsClusterMember.getHierarchyLevel())));
if(!mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){
// register as known coordinator-as-cluster-member
mLocalCoordinatorAsClusterMemebers.add(pCoordinatorAsClusterMember);
tNewEntry = true;
}else{
Logging.err(this, "CoordinatorAsClusterMember already known: " + pCoordinatorAsClusterMember);
}
}
if(tNewEntry){
if(HRMConfig.DebugOutput.GUI_SHOW_COORDINATOR_CLUSTER_MEMBERS_IN_ARG){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the node in the local ARG
registerNodeARG(pCoordinatorAsClusterMember);
// register the link in the local ARG
registerLinkARG(pCoordinatorAsClusterMember, pCoordinatorAsClusterMember.getCoordinator(), new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
// register link to central node in the ARG
if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){
registerLinkARG(mCentralARGNode, pCoordinatorAsClusterMember, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
}
// it's time to update the GUI
notifyGUI(pCoordinatorAsClusterMember);
}
}
}
/**
* Unregister a coordinator-as-cluster-member from the local database
*
* @param pCoordinatorAsClusterMember the coordinator-as-cluster-member which should be unregistered
*/
public synchronized void unregisterCoordinatorAsClusterMember(CoordinatorAsClusterMember pCoordinatorAsClusterMember)
{
Logging.log(this, "Unregistering coordinator-as-cluster-member " + pCoordinatorAsClusterMember);
boolean tFoundEntry = false;
synchronized (mLocalCoordinatorAsClusterMemebers) {
if(mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){
// unregister the old HRMID
revokeClusterMemberAddress(pCoordinatorAsClusterMember, pCoordinatorAsClusterMember.getHRMID());
// unregister from list of known cluster members
mLocalCoordinatorAsClusterMemebers.remove(pCoordinatorAsClusterMember);
Logging.log(this, " ..unregistered: " + pCoordinatorAsClusterMember);
}else{
Logging.log(this, " ..not found: " + pCoordinatorAsClusterMember);
}
}
if(tFoundEntry){
if(HRMConfig.DebugOutput.GUI_SHOW_COORDINATOR_CLUSTER_MEMBERS_IN_ARG){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register at the ARG
unregisterNodeARG(pCoordinatorAsClusterMember);
// it's time to update the GUI
notifyGUI(pCoordinatorAsClusterMember);
}
}
}
/**
* Registers a cluster member at the local database.
*
* @param pClusterMember the cluster member which should be registered
*/
public synchronized void registerClusterMember(ClusterMember pClusterMember)
{
int tLevel = pClusterMember.getHierarchyLevel().getValue();
Logging.log(this, "Registering cluster member " + pClusterMember + " at level " + tLevel);
boolean tNewEntry = false;
synchronized (mLocalClusterMembers) {
// make sure the Election priority is the right one, avoid race conditions here
pClusterMember.setPriority(ElectionPriority.create(this, getConnectivityNodePriority()));
if(!mLocalClusterMembers.contains(pClusterMember)){
// register as known cluster member
mLocalClusterMembers.add(pClusterMember);
tNewEntry = true;
}
}
/**
* Register as L0 ClusterMember
*/
if(pClusterMember.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(!mLocalL0ClusterMembers.contains(pClusterMember)){
// register as known cluster member
mLocalL0ClusterMembers.add(pClusterMember);
}
}
}
if(tNewEntry){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the cluster in the local ARG
registerNodeARG(pClusterMember);
// register link to central node in the ARG
if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){
registerLinkARG(mCentralARGNode, pClusterMember, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
}
// it's time to update the GUI
notifyGUI(pClusterMember);
}
}
/**
* Unregister a cluster member from the local database
*
* @param pClusterMember the cluster member which should be unregistered
*/
public synchronized void unregisterClusterMember(ClusterMember pClusterMember)
{
Logging.log(this, "Unregistering cluster member " + pClusterMember);
boolean tFoundEntry = false;
synchronized (mLocalClusterMembers) {
if(mLocalClusterMembers.contains(pClusterMember)){
// unregister the old HRMID
revokeClusterMemberAddress(pClusterMember, pClusterMember.getHRMID());
// unregister from list of known cluster members
mLocalClusterMembers.remove(pClusterMember);
tFoundEntry = true;
}
}
/**
* Unregister as L0 ClusterMember
*/
if(pClusterMember.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(mLocalL0ClusterMembers.contains(pClusterMember)){
// register as known cluster member
mLocalL0ClusterMembers.remove(pClusterMember);
}
}
}
if(tFoundEntry){
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register at the ARG
unregisterNodeARG(pClusterMember);
// it's time to update the GUI
notifyGUI(pClusterMember);
}
}
/**
* Registers a cluster at the local database.
*
* @param pCluster the cluster which should be registered
*/
public synchronized void registerCluster(Cluster pCluster)
{
int tLevel = pCluster.getHierarchyLevel().getValue();
Logging.log(this, "Registering cluster " + pCluster + " at level " + tLevel);
synchronized (mLocalClusters) {
// register as known cluster
mLocalClusters.add(pCluster);
}
synchronized (mLocalClusterMembers) {
// register as known cluster member
mLocalClusterMembers.add(pCluster);
}
/**
* Register as L0 ClusterMember
*/
if(pCluster.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(!mLocalL0ClusterMembers.contains(pCluster)){
// register as known cluster member
mLocalL0ClusterMembers.add(pCluster);
}
}
}
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register the cluster in the local ARG
registerNodeARG(pCluster);
// register link to central node in the ARG
if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){
registerLinkARG(mCentralARGNode, pCluster, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF));
}
// it's time to update the GUI
notifyGUI(pCluster);
}
/**
* Unregisters a cluster from the local database.
*
* @param pCluster the cluster which should be unregistered.
*/
public synchronized void unregisterCluster(Cluster pCluster)
{
Logging.log(this, "Unregistering cluster " + pCluster);
synchronized (mLocalClusters) {
// unregister the old HRMID
revokeClusterAddress(pCluster, pCluster.getHRMID());
// unregister from list of known clusters
mLocalClusters.remove(pCluster);
}
synchronized (mLocalClusterMembers) {
// unregister from list of known cluster members
mLocalClusterMembers.remove(pCluster);
}
/**
* Unregister as L0 ClusterMember
*/
if(pCluster.getHierarchyLevel().isBaseLevel()){
synchronized (mLocalL0ClusterMembers) {
if(mLocalL0ClusterMembers.contains(pCluster)){
// register as known cluster member
mLocalL0ClusterMembers.remove(pCluster);
}
}
}
// updates the GUI decoration for this node
updateGUINodeDecoration();
// register at the ARG
unregisterNodeARG(pCluster);
// it's time to update the GUI
notifyGUI(pCluster);
}
/**
* Updates the registered HRMID for a defined Cluster.
*
* @param pCluster the Cluster whose HRMID is updated
* @param pOldHRMID the old HRMID
*/
public void updateClusterAddress(Cluster pCluster, HRMID pOldHRMID)
{
HRMID tHRMID = pCluster.getHRMID();
if((pOldHRMID == null) || (!pOldHRMID.equals(tHRMID))){
/**
* Unregister old
*/
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
unregisterHRMID(pCluster, pOldHRMID, "updateClusterAddress() for " + pCluster);
}
/**
* Register new
*/
Logging.log(this, "Updating address from " + pOldHRMID + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for Cluster " + pCluster);
registerHRMID(pCluster, "updateClusterAddress() for " + pCluster);
}
}
/**
* Updates the registered HRMID for a defined ClusterMember.
*
* @param pClusterMember the ClusterMember whose HRMID is updated
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void updateClusterMemberAddress(ClusterMember pClusterMember, HRMID pOldHRMID)
{
HRMID tHRMID = pClusterMember.getHRMID();
if((pOldHRMID == null) || (!pOldHRMID.equals(tHRMID))){
/**
* Unregister old
*/
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
unregisterHRMID(pClusterMember, pOldHRMID, "updateClusterMemberAddress() for " + pClusterMember + ", old HRMID=" + pOldHRMID);
}
/**
* Register new
*/
Logging.log(this, "Updating address from " + (pOldHRMID != null ? pOldHRMID.toString() : "null") + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for ClusterMember " + pClusterMember + ", old HRMID=" + pOldHRMID);
// process this only if we are at base hierarchy level, otherwise we will receive the same update from
// the corresponding coordinator instance
if (pClusterMember.getHierarchyLevel().isBaseLevel()){
registerHRMID(pClusterMember, "updateClusterMemberAddress() for " + pClusterMember + ", old HRMID=" + pOldHRMID);
}else{
// we are at a higher hierarchy level and don't need the HRMID update because we got the same from the corresponding coordinator instance
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Skipping HRMID registration " + (tHRMID != null ? tHRMID.toString() : "null") + " for " + pClusterMember + ", old HRMID=" + pOldHRMID);
}
}
}
}
/**
* Revokes a cluster address
*
* @param pClusterMember the ClusterMember for which the address is revoked
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void revokeClusterMemberAddress(ClusterMember pClusterMember, HRMID pOldHRMID)
{
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for ClusterMember " + pClusterMember);
if (pClusterMember.getHierarchyLevel().isBaseLevel()){
unregisterHRMID(pClusterMember, pOldHRMID, "revokeClusterMemberAddress()");
}else{
// we are at a higher hierarchy level and don't need the HRMID revocation
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Skipping HRMID revocation of " + pOldHRMID.toString() + " for " + pClusterMember);
}
}
}
}
/**
* Revokes a cluster address
*
* @param pCluster the Cluster for which the address is revoked
* @param pOldHRMID the old HRMID which should be unregistered
*/
public void revokeClusterAddress(Cluster pCluster, HRMID pOldHRMID)
{
if((pOldHRMID != null) && (!pOldHRMID.isZero())){
Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for Cluster " + pCluster);
if (pCluster.getHierarchyLevel().isBaseLevel()){
unregisterHRMID(pCluster, pOldHRMID, "revokeClusterAddress()");
}else{
// we are at a higher hierarchy level and don't need the HRMID revocation
if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){
Logging.warn(this, "Skipping HRMID revocation of " + pOldHRMID.toString() + " for " + pCluster);
}
}
}
}
/**
* Registers a superior coordinator at the local database
*
* @param pSuperiorCoordinatorClusterName a description of the announced superior coordinator
*/
public void registerSuperiorCoordinator(ClusterName pSuperiorCoordinatorClusterName)
{
boolean tUpdateGui = false;
synchronized (mSuperiorCoordinators) {
if(!mSuperiorCoordinators.contains(pSuperiorCoordinatorClusterName)){
Logging.log(this, "Registering superior coordinator: " + pSuperiorCoordinatorClusterName + ", knowing these superior coordinators: " + mSuperiorCoordinators);
mSuperiorCoordinators.add(pSuperiorCoordinatorClusterName);
tUpdateGui = true;
}else{
// already registered
}
}
/**
* Update the GUI
*/
// updates the GUI decoration for this node
if(tUpdateGui){
updateGUINodeDecoration();
}
}
/**
* Unregisters a formerly registered superior coordinator from the local database
*
* @param pSuperiorCoordinatorClusterName a description of the invalid superior coordinator
*/
public void unregisterSuperiorCoordinator(ClusterName pSuperiorCoordinatorClusterName)
{
boolean tUpdateGui = false;
synchronized (mSuperiorCoordinators) {
if(mSuperiorCoordinators.contains(pSuperiorCoordinatorClusterName)){
Logging.log(this, "Unregistering superior coordinator: " + pSuperiorCoordinatorClusterName + ", knowing these superior coordinators: " + mSuperiorCoordinators);
mSuperiorCoordinators.remove(pSuperiorCoordinatorClusterName);
tUpdateGui = true;
}else{
// already removed or never registered
}
}
/**
* Update the GUI
*/
// updates the GUI decoration for this node
if(tUpdateGui){
updateGUINodeDecoration();
}
}
/**
* Returns all superior coordinators
*
* @return the superior coordinators
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterName> getAllSuperiorCoordinators()
{
LinkedList<ClusterName> tResult = null;
synchronized (mSuperiorCoordinators) {
tResult = (LinkedList<ClusterName>) mSuperiorCoordinators.clone();
}
return tResult;
}
/**
* Returns a list of known coordinator as cluster members.
*
* @return the list of known coordinator as cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<CoordinatorAsClusterMember> getAllCoordinatorAsClusterMembers()
{
LinkedList<CoordinatorAsClusterMember> tResult = null;
synchronized (mLocalCoordinatorAsClusterMemebers) {
tResult = (LinkedList<CoordinatorAsClusterMember>) mLocalCoordinatorAsClusterMemebers.clone();
}
return tResult;
}
/**
* Returns a list of known cluster members.
*
* @return the list of known cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterMember> getAllClusterMembers()
{
LinkedList<ClusterMember> tResult = null;
synchronized (mLocalClusterMembers) {
tResult = (LinkedList<ClusterMember>) mLocalClusterMembers.clone();
}
return tResult;
}
/**
* Returns a list of known L0 cluster members.
*
* @return the list of known L0 cluster members
*/
@SuppressWarnings("unchecked")
public LinkedList<ClusterMember> getAllL0ClusterMembers()
{
LinkedList<ClusterMember> tResult = null;
synchronized (mLocalL0ClusterMembers) {
tResult = (LinkedList<ClusterMember>) mLocalL0ClusterMembers.clone();
}
return tResult;
}
/**
* Returns a list of known cluster members (including local Cluster objects) for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of cluster members
*/
public LinkedList<ClusterMember> getAllClusterMembers(HierarchyLevel pHierarchyLevel)
{
return getAllClusterMembers(pHierarchyLevel.getValue());
}
/**
* Returns a list of known CoordinatorAsClusterMember for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of CoordinatorAsClusterMember
*/
public LinkedList<CoordinatorAsClusterMember> getAllCoordinatorAsClusterMembers(int pHierarchyLevel)
{
LinkedList<CoordinatorAsClusterMember> tResult = new LinkedList<CoordinatorAsClusterMember>();
// get a list of all known coordinators
LinkedList<CoordinatorAsClusterMember> tAllCoordinatorAsClusterMembers = getAllCoordinatorAsClusterMembers();
// iterate over all known coordinators
for (CoordinatorAsClusterMember tCoordinatorAsClusterMember : tAllCoordinatorAsClusterMembers){
// have we found a matching coordinator?
if (tCoordinatorAsClusterMember.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tCoordinatorAsClusterMember);
}
}
return tResult;
}
/**
* Returns a list of known cluster members (including local Cluster objects) for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of cluster members
*/
public LinkedList<ClusterMember> getAllClusterMembers(int pHierarchyLevel)
{
LinkedList<ClusterMember> tResult = new LinkedList<ClusterMember>();
// get a list of all known coordinators
LinkedList<ClusterMember> tAllClusterMembers = getAllClusterMembers();
// iterate over all known coordinators
for (ClusterMember tClusterMember : tAllClusterMembers){
// have we found a matching coordinator?
if (tClusterMember.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tClusterMember);
}
}
return tResult;
}
/**
* Returns a list of known clusters.
*
* @return the list of known clusters
*/
@SuppressWarnings("unchecked")
public LinkedList<Cluster> getAllClusters()
{
LinkedList<Cluster> tResult = null;
synchronized (mLocalClusters) {
tResult = (LinkedList<Cluster>) mLocalClusters.clone();
}
return tResult;
}
/**
* Returns a list of known clusters for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of clusters
*/
public LinkedList<Cluster> getAllClusters(HierarchyLevel pHierarchyLevel)
{
return getAllClusters(pHierarchyLevel.getValue());
}
/**
* Returns a list of known clusters for a given hierarchy level.
*
* @param pHierarchyLevel the hierarchy level
*
* @return the list of clusters
*/
public LinkedList<Cluster> getAllClusters(int pHierarchyLevel)
{
LinkedList<Cluster> tResult = new LinkedList<Cluster>();
// get a list of all known coordinators
LinkedList<Cluster> tAllClusters = getAllClusters();
// iterate over all known coordinators
for (Cluster tCluster : tAllClusters){
// have we found a matching coordinator?
if (tCluster.getHierarchyLevel().getValue() == pHierarchyLevel){
// add this coordinator to the result
tResult.add(tCluster);
}
}
return tResult;
}
/**
* Returns the locally known Cluster object for a given hierarchy level
*
* @param pHierarchyLevel the hierarchy level for which the Cluster object is searched
*
* @return the found Cluster object
*/
public Cluster getCluster(int pHierarchyLevel)
{
Cluster tResult = null;
for(Cluster tKnownCluster : getAllClusters()) {
if(tKnownCluster.getHierarchyLevel().getValue() == pHierarchyLevel) {
tResult = tKnownCluster;
break;
}
}
return tResult;
}
/**
* Returns the locally known Coordinator object for a given hierarchy level
*
* @param pHierarchyLevelValue the hierarchy level for which the Coordinator object is searched
*
* @return the found Coordinator object
*/
private Coordinator getCoordinator(int pHierarchyLevelValue)
{
Coordinator tResult = null;
for(Coordinator tKnownCoordinator : getAllCoordinators()) {
if(tKnownCoordinator.getHierarchyLevel().getValue() == pHierarchyLevelValue) {
tResult = tKnownCoordinator;
break;
}
}
return tResult;
}
/**
* Returns a locally known Coordinator object for a given hierarchy level.
* HINT: For base hierarchy level, there could exist more than one local coordinator!
*
* @param pHierarchyLevel the hierarchy level for which the Coordinator object is searched
*
* @return the found Coordinator object
*/
public Coordinator getCoordinator(HierarchyLevel pHierarchyLevel)
{
Coordinator tResult = null;
for(Coordinator tKnownCoordinator : getAllCoordinators()) {
if(tKnownCoordinator.getHierarchyLevel().equals(pHierarchyLevel)) {
tResult = tKnownCoordinator;
break;
}
}
return tResult;
}
/**
* Returns the locally known CoordinatorProxy object, which was identified by its ClusterName
*
* @param pClusterName the cluster name of the searched coordinator proxy
*
* @return the desired CoordinatorProxy, null if the coordinator isn't known
*/
public CoordinatorProxy getCoordinatorProxyByName(ClusterName pClusterName)
{
CoordinatorProxy tResult = null;
synchronized (mLocalCoordinatorProxies) {
for (CoordinatorProxy tCoordinatorProxy : mLocalCoordinatorProxies){
if(tCoordinatorProxy.equals(pClusterName)){
tResult = tCoordinatorProxy;
break;
}
}
}
return tResult;
}
/**
* Returns a known coordinator, which is identified by its ID.
*
* @param pCoordinatorID the coordinator ID
*
* @return the searched coordinator object
*/
public Coordinator getCoordinatorByID(long pCoordinatorID)
{
Coordinator tResult = null;
for(Coordinator tKnownCoordinator : getAllCoordinators()) {
if (tKnownCoordinator.getCoordinatorID() == pCoordinatorID) {
tResult = tKnownCoordinator;
}
}
return tResult;
}
/**
* Clusters the given hierarchy level
* HINT: It is synchronized to only one call at the same time.
*
* @param pHierarchyLevel the hierarchy level where a clustering should be done
*/
public void cluster(ControlEntity pCause, final HierarchyLevel pHierarchyLevel)
{
if(pHierarchyLevel.getValue() <= HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY_HIERARCHY_LIMIT){
Logging.log(this, "CLUSTERING REQUEST for hierarchy level: " + pHierarchyLevel.getValue() + ", cause=" + pCause);
if(mProcessorThread != null){
mProcessorThread.eventUpdateCluster(pCause, pHierarchyLevel);
}
}
}
/**
* Notifies packet processor about a new packet
*
* @param pComChannel the comm. channel which has a new received packet
*/
public void notifyPacketProcessor(ComChannel pComChannel)
{
if(mProcessorThread != null){
mProcessorThread.eventReceivedPacket(pComChannel);
}
}
/**
* Registers an outgoing communication session
*
* @param pComSession the new session
*/
public void registerSession(ComSession pComSession)
{
Logging.log(this, "Registering communication session: " + pComSession);
synchronized (mCommunicationSessions) {
mCommunicationSessions.add(pComSession);
}
}
/**
* Determines the outgoing communication session for a desired target cluster
* HINT: This function has to be called in a separate thread!
*
* @param pDestinationL2Address the L2 address of the destination
*
* @return the found comm. session or null
*/
public ComSession getCreateComSession(L2Address pDestinationL2Address)
{
ComSession tResult = null;
boolean DEBUG = false;
// is the destination valid?
if (pDestinationL2Address != null){
//Logging.log(this, "Searching for outgoing comm. session to: " + pDestinationL2Address);
synchronized (mCommunicationSessions) {
for (ComSession tComSession : mCommunicationSessions){
//Logging.log(this, " ..ComSession: " + tComSession);
// get the L2 address of the comm. session peer
L2Address tPeerL2Address = tComSession.getPeerL2Address();
if(pDestinationL2Address.equals(tPeerL2Address)){
//Logging.log(this, " ..found match");
tResult = tComSession;
break;
}else{
//Logging.log(this, " ..uninteresting");
}
}
}
// have we found an already existing connection?
if(tResult == null){
if(DEBUG){
Logging.log(this, "getCreateComSession() could find a comm. session for destination: " + pDestinationL2Address + ", knowing these sessions and their channels:");
synchronized (mCommunicationSessions) {
for (ComSession tComSession : mCommunicationSessions){
Logging.log(this, " ..ComSession: " + tComSession);
for(ComChannel tComChannel : tComSession.getAllComChannels()){
Logging.log(this, " ..ComChannel: " + tComChannel);
Logging.log(this, " ..RemoteCluster: " + tComChannel.getRemoteClusterName().toString());
}
}
}
}
/**
* Create the new connection
*/
if(DEBUG){
Logging.log(this, " ..creating new connection and session to: " + pDestinationL2Address);
}
tResult = createComSession(pDestinationL2Address);
}
}else{
//Logging.err(this, "getCreateComSession() detected invalid destination L2 address");
}
return tResult;
}
/**
* Creates a new comm. session (incl. connection) to a given destination L2 address and uses the given connection requirements
* HINT: This function has to be called in a separate thread!
*
* @param pDestinationL2Address the L2 address of the destination
*
* @return the new comm. session or null
*/
private ComSession createComSession(L2Address pDestinationL2Address)
{
ComSession tResult = null;
/**
* Create default connection requirements
*/
Description tConnectionRequirements = createHRMControllerDestinationDescription();
Logging.log(this, "Creating connection/comm. session to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements);
/**
* Create communication session
*/
Logging.log(this, " ..creating new communication session");
ComSession tComSession = new ComSession(this);
/**
* Wait until the FoGSiEm simulation is created
*/
if(HRMConfig.DebugOutput.BLOCK_HIERARCHY_UNTIL_END_OF_SIMULATION_CREATION)
{
while(!simulationCreationFinished()){
try {
Logging.log(this, "WAITING FOR END OF SIMULATION CREATION");
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
/**
* Connect to the neighbor node
*/
Connection tConnection = null;
Logging.log(this, " ..CONNECTING to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements);
try {
tConnection = connectBlock(pDestinationL2Address, tConnectionRequirements, getNode().getIdentity());
} catch (NetworkException tExc) {
Logging.err(this, "Cannot connect to: " + pDestinationL2Address, tExc);
}
Logging.log(this, " ..connectBlock() FINISHED");
if(tConnection != null) {
mCounterOutgoingConnections++;
Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections);
tComSession.startConnection(pDestinationL2Address, tConnection);
// return the created comm. session
tResult = tComSession;
}else{
Logging.err(this, " ..connection failed to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements);
}
return tResult;
}
/**
* Unregisters an outgoing communication session
*
* @param pComSession the session
*/
public void unregisterSession(ComSession pComSession)
{
Logging.log(this, "Unregistering outgoing communication session: " + pComSession);
synchronized (mCommunicationSessions) {
mCommunicationSessions.remove(pComSession);
}
}
/**
* Returns the list of registered own HRMIDs which can be used to address the physical node on which this instance is running.
*
* @return the list of HRMIDs
*/
@SuppressWarnings("unchecked")
public LinkedList<HRMID> getHRMIDs()
{
LinkedList<HRMID> tResult = null;
synchronized(mRegisteredOwnHRMIDs){
tResult = (LinkedList<HRMID>) mRegisteredOwnHRMIDs.clone();
}
return tResult;
}
/**
* Returns true if the given HRMID is a local one.
*
* @param pHRMID the HRMID
*
* @return true if the given HRMID is a local one
*/
private boolean isLocal(HRMID pHRMID)
{
boolean tResult = false;
synchronized(mRegisteredOwnHRMIDs){
for(HRMID tKnownHRMID : mRegisteredOwnHRMIDs){
if(tKnownHRMID.equals(pHRMID)){
tResult = true;
break;
}
}
}
return tResult;
}
/**
* Returns true if the local node belongs to the given Cluster
*
* @param pHRMID the HRMID of the Cluster
*
* @return true if the local node belongs to the given Cluster
*/
public boolean isLocalCluster(HRMID pClusterHRMID)
{
boolean tResult = false;
if(!pClusterHRMID.isClusterAddress()){
pClusterHRMID.setLevelAddress(0, 0);
}
synchronized(mRegisteredOwnHRMIDs){
for(HRMID tKnownHRMID : mRegisteredOwnHRMIDs){
//Logging.err(this, "Checking isCluster for " + tKnownHRMID + " and if it is " + pHRMID);
if(tKnownHRMID.isCluster(pClusterHRMID)){
//Logging.err(this, " ..true");
tResult = true;
break;
}
}
}
return tResult;
}
/**
* Determines the local sender address for a route with a given next hop
*
* @param pSource the given source
* @param pNextHop the given next hop
*
* @return the local sender address
*/
private HRMID getLocalSenderAddress(HRMID pSource, HRMID pNextHop)
{
HRMID tResult = pSource;
// figure out the L0 cluster
HRMID tNextHopL0Cluster = pNextHop;
tNextHopL0Cluster.setLevelAddress(0, 0);
synchronized(mRegisteredOwnHRMIDs){
// iterate over all local HRMIDs
for(HRMID tLocalHRMID : mRegisteredOwnHRMIDs){
if(!tLocalHRMID.isClusterAddress()){
if(tLocalHRMID.isCluster(tNextHopL0Cluster)){
tResult = tLocalHRMID.clone();
break;
}
}
}
}
return tResult;
}
/**
*
* @param pForeignHRMID
* @return
*/
private HRMID aggregateForeignHRMID(HRMID pForeignHRMID)
{
HRMID tResult = null;
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, "Aggrgating foreign HRMID: " + pForeignHRMID);
}
synchronized(mRegisteredOwnHRMIDs){
int tHierLevel = HRMConfig.Hierarchy.HEIGHT_LIMIT;
// iterate over all local HRMIDs
for(HRMID tLocalHRMID : mRegisteredOwnHRMIDs){
// ignore cluster addresses
if(!tLocalHRMID.isClusterAddress()){
/**
* Is the potentially foreign HRMID a local one?
*/
if(tLocalHRMID.equals(pForeignHRMID)){
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..found matching local HRMID: " + tLocalHRMID);
}
tResult = pForeignHRMID;
break;
}
/**
* Determine the foreign cluster in relation to current local HRMID
*/
HRMID tForeignCluster = tLocalHRMID.getForeignCluster(pForeignHRMID);
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..foreign cluster of " + pForeignHRMID + " for " + tLocalHRMID + " is " + tForeignCluster);
}
/**
* Update the result value
*/
if((tResult == null) || (tHierLevel < tForeignCluster.getHierarchyLevel())){
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..found better result: " + tResult + ", best lvl: " + tHierLevel + ", cur. lvl: " + tForeignCluster.getHierarchyLevel());
}
tHierLevel = tForeignCluster.getHierarchyLevel();
tResult = tForeignCluster;
}
}
}
}
if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){
Logging.err(this, " ..result: " + tResult);
}
return tResult;
}
/**
* Adds an entry to the routing table of the local HRS instance.
* In opposite to addHRMRoute() from the HierarchicalRoutingService class, this function additionally updates the GUI.
* If the L2 address of the next hop is defined, the HRS will update the HRMID-to-L2ADDRESS mapping.
*
* @param pRoutingEntry the new routing entry
*
* @return true if the entry had new routing data
*/
private int mCallsAddHRMRoute = 0;
private boolean addHRMRoute(RoutingEntry pRoutingEntry)
{
boolean tResult = false;
mCallsAddHRMRoute++;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Adding (" + mCallsAddHRMRoute + ") HRM routing table entry: " + pRoutingEntry);
}
// filter invalid destinations
if(pRoutingEntry.getDest() == null){
throw new RuntimeException(this + "::addHRMRoute() detected an invalid destination in routing entry: " + pRoutingEntry);
}
// filter invalid next hop
if(pRoutingEntry.getNextHop() == null){
throw new RuntimeException(this + "::addHRMRoute() detected an invalid next hop in routing entry: " + pRoutingEntry);
}
// plausibility check
// if((!pRoutingEntry.getDest().isClusterAddress()) && (!pRoutingEntry.getDest().equals(pRoutingEntry.getNextHop()))){
// throw new RuntimeException(this + "::addHRMRoute() detected an invalid destination (should be equal to the next hop) in routing entry: " + pRoutingEntry);
// }
/**
* Inform the HRS about the new route
*/
tResult = getHRS().addHRMRoute(pRoutingEntry);
/**
* Notify GUI
*/
if(tResult){
//Logging.log(this, "Notifying GUI because of: " + pRoutingEntry + ", cause=" + pRoutingEntry.getCause());
// it's time to update the GUI
notifyGUI(pRoutingEntry);
}
return tResult;
}
/**
* Adds interesting parts of a received shared routing table
*
* @param pReceivedSharedRoutingTable the received shared routing table
* @param pReceiverHierarchyLevel the hierarchy level of the receiver
* @param pSenderHRMID the HRMID of the sender
* @param pCause the cause for this addition of routes
*/
public void addHRMRouteShare(RoutingTable pReceivedSharedRoutingTable, HierarchyLevel pReceiverHierarchyLevel, HRMID pSenderHRMID, String pCause)
{
boolean DEBUG = false;
// if(pReceiverHierarchyLevel.isBaseLevel()){
// if(!getAllCoordinators(2).isEmpty()){
// DEBUG = true;
// }
// }
for(RoutingEntry tEntry : pReceivedSharedRoutingTable){
RoutingEntry tNewLocalRoutingEntry = tEntry.clone();
if(DEBUG){
Logging.log(this, " ..received shared route: " + tNewLocalRoutingEntry + ", aggregated foreign destination: " + aggregateForeignHRMID(tNewLocalRoutingEntry.getDest()));
}
/**
* Mark as shared entry
*/
tNewLocalRoutingEntry.setSharedLink(pSenderHRMID);
boolean tDropRoute = false;
/**
* Check if the route starts at this node.
* If the route starts at a direct neighbor node, try to find a combined route and store this one instead of the original shared route.
*/
if(!isLocal(tNewLocalRoutingEntry.getSource())){
// check if the route starts - at least - at one of the direct neighbor nodes
if(isLocalCluster(tNewLocalRoutingEntry.getSource())){
/**
* The received shared route starts at one of the direct neighbor nodes
* => we derive a new route as new combination of: [route to direct neighbor] ==> [received shared route]
*/
RoutingEntry tSecondRoutePart = tNewLocalRoutingEntry.clone();
RoutingTable tLocalRoutingTable = mHierarchicalRoutingService.getRoutingTable();
// search for a routing entry to the direct neighbor node
RoutingEntry tFirstRoutePart = tLocalRoutingTable.getDirectNeighborEntry(tNewLocalRoutingEntry.getSource());
// have we found an routing entry to the source of the received shared route?
if(tFirstRoutePart != null){
tNewLocalRoutingEntry = tFirstRoutePart;
tNewLocalRoutingEntry.append(tSecondRoutePart, this + "::addHRMRouteShare(pCause) at lvl: " + pReceiverHierarchyLevel);
// reset the next hop L2 address
tNewLocalRoutingEntry.setNextHopL2Address(null);
}else{
tDropRoute = true;
if(DEBUG){
Logging.warn(this, " ..dropping uninteresting (does start at a direct neighbor node but no route to the direct neighbor could be found) route: " + tNewLocalRoutingEntry);
}
}
}else{
// drop the route
tDropRoute = true;
if(DEBUG){
Logging.warn(this, " ..dropping uninteresting (does not start neither at this node nor at a direct neighbor node) route: " + tNewLocalRoutingEntry);
}
}
}
/**
* Store only routes which start at this node
*/
if(!tDropRoute){
if(isLocal(tNewLocalRoutingEntry.getSource())){
/**
* ignore routes to cluster this nodes belong to
* => such routes are already known based on neighborhood detection of the L0 comm. channels (Clusters)
*/
if((!tNewLocalRoutingEntry.getDest().isClusterAddress()) || (!isLocalCluster(tNewLocalRoutingEntry.getDest()))){
if((!tNewLocalRoutingEntry.getDest().isClusterAddress()) || (tNewLocalRoutingEntry.getHopCount() > 1)){
// patch the source with the correct local sender address
tNewLocalRoutingEntry.setSource(getLocalSenderAddress(tNewLocalRoutingEntry.getSource(), tNewLocalRoutingEntry.getNextHop()));
tNewLocalRoutingEntry.extendCause(pCause);
tNewLocalRoutingEntry.extendCause(this + "::addHRMRouteShare() at lvl: " + pReceiverHierarchyLevel.getValue());
/**
* Set the timeout for the found shared route
* => 2 times the time period between two share phase for the sender's hierarchy level
*/
double tTimeoffset = 2 * getPeriodSharePhase(pReceiverHierarchyLevel.getValue() + 1 /* the sender is one level above */);
tNewLocalRoutingEntry.setTimeout(getSimulationTime() + tTimeoffset);
/**
* Store the found route
*/
if(DEBUG){
Logging.log(this, " ..adding shared route (timeout=" + tNewLocalRoutingEntry.getTimeout() + ", time-offset=" + tTimeoffset + "): " + tNewLocalRoutingEntry);
}
addHRMRoute(tNewLocalRoutingEntry);
}else{
if(DEBUG){
Logging.warn(this, " ..dropping uninteresting (leads to a direct neighbor node/cluster) route: " + tNewLocalRoutingEntry);
}
}
}else{
if(DEBUG){
Logging.warn(this, " ..dropping uninteresting (this node belongs to the destination cluster) route: " + tNewLocalRoutingEntry);
}
}
}else{
if(DEBUG){
Logging.err(this, " ..dropping uninteresting (does not start at this node) route: " + tNewLocalRoutingEntry);
}
}
}
}
}
/**
* Registers automatically new links in the HRG based on a given routing table entry.
* This function uses mainly the source and the next hop address. It switches between the hierarchy levels and derives for each hierarchy level the HRG link.
* For example, if a route from 1.2.3 to next 2.5.1 in order to reach 2.0.0 is given, then the following links will be added:
* 1.2.3 <==> 2.5.1
* 1.2.0 <==> 2.5.0
* 1.0.0 <==> 2.0.0
*
* @param pRoutingEntry the routing table entry
*/
public void registerAutoHRG(RoutingEntry pRoutingEntry)
{
HRMID tDestHRMID = pRoutingEntry.getDest();
if(tDestHRMID != null){
if((!tDestHRMID.isClusterAddress()) || (pRoutingEntry.getNextHop().isCluster(tDestHRMID))){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") node-2-node HRG link from " + pRoutingEntry.getSource() + " to " + pRoutingEntry.getNextHop() + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
tRoutingEntry.extendCause(this + "::registerAutoHRG() as " + tRoutingEntry);
tRoutingEntry.setTimeout(pRoutingEntry.getTimeout());
double tBefore = HRMController.getRealTime();
registerLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), tRoutingEntry);
double tSpentTime = HRMController.getRealTime() - tBefore;
if(tSpentTime > 30){
Logging.log(this, " ..registerAutoHRG()::registerLinkHRG() took " + tSpentTime + " ms for processing " + pRoutingEntry);
}
}
HRMID tGeneralizedSourceHRMID = tDestHRMID.getForeignCluster(pRoutingEntry.getSource());
// get the hierarchy level at which this link connects two clusters
int tLinkHierLvl = tGeneralizedSourceHRMID.getHierarchyLevel();
// initialize the source cluster HRMID
HRMID tSourceClusterHRMID = pRoutingEntry.getSource();
// initialize the destination cluster HRMID
HRMID tDestClusterHRMID = pRoutingEntry.getNextHop();
for(int i = 0; i <= tLinkHierLvl; i++){
// reset the value for the corresponding hierarchy level for both the source and destination cluster HRMID
tSourceClusterHRMID.setLevelAddress(i, 0);
tDestClusterHRMID.setLevelAddress(i, 0);
if(!tSourceClusterHRMID.equals(tDestClusterHRMID)){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") cluster-2-cluster (lvl: " + i + ") HRG link from " + tSourceClusterHRMID + " to " + tDestClusterHRMID + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
// tRoutingEntry.setDest(tDestClusterHRMID);
// RoutingEntry.create(pRoutingEntry.getSource().clone(), tDestClusterHRMID.clone(), pRoutingEntry.getNextHop().clone(), RoutingEntry.NO_HOP_COSTS, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE, pRoutingEntry.getCause());
// tRoutingEntry.setNextHopL2Address(pRoutingEntry.getNextHopL2Address());
tRoutingEntry.extendCause(this + "::registerAutoHRG() with destination " + tRoutingEntry.getDest() + ", org. destination=" +pRoutingEntry.getDest() + " as " + tRoutingEntry);
// tRoutingEntry.setTimeout(pRoutingEntry.getTimeout());
registerCluster2ClusterLinkHRG(tSourceClusterHRMID, tDestClusterHRMID, tRoutingEntry);
}
}
}
}
/**
* Adds a table to the routing table of the local HRS instance.
* In opposite to addHRMRoute() from the HierarchicalRoutingService class, this function additionally updates the GUI.
* If the L2 address of the next hop is defined, the HRS will update the HRMID-to-L2ADDRESS mapping.
*
* @param pRoutingTable the routing table with new entries
*
* @return true if the table had new routing data
*/
public boolean addHRMRoutes(RoutingTable pRoutingTable)
{
boolean tResult = false;
for(RoutingEntry tEntry : pRoutingTable){
tResult |= addHRMRoute(tEntry);
}
return tResult;
}
/**
* Deletes a route from the local HRM routing table.
*
* @param pRoutingTableEntry the routing table entry
*
* @return true if the entry was found and removed, otherwise false
*/
private boolean delHRMRoute(RoutingEntry pRoutingEntry)
{
boolean tResult = false;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Deleting HRM routing table entry: " + pRoutingEntry);
}
/**
* Inform the HRS about the new route
*/
tResult = getHRS().delHRMRoute(pRoutingEntry);
/**
* Notify GUI
*/
if(tResult){
pRoutingEntry.extendCause(this + "::delHRMRoute()");
// it's time to update the GUI
notifyGUI(pRoutingEntry);
}
return tResult;
}
/**
* Unregisters automatically old links from the HRG based on a given routing table entry
*
* @param pRoutingEntry the routing table entry
*/
public void unregisterAutoHRG(RoutingEntry pRoutingEntry)
{
HRMID tDestHRMID = pRoutingEntry.getDest();
if(tDestHRMID != null){
if((!tDestHRMID.isClusterAddress()) || (pRoutingEntry.getNextHop().isCluster(tDestHRMID))){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..unregistering (" + mCallsAddHRMRoute + ") node-2-node HRG link from " + pRoutingEntry.getSource() + " to " + pRoutingEntry.getNextHop() + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
unregisterLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), tRoutingEntry);
}
HRMID tGeneralizedSourceHRMID = tDestHRMID.getForeignCluster(pRoutingEntry.getSource());
// get the hierarchy level at which this link connects two clusters
int tLinkHierLvl = tGeneralizedSourceHRMID.getHierarchyLevel();
// initialize the source cluster HRMID
HRMID tSourceClusterHRMID = pRoutingEntry.getSource().clone();
// initialize the destination cluster HRMID
HRMID tDestClusterHRMID = pRoutingEntry.getNextHop().clone();
for(int i = 0; i <= tLinkHierLvl; i++){
// reset the value for the corresponding hierarchy level for both the source and destination cluster HRMID
tSourceClusterHRMID.setLevelAddress(i, 0);
tDestClusterHRMID.setLevelAddress(i, 0);
if(!tSourceClusterHRMID.equals(tDestClusterHRMID)){
if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){
Logging.log(this, " ..unregistering (" + mCallsAddHRMRoute + ") cluster-2-cluster (lvl: " + i + ") HRG link from " + tSourceClusterHRMID + " to " + tDestClusterHRMID + " for: " + pRoutingEntry);
}
RoutingEntry tRoutingEntry = pRoutingEntry.clone();
// tRoutingEntry.setDest(tDestClusterHRMID);
// RoutingEntry.create(pRoutingEntry.getSource().clone(), tDestClusterHRMID.clone(), pRoutingEntry.getNextHop().clone(), RoutingEntry.NO_HOP_COSTS, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE, pRoutingEntry.getCause());
// tRoutingEntry.setNextHopL2Address(pRoutingEntry.getNextHopL2Address());
tRoutingEntry.extendCause(this + "::unregisterAutoHRG() with destination " + tRoutingEntry.getDest() + ", org. destination=" +pRoutingEntry.getDest());
// tRoutingEntry.setTimeout(pRoutingEntry.getTimeout());
unregisterCluster2ClusterLinkHRG(tSourceClusterHRMID, tDestClusterHRMID, tRoutingEntry);
}
}
}
}
/**
* Removes a table from the routing table of the local HRS instance.
*
* @param pRoutingTable the routing table with old entries
*
* @return true if the table had existing routing data
*/
public boolean delHRMRoutes(RoutingTable pRoutingTable)
{
boolean tResult = false;
for(RoutingEntry tEntry : pRoutingTable){
RoutingEntry tDeleteThis = tEntry.clone();
tDeleteThis.extendCause(this + "::delHRMRoutes()");
tResult |= delHRMRoute(tDeleteThis);
}
return tResult;
}
/**
* Adds a route to the local L2 routing table.
*
* @param pToL2Address the L2Address of the destination
* @param pRoute the route to the direct neighbor
*/
public void registerL2Route(L2Address pToL2Address, Route pRoute)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "REGISTERING LINK (L2):\n DEST.=" + pToL2Address + "\n LINK=" + pRoute);
}
// inform the HRS about the new route
if(getHRS().registerL2Route(pToL2Address, pRoute)){
// it's time to update the GUI
notifyGUI(pRoute);
}
}
/**
* Connects to a service with the given name. Method blocks until the connection has been set up.
*
* @param pDestination the connection destination
* @param pRequirements the requirements for the connection
* @param pIdentity the identity of the connection requester
*
* @return the created connection
*
* @throws NetworkException
*/
public Connection connectBlock(Name pDestination, Description pRequirements, Identity pIdentity) throws NetworkException
{
Logging.log(this, "\n\n\n========> OUTGOING CONNECTION REQUEST TO: " + pDestination + " with requirements: " + pRequirements);
// connect
Connection tConnection = getLayer().connect(pDestination, pRequirements, pIdentity);
Logging.log(this, " ..=====> got connection: " + tConnection);
// create blocking event handler
BlockingEventHandling tBlockingEventHandling = new BlockingEventHandling(tConnection, 1);
// wait for the first event
Event tEvent = tBlockingEventHandling.waitForEvent();
Logging.log(this, " ..=====> got connection event: " + tEvent);
if(tEvent instanceof ConnectedEvent) {
if(!tConnection.isConnected()) {
throw new NetworkException(this, "Connected event but connection is not connected.");
} else {
return tConnection;
}
}else if(tEvent instanceof ErrorEvent) {
Exception exc = ((ErrorEvent) tEvent).getException();
if(exc instanceof NetworkException) {
throw (NetworkException) exc;
} else {
throw new NetworkException(this, "Can not connect to " + pDestination +".", exc);
}
}else{
throw new NetworkException(this, "Can not connect to " + pDestination +" due to " + tEvent);
}
}
/**
* Marks the FoGSiEm simulation creation as finished.
*/
public static void eventSimulationCreationHasFinished()
{
mFoGSiEmSimulationCreationFinished = true;
}
/**
* EVENT: simulation restarted
*/
public static void eventSimulationRestarted()
{
Logging.log(null, "EVENT: simulation restarted");
// reset the stored HRMController database
mRegisteredHRMControllers = new LinkedList<HRMController>();
sRegisteredCoordinators = 0;
sUnregisteredCoordinators = 0;
sResetNMS = true;
}
/**
* Checks if the entire simulation was created
*
* @return true or false
*/
private boolean simulationCreationFinished()
{
return mFoGSiEmSimulationCreationFinished;
}
/**
* Determines the Cluster object (on hierarchy level 0) for a given network interface
*
* @param pInterface the network interface
*
* @return the found Cluster object, null if nothing was found
*/
private Cluster getBaseHierarchyLevelCluster(NetworkInterface pInterface)
{
Cluster tResult = null;
LinkedList<Cluster> tBaseClusters = getAllClusters(HierarchyLevel.BASE_LEVEL);
for (Cluster tCluster : tBaseClusters){
NetworkInterface tClusterNetIf = tCluster.getBaseHierarchyLevelNetworkInterface();
if ((pInterface == tClusterNetIf) || (pInterface.equals(tCluster.getBaseHierarchyLevelNetworkInterface()))){
tResult = tCluster;
}
}
return tResult;
}
/**
* Determines the hierarchy node priority for Election processes
*
* @return the hierarchy node priority
*/
public long getHierarchyNodePriority(HierarchyLevel pLevel)
{
if (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY){
// the used hierarchy level is always "1" above of the one from the causing entity
int tHierLevel = pLevel.getValue();
if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){
// always use L1
tHierLevel = 1;
}
return mNodeHierarchyPriority[tHierLevel];
}else{
return getConnectivityNodePriority();
}
}
/**
* Determines the connectivity node priority for Election processes
*
* @return the connectivity node priority
*/
public long getConnectivityNodePriority()
{
return mNodeConnectivityPriority;
}
/**
* Sets new connectivity node priority for Election processes
*
* @param pPriority the new connectivity node priority
*/
private int mConnectivityPriorityUpdates = 0;
private synchronized void setConnectivityPriority(long pPriority)
{
Logging.log(this, "Setting new connectivity node priority: " + pPriority);
mNodeConnectivityPriority = pPriority;
mConnectivityPriorityUpdates++;
/**
* Inform all local ClusterMembers/Clusters at level 0 about the change
* HINT: we have to enforce a permanent lock of mLocalClusterMembers,
* otherwise race conditions might be caused (another ClusterMemeber
* could be created while we are updating the priorities of all the
* formerly known ones)
* HINT: mLocalClusterMembers also contains all local Clusters
*/
// get a copy of the list about local CoordinatorAsClusterMember instances in order to avoid dead lock between HRMControllerProcessor and main EventHandler
LinkedList<ClusterMember> tLocalL0ClusterMembers = getAllL0ClusterMembers();
Logging.log(this, " ..informing about the new priority: " + pPriority + " - update nr. " + mConnectivityPriorityUpdates + ")");
int i = 0;
for(ClusterMember tClusterMember : tLocalL0ClusterMembers){
// only base hierarchy level!
if(tClusterMember.getHierarchyLevel().isBaseLevel()){
Logging.log(this, " ..update (" + mConnectivityPriorityUpdates + ") - informing[" + i + "]: " + tClusterMember);
tClusterMember.eventConnectivityNodePriorityUpdate(getConnectivityNodePriority());
i++;
}
}
}
/**
* EVENT: hierarchy data changed
*/
private void eventHierarchyDataChanged()
{
/**
* Refresh the stored simulation time describing when the last AnnounceCoordinator packet had impact on the hierarchy
*/
mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = getSimulationTime();
/**
* If GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS is deactivated and the topology changes, we have deactivated the
* AnnounceCoordinator packets too early or the user has deactivated it too early. -> this leads to faulty results with a high probability
*/
if(!GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){
Logging.err(this, "------------------------------------------------------------------------------------------------------------------");
Logging.err(this, "--- Detected a hierarchy data change when GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS was already set to false ");
Logging.err(this, "------------------------------------------------------------------------------------------------------------------");
}
}
/**
* Distributes hierarchy node priority update to all important local entities
*
* @param pHierarchyLevel the hierarchy level
*/
public void distributeHierarchyNodePriorityUpdate(HierarchyLevel pHierarchyLevel)
{
long tNewPrio = getHierarchyNodePriority(pHierarchyLevel);
/**
* Inform all local CoordinatorAsClusterMemeber objects about the change
* HINT: we have to enforce a permanent lock of mLocalCoordinatorAsClusterMemebers,
* otherwise race conditions might be caused (another CoordinatorAsClusterMemeber
* could be created while we are updating the priorities of all the
* formerly known ones)
*/
Logging.log(this, " ..informing about the priority (" + tNewPrio + ") update (" + mHierarchyPriorityUpdates + ")");
// get a copy of the list about local CoordinatorAsClusterMember instances in order to avoid dead lock between HRMControllerProcessor and main EventHandler
LinkedList<CoordinatorAsClusterMember> tLocalCoordinatorAsClusterMembers = getAllCoordinatorAsClusterMembers();
int i = 0;
for(CoordinatorAsClusterMember tCoordinatorAsClusterMember : tLocalCoordinatorAsClusterMembers){
if((tCoordinatorAsClusterMember.getHierarchyLevel().equals(pHierarchyLevel)) || (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
Logging.log(this, " ..update (" + mHierarchyPriorityUpdates + ") - informing[" + i + "]: " + tCoordinatorAsClusterMember);
tCoordinatorAsClusterMember.eventHierarchyNodePriorityUpdate(getHierarchyNodePriority(pHierarchyLevel));
i++;
}
}
// get a copy of the list about local CoordinatorAsClusterMember instances in order to avoid dead lock between HRMControllerProcessor and main EventHandler
LinkedList<Cluster> tLocalClusters = getAllClusters();
i = 0;
for(Cluster tLocalCluster : tLocalClusters){
if((tLocalCluster.getHierarchyLevel().equals(pHierarchyLevel)) || (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
Logging.log(this, " ..update (" + mHierarchyPriorityUpdates + ") - informing[" + i + "]: " + tLocalCluster);
tLocalCluster.eventHierarchyNodePriorityUpdate(getHierarchyNodePriority(pHierarchyLevel));
i++;
}
}
}
/**
* Sets new hierarchy node priority for Election processes
*
* @param pPriority the new hierarchy node priority
* @param pHierarchyLevel the hierarchy level
*/
private int mHierarchyPriorityUpdates = 0;
private synchronized void setHierarchyPriority(long pPriority, HierarchyLevel pHierarchyLevel)
{
Logging.log(this, "Setting new hierarchy node priority: " + pPriority);
mNodeHierarchyPriority[pHierarchyLevel.getValue()] = pPriority;
mHierarchyPriorityUpdates++;
Logging.log(this, " ..informing about the priority (" + pPriority + ") update (" + mHierarchyPriorityUpdates + ")");
/**
* Asynchronous execution of "distributeHierarchyNodePriorityUpdate()" inside context of HRMControllerProcessor.
* This also reduces convergence time for finding the correct network clustering
*/
if(mProcessorThread != null){
mProcessorThread.eventNewHierarchyPriority(pHierarchyLevel);
}
//HINT: for synchronous execution use here "distributeHierarchyNodePriorityUpdate(pHierarchyLevel)"
// instead of "mProcessorThread.eventNewHierarchyPriority(pHierarchyLevel)"
/**
* Trigger: hierarchy data changed
*/
eventHierarchyDataChanged();
}
/**
* Increases base Election priority
*
* @param pCausingInterfaceToNeighbor the update causing interface to a neighbor
*/
private synchronized void increaseNodePriority_Connectivity(NetworkInterface pCausingInterfaceToNeighbor)
{
// get the current priority
long tPriority = getConnectivityNodePriority();
Logging.log(this, "Increasing node priority (CONNECTIVITY) by " + ElectionPriority.OFFSET_FOR_CONNECTIVITY);
// increase priority
tPriority += ElectionPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionConnectivityPriorityUpdates += "\n + " + ElectionPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor;
// update priority
setConnectivityPriority(tPriority);
Logging.log(this, "Increasing hierarchy node priority (CONNECTIVITY) by " + ElectionPriority.OFFSET_FOR_CONNECTIVITY);
// get the current priority
long tHierarchyPriority = mNodeHierarchyPriority[1];
// increase priority
tHierarchyPriority += ElectionPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionHierarchyPriorityUpdates += "\n + " + ElectionPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor;
// update priority
setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1));
}
/**
* Decreases base Election priority
*
* @param pCausingInterfaceToNeighbor the update causing interface to a neighbor
*/
private synchronized void decreaseNodePriority_Connectivity(NetworkInterface pCausingInterfaceToNeighbor)
{
// get the current priority
long tPriority = getConnectivityNodePriority();
Logging.log(this, "Decreasing node priority (CONNECTIVITY) by " + ElectionPriority.OFFSET_FOR_CONNECTIVITY);
// increase priority
tPriority -= ElectionPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionConnectivityPriorityUpdates += "\n - " + ElectionPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor;
// update priority
setConnectivityPriority(tPriority);
Logging.log(this, "Decreasing hierarchy node priority (CONNECTIVITY) by " + ElectionPriority.OFFSET_FOR_CONNECTIVITY);
// get the current priority
long tHierarchyPriority = mNodeHierarchyPriority[1];
// increase priority
tHierarchyPriority -= ElectionPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionHierarchyPriorityUpdates += "\n - " + ElectionPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor;
// update priority
setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1));
}
/**
* Increases hierarchy Election priority
*
* @param pCausingEntity the update causing entity
*/
public void increaseHierarchyNodePriority_KnownCoordinator(ControlEntity pCausingEntity)
{
/**
* Are we at base hierarchy level or should we accept all levels?
*/
if((pCausingEntity.getHierarchyLevel().isBaseLevel()) || (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
// the used hierarchy level is always "1" above of the one from the causing entity
int tHierLevel = pCausingEntity.getHierarchyLevel().getValue() + 1;
if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){
// always use L1
tHierLevel = 1;
}
int tDistance = 0;
if(pCausingEntity instanceof CoordinatorProxy){
tDistance = ((CoordinatorProxy)pCausingEntity).getDistance();
}
int tMaxDistance = HRMConfig.Hierarchy.EXPANSION_RADIUS;
if(!pCausingEntity.getHierarchyLevel().isBaseLevel()){
tMaxDistance = HRMConfig.Hierarchy.MAX_HOPS_TO_A_REMOTE_COORDINATOR;
}
if((tDistance >= 0) && (tDistance <= tMaxDistance)){
// get the current priority
long tPriority = mNodeHierarchyPriority[tHierLevel];
float tOffset = 0;
if (pCausingEntity.getHierarchyLevel().isBaseLevel()){
tOffset = (float)ElectionPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance);
}else{
tOffset = (float)ElectionPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L1p_COORDINATOR * (2 + tMaxDistance - tDistance);
}
Logging.log(this, "Increasing hierarchy node priority (KNOWN BASE COORDINATOR) by " + (long)tOffset + ", distance=" + tDistance + "/" + tMaxDistance);
// increase priority
tPriority += (long)(tOffset);
String tSpace = "";
for(int i = 0; i < tHierLevel; i++){
tSpace += " ";
}
mDesriptionHierarchyPriorityUpdates += "\n + " + tSpace + tPriority + "-L" + tHierLevel + ": " + tOffset + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity;
// update priority
setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel));
}else{
Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance);
}
}
}
/**
* Decreases hierarchy Election priority
*
* @param pCausingEntity the update causing entity
*/
public void decreaseHierarchyNodePriority_KnownCoordinator(ControlEntity pCausingEntity)
{
/**
* Are we at base hierarchy level or should we accept all levels?
*/
if((pCausingEntity.getHierarchyLevel().isBaseLevel()) || (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){
// the used hierarchy level is always "1" above of the one from the causing entity
int tHierLevel = pCausingEntity.getHierarchyLevel().getValue() + 1;
if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){
// always use L1
tHierLevel = 1;
}
int tDistance = 0;
if(pCausingEntity instanceof CoordinatorProxy){
tDistance = ((CoordinatorProxy)pCausingEntity).getDistance();
}
int tMaxDistance = HRMConfig.Hierarchy.EXPANSION_RADIUS;
if(!pCausingEntity.getHierarchyLevel().isBaseLevel()){
tMaxDistance = HRMConfig.Hierarchy.MAX_HOPS_TO_A_REMOTE_COORDINATOR;
}
if((tDistance >= 0) && (tDistance <= tMaxDistance)){
// get the current priority
long tPriority = mNodeHierarchyPriority[tHierLevel];
float tOffset = 0;
if (pCausingEntity.getHierarchyLevel().isBaseLevel()){
tOffset = (float)ElectionPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance);
}else{
tOffset = (float)ElectionPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L1p_COORDINATOR * (2 + tMaxDistance - tDistance);
}
Logging.log(this, "Decreasing hierarchy node priority (KNOWN BASE COORDINATOR) by " + (long)tOffset + ", distance=" + tDistance + "/" + tMaxDistance);
// decrease priority
tPriority -= (long)(tOffset);
String tSpace = "";
for(int i = 0; i < tHierLevel; i++){
tSpace += " ";
}
mDesriptionHierarchyPriorityUpdates += "\n - " + tSpace + tPriority + "-L" + tHierLevel + ": " + tOffset + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity;
// update priority
setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel));
}else{
Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance);
}
}
}
/**
* Returns a description about all connectivity priority updates.
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public String getGUIDescriptionConnectivityPriorityUpdates()
{
return mDesriptionConnectivityPriorityUpdates;
}
/**
* Returns a description about all HRMID updates.
*
* @return the description
*/
public String getGUIDescriptionHRMIDChanges()
{
return mDescriptionHRMIDUpdates;
}
/**
* Returns a description about all HRG updates.
*
* @return the description
*/
public String getGUIDescriptionHRGChanges()
{
return mDescriptionHRGUpdates;
}
/**
* Returns a description about all hierarchy priority updates
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public String getGUIDescriptionHierarchyPriorityUpdates()
{
return mDesriptionHierarchyPriorityUpdates;
}
/**
* Returns a log about "update cluster" events
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public String getGUIDescriptionClusterUpdates()
{
return mProcessorThread.getGUIDescriptionClusterUpdates();
}
/**
* Returns a description about all used cluster addresses
*
* @return the description
*/
public String getGUIDEscriptionUsedAddresses()
{
String tResult = "";
LinkedList<Cluster> tAllClusters = getAllClusters();
for (Cluster tCluster : tAllClusters){
tResult += "\n .." + tCluster + " uses these addresses:";
LinkedList<Integer> tUsedAddresses = tCluster.getUsedAddresses();
int i = 0;
for (int tUsedAddress : tUsedAddresses){
tResult += "\n ..[" + i + "]: " + tUsedAddress;
i++;
}
LinkedList<ComChannel> tAllClusterChannels = tCluster.getComChannels();
tResult += "\n .." + tCluster + " channels:";
i = 0;
for(ComChannel tComChannel : tAllClusterChannels){
tResult += "\n ..[" + i + "]: " + tComChannel;
i++;
}
}
return tResult;
}
/**
* Reacts on a lost physical neighbor.
* HINT: "pNeighborL2Address" doesn't correspond to the neighbor's central FN!
*
* @param pInterfaceToNeighbor the network interface to the neighbor
* @param pNeighborL2Address the L2 address of the detected physical neighbor's first FN towards the common bus.
*/
public synchronized void eventLostPhysicalNeighborNode(final NetworkInterface pInterfaceToNeighbor, L2Address pNeighborL2Address)
{
Logging.log(this, "\n\n\n############## LOST DIRECT NEIGHBOR NODE " + pNeighborL2Address + ", interface=" + pInterfaceToNeighbor);
synchronized (mCommunicationSessions) {
Logging.log(this, " ..known sessions: " + mCommunicationSessions);
for (ComSession tComSession : mCommunicationSessions){
if(tComSession.isPeer(pNeighborL2Address)){
Logging.log(this, " ..stopping session: " + tComSession);
tComSession.stopConnection();
}else{
Logging.log(this, " ..leaving session: " + tComSession);
}
}
}
synchronized (mLocalNetworkInterfaces) {
if(mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){
Integer tRefCount = mLocalNetworkInterfacesRefCount.get(pInterfaceToNeighbor);
/**
* decrease ref counter
*/
if(tRefCount == null){
Logging.err(this, "Invalid ref. count for known network interface: " + pInterfaceToNeighbor);
}
tRefCount--;
mLocalNetworkInterfacesRefCount.put(pInterfaceToNeighbor, tRefCount);
/**
* delete the network interface from the database about known network interfaces
*/
if(tRefCount.intValue() <= 1){
Logging.log(this, "\n######### Detected lost network interface: " + pInterfaceToNeighbor);
mLocalNetworkInterfaces.remove(pInterfaceToNeighbor);
}
}
decreaseNodePriority_Connectivity(pInterfaceToNeighbor);
}
// updates the GUI decoration for this node
updateGUINodeDecoration();
}
/**
* Reacts on a detected new physical neighbor. A new connection to this neighbor is created.
* HINT: "pNeighborL2Address" doesn't correspond to the neighbor's central FN!
*
* @param pInterfaceToNeighbor the network interface to the neighbor
* @param pNeighborL2Address the L2 address of the detected physical neighbor's first FN towards the common bus.
*/
public synchronized void eventDetectedPhysicalNeighborNode(final NetworkInterface pInterfaceToNeighbor, final L2Address pNeighborL2Address)
{
Logging.log(this, "\n\n\n############## FOUND DIRECT NEIGHBOR NODE " + pNeighborL2Address + ", interface=" + pInterfaceToNeighbor);
/**
* Helper for having access to the HRMController within the created thread
*/
final HRMController tHRMController = this;
/**
* Create connection thread
*/
Thread tThread = new Thread() {
public String toString()
{
return tHRMController.toString();
}
public void run()
{
Thread.currentThread().setName("NeighborConnector@" + tHRMController.getNodeGUIName() + " for " + pNeighborL2Address);
/**
* Create/get the cluster on base hierarchy level
*/
Cluster tParentCluster = null;
synchronized (mLocalNetworkInterfaces) {
/**
* add the network interface to the database about known network interfaces
*/
if(!mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){
Logging.log(this, "\n######### Detected new network interface: " + pInterfaceToNeighbor);
mLocalNetworkInterfaces.add(pInterfaceToNeighbor);
}
/**
* increase the ref. coutner for this network interface
*/
Integer tRefCount = mLocalNetworkInterfacesRefCount.get(pInterfaceToNeighbor);
if(tRefCount == null){
tRefCount = new Integer(1);
}else{
tRefCount++;
}
mLocalNetworkInterfacesRefCount.put(pInterfaceToNeighbor, tRefCount);
//HINT: we make sure that we use only one Cluster object per Bus
Cluster tExistingCluster = getBaseHierarchyLevelCluster(pInterfaceToNeighbor);
if (tExistingCluster != null){
Logging.log(this, " ..using existing level0 cluster: " + tExistingCluster);
tParentCluster = tExistingCluster;
}else{
Logging.log(this, " ..knowing level0 clusters: " + getAllClusters(0));
Logging.log(this, " ..creating new level0 cluster");
tParentCluster = Cluster.createBaseCluster(tHRMController);
tParentCluster.setBaseHierarchyLevelNetworkInterface(pInterfaceToNeighbor);
increaseNodePriority_Connectivity(pInterfaceToNeighbor);
// updates the GUI decoration for this node
updateGUINodeDecoration();
}
}
/**
* Create communication session
*/
Logging.log(this, " ..get/create communication session");
ComSession tComSession = getCreateComSession(pNeighborL2Address);
if(tComSession != null) {
/**
* Update ARG
*/
//registerLinkARG(this, tParentCluster, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.REMOTE_CONNECTION));
/**
* Create communication channel
*/
Logging.log(this, " ..creating new communication channel");
ComChannel tComChannel = new ComChannel(tHRMController, ComChannel.Direction.OUT, tParentCluster, tComSession);
tComChannel.setRemoteClusterName(tParentCluster.createClusterName());
/**
* Send "RequestClusterMembership" along the comm. session
* HINT: we cannot use the created channel because the remote side doesn't know anything about the new comm. channel yet)
*/
RequestClusterMembership tRequestClusterMembership = new RequestClusterMembership(getNodeName(), pNeighborL2Address, tParentCluster.createClusterName(), tParentCluster.createClusterName());
Logging.log(this, " ..sending membership request: " + tRequestClusterMembership);
if (tComSession.write(tRequestClusterMembership)){
Logging.log(this, " ..requested sucessfully for membership of: " + tParentCluster + " at node " + pNeighborL2Address);
}else{
Logging.log(this, " ..failed to request for membership of: " + tParentCluster + " at node " + pNeighborL2Address);
}
Logging.log(this, "Connection thread for " + pNeighborL2Address + " finished");
}else{
Logging.log(this, "Connection thread for " + pNeighborL2Address + " failed");
}
}
};
/**
* Start the connection thread
*/
tThread.start();
}
/**
* Determines a reference to the current AutonomousSystem instance.
*
* @return the desired reference
*/
public AutonomousSystem getAS()
{
return mAS;
}
/**
* Returns the node-global election state
*
* @return the node-global election state
*/
public Object getNodeElectionState()
{
return mNodeElectionState;
}
/**
* Returns the node-global election state change description
* This function is only used within the GUI. It is not part of the concept.
*
* @return the description
*/
public Object getGUIDescriptionNodeElectionStateChanges()
{
return mDescriptionNodeElectionState;
}
/**
* Adds a description to the node-global election state change description
*
* @param pAdd the additive string
*/
public void addGUIDescriptionNodeElectionStateChange(String pAdd)
{
mDescriptionNodeElectionState += pAdd;
}
/**
* Determines the current simulation time
*
* @return the simulation time
*/
public double getSimulationTime()
{
return mAS.getTimeBase().now();
}
/**
* Determines the current real time
*
* @return the real time in [ms]
*/
public static double getRealTime()
{
double tResult = 0;
Date tDate = new Date();
tResult = tDate.getTime();
return tResult;
}
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.IEvent#fire()
*/
@Override
public void fire()
{
reportAndShare();
}
/**
* Auto-removes all deprecated coordinator proxies
*/
private void autoRemoveObsoleteCoordinatorProxies()
{
if(HRMController.GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){
LinkedList<CoordinatorProxy> tProxies = getAllCoordinatorProxies();
for(CoordinatorProxy tProxy : tProxies){
// does the link have a timeout?
if(tProxy.isObsolete()){
Logging.log(this, "AUTO REMOVING COORDINATOR PROXY: " + tProxy);
/**
* Trigger: remote coordinator role invalid
*/
tProxy.eventRemoteCoordinatorRoleInvalid();
}
}
}
}
/**
* Auto-deactivates AnnounceCoordinator packets.
* This function is only useful for measurement speedup or to ease debugging. It is neither part of the concept nor it is used to derive additional data. It only reduces packet overhead in the network.
*/
@SuppressWarnings("unused")
private void autoDeactivateAnnounceCoordinator()
{
if(mSimulationTimeOfLastCoordinatorAnnouncementWithImpact != 0){
double tTimeWithFixedHierarchyData = getSimulationTime() - mSimulationTimeOfLastCoordinatorAnnouncementWithImpact;
//Logging.log(this, "Simulation time of last AnnounceCoordinator with impact: " + mSimulationTimeOfLastCoordinatorAnnouncementWithImpact + ", time diff: " + tTimeWithFixedHierarchyData);
if(HRMConfig.Measurement.AUTO_DEACTIVATE_ANNOUNCE_COORDINATOR_PACKETS){
if(GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){
/**
* Auto-deactivate the AnnounceCoordinator packets if no further change in hierarchy data is expected anymore
*/
if(tTimeWithFixedHierarchyData > 2 * HRMConfig.Hierarchy.COORDINATOR_TIMEOUT){
GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = false;
Logging.warn(this, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Logging.warn(this, "+++ Deactivating AnnounceCoordinator packets due to long-term stability of hierarchy data");
Logging.warn(this, "+++ Current simulation time: " + getSimulationTime() + ", treshold time diff: " + (HRMConfig.Hierarchy.COORDINATOR_TIMEOUT * 2) + ", time with stable hierarchy data: " + tTimeWithFixedHierarchyData);
Logging.warn(this, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
if(HRMConfig.Measurement.AUTO_DEACTIVATE_ANNOUNCE_COORDINATOR_PACKETS_AUTO_START_ADDRESS_DISTRIBUTION){
autoActivateAddressDistribution();
}
if((GUI_USER_CTRL_ADDRESS_DISTRUTION) && (HRMConfig.Measurement.AUTO_DEACTIVATE_ANNOUNCE_COORDINATOR_PACKETS_AUTO_START_ADDRESS_DISTRIBUTION_AUTO_START_REPORTING_SHARING)){
autoActivateReportingSharing();
}
}
}
}
}
}
private void autoActivateAddressDistribution()
{
Logging.warn(this, "+++++++++++++++++++++++++++++++++++++++++++++++++");
Logging.warn(this, "+++ Activating address distribution");
Logging.warn(this, "+++++++++++++++++++++++++++++++++++++++++++++++++");
GUI_USER_CTRL_ADDRESS_DISTRUTION = true;
// iterate over all HRMControllers
int tFound = 0;
for(HRMController tHRMController : HRMController.getALLHRMControllers()) {
LinkedList<Coordinator> tHighestCoordinators = tHRMController.getAllCoordinators(HRMConfig.Hierarchy.HEIGHT - 1);
if(!tHighestCoordinators.isEmpty()){
for (Coordinator tHighestCoordinator : tHighestCoordinators){
tFound++;
if(tFound == 1){
Logging.log(this, "Found highest coordinator: " + tHighestCoordinator);
tHighestCoordinator.getCluster().distributeAddresses();
}else{
Logging.err(this, "Found highest coordinator nr. " + tFound + ": " + tHighestCoordinator);
}
}
}
}
if(tFound == 0){
Logging.err(this, "autoActivateAddressDistribution() hasn't found the highest coordinator");
}
}
/**
* Auto-activates reporting/sharing after AnnounceCoordinator packets were deactivated.
*/
private void autoActivateReportingSharing()
{
Logging.warn(this, "+++++++++++++++++++++++++++++++++++++++++++++++++");
Logging.warn(this, "+++ Activating reporting/sharing of topology data");
Logging.warn(this, "+++++++++++++++++++++++++++++++++++++++++++++++++");
GUI_USER_CTRL_REPORT_TOPOLOGY = true;
// HINT: the report/share functions are triggered periodically and will start the start the reports/shares without any further setting
}
/**
* Validates the hierarchy creation
*/
private void validateResults()
{
if((!HRMConfig.Measurement.AUTO_DEACTIVATE_ANNOUNCE_COORDINATOR_PACKETS) || (!GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS)){
/**
* Check coordinators
*/
for (Coordinator tCoordinator : getAllCoordinators()) {
if(!tCoordinator.getHierarchyLevel().isHighest()){
if(!tCoordinator.isSuperiorCoordinatorValid()){
Logging.err(this, "validateResults() detected invalid comm. channel to superior coordinator for: " + tCoordinator);
}
}
// for (ComChannel tComChannel : tCoordinator.getClusterMembershipComChannels()){
// if(tComChannel.getPeerPriority().isUndefined()){
// Logging.err(this, "validateResults() detected undefined peer priority for CoordinatorAsClusterMember channel: " + tComChannel);
// }
// }
}
/**
* Check cluster
*/
for (Cluster tCluster : getAllClusters()) {
HierarchyLevel tClusterLevel = tCluster.getHierarchyLevel();
if(tClusterLevel.isHigherLevel()){
for (ComChannel tComChannel : tCluster.getComChannels()){
if(tComChannel.getPeerPriority().isUndefined()){
Logging.err(this, "validateResults() detected undefined peer priority for Cluster channel: " + tComChannel);
}else{
ElectionPriority tChannelPeerPriority = tComChannel.getPeerPriority();
L2Address tChanPeerL2Address = tComChannel.getPeerL2Address();
boolean tFound = false;
for(HRMController tHRMController : getALLHRMControllers()){
if(tHRMController.getNodeL2Address().equals(tChanPeerL2Address)){
// Logging.log(this, "MATCH: " + tHRMController.getNodeL2Address() + " <==> " + tChanPeerL2Address);
tFound = true;
long tFoundPriority = tHRMController.getHierarchyNodePriority(tClusterLevel);
if(tFoundPriority != tChannelPeerPriority.getValue()){
Logging.err(this, "validateResults() detected wrong peer priority: " + tChannelPeerPriority.getValue() + " but it should be " + tFoundPriority + " for: " + tComChannel);
}
break;
}else{
// Logging.log(this, "NO MATCH: " + tHRMController.getNodeL2Address() + " <==> " + tChanPeerL2Address);
}
}
if(!tFound){
Logging.err(this, "validateResults() wasn't able to find node: " + tChanPeerL2Address + " as peer of: " + tComChannel);
}
}
}
}
}
}
}
/**
* Triggers the "report phase" / "share phase" of all known coordinators
*/
private void reportAndShare()
{
if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){
Logging.log(this, "REPORT AND SHARE TRIGGER received");
}
/**
* auto-deactivate AnnounceCoordinator
*/
autoDeactivateAnnounceCoordinator();
/**
* auto-remove old CoordinatorProxies
*/
autoRemoveObsoleteCoordinatorProxies();
/**
* auto-remove old HRG links
*/
autoRemoveObsoleteHRGLinks();
/**
* generalize all known HRM routes to neighbors
*/
// generalizeMeighborHRMRoutesAuto();
if(HRMConfig.Measurement.VALIDATE_RESULTS){
validateResults();
}
if(GUI_USER_CTRL_REPORT_TOPOLOGY){
/**
* detect local neighborhood and update HRG/HRMRouting
*/
for (ClusterMember tClusterMember : getAllL0ClusterMembers()) {
tClusterMember.detectNeighborhood();
}
/**
* report phase
*/
for (Coordinator tCoordinator : getAllCoordinators()) {
tCoordinator.reportPhase();
}
/**
* share phase
*/
if(GUI_USER_CTRL_SHARE_ROUTES){
for (Coordinator tCoordinator : getAllCoordinators()) {
tCoordinator.sharePhase();
}
}
}
/**
* auto-remove old HRM routes
*/
autoRemoveObsoleteHRMRoutes();
/**
* register next trigger
*/
mAS.getTimeBase().scheduleIn(HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE, this);
}
/**
* Calculate the time period between "share phases"
*
* @param pHierarchyLevel the hierarchy level
* @return the calculated time period
*/
public double getPeriodSharePhase(int pHierarchyLevelValue)
{
switch(HRMConfig.Routing.REPORT_SHARE_PHASE_TIMING_SCHEME){
case CONSTANT:
return (double) 2 * HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE * (0 + 1);
case LINEAR:
return (double) 2 * HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE * (pHierarchyLevelValue + 1);
case EXPONENTIAL:
return (double) 2 * HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE * (pHierarchyLevelValue + 1); //TODO: use an exponential time distribution here
}
return 1;
}
/**
* Calculate the time period between "share phases"
*
* @param pHierarchyLevel the hierarchy level
* @return the calculated time period
*/
public double getPeriodReportPhase(HierarchyLevel pHierarchyLevel)
{
switch(HRMConfig.Routing.REPORT_SHARE_PHASE_TIMING_SCHEME){
case CONSTANT:
return (double) HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE * (0 + 1);
case LINEAR:
return (double) HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE * (pHierarchyLevel.getValue() + 1);
case EXPONENTIAL:
return (double) HRMConfig.Routing.REPORT_SHARE_PHASE_TIME_BASE * (pHierarchyLevel.getValue() + 1); //TODO: use an exponential time distribution here
}
return 1;
}
/**
* This method is derived from IServerCallback. It is called by the ServerFN in order to acquire the acknowledgment from the HRMController about the incoming connection
*
* @param pAuths the authentications of the requesting sender
* @param pRequirements the requirements for the incoming connection
* @param pTargetName the registered name of the addressed target service
* @return true of false
*/
@Override
public boolean openAck(LinkedList<Signature> pAuths, Description pRequirements, Name pTargetName)
{
//TODO: check if a neighbor wants to explore its neighbor -> select if we want to join its cluster or not
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Incoming request for acknowledging the connection:");
Logging.log(this, " ..source: " + pAuths);
Logging.log(this, " ..destination: " + pTargetName);
Logging.log(this, " ..requirements: " + pRequirements);
}
return true;
}
/**
* Helper function to get the local machine's host name.
* The output of this function is useful for distributed simulations if coordinators/clusters with the name might coexist on different machines.
*
* @return the host name
*/
public static String getHostName()
{
String tResult = null;
try{
tResult = java.net.InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException tExc) {
Logging.err(null, "Unable to determine the local host name", tExc);
}
return tResult;
}
/**
* Determines the L2Address of the first FN towards a neighbor. This corresponds to the FN, located between the central FN and the bus to the neighbor node.
*
* @param pNeighborName the name of the neighbor
* @return the L2Address of the search FN
*/
public L2Address getL2AddressOfFirstFNTowardsNeighbor(L2Address pNeighborName)
{
L2Address tResult = null;
if (pNeighborName != null){
if(!pNeighborName.equals(getHRS().getCentralFNL2Address())){
Route tRoute = null;
// get the name of the central FN
L2Address tCentralFNL2Address = getHRS().getCentralFNL2Address();
// get a route to the neighbor node (the destination of the desired connection)
try {
tRoute = getHRS().getRoute(pNeighborName, new Description(), getNode().getIdentity());
} catch (RoutingException tExc) {
Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() is unable to find route to " + pNeighborName, tExc);
} catch (RequirementsException tExc) {
Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() is unable to find route to " + pNeighborName + " with requirements no requirents, Huh!", tExc);
}
// have we found a route to the neighbor?
if((tRoute != null) && (!tRoute.isEmpty())) {
// get the first route part, which corresponds to the link between the central FN and the searched first FN towards the neighbor
RouteSegmentPath tPath = (RouteSegmentPath) tRoute.getFirst();
// check if route has entries
if((tPath != null) && (!tPath.isEmpty())){
// get the gate ID of the link
GateID tGateID = tPath.getFirst();
RoutingServiceLink tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor = null;
boolean tWithoutException = false; //TODO: rework some software structures to avoid this ugly implementation
while(!tWithoutException){
try{
// get all outgoing links from the central FN
Collection<RoutingServiceLink> tOutgoingLinksFromCentralFN = getHRS().getOutgoingLinks(tCentralFNL2Address);
// iterate over all outgoing links and search for the link from the central FN to the FN, which comes first when routing towards the neighbor
for(RoutingServiceLink tLink : tOutgoingLinksFromCentralFN) {
// compare the GateIDs
if(tLink.equals(tGateID)) {
// found!
tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor = tLink;
}
}
tWithoutException = true;
}catch(ConcurrentModificationException tExc){
// FoG has manipulated the topology data and called the HRS for updating the L2 routing graph
continue;
}
}
// determine the searched FN, which comes first when routing towards the neighbor
HRMName tFirstNodeBeforeBusToNeighbor = getHRS().getL2LinkDestination(tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor);
if (tFirstNodeBeforeBusToNeighbor instanceof L2Address){
// get the L2 address
tResult = (L2Address)tFirstNodeBeforeBusToNeighbor;
}else{
Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() found a first FN (" + tFirstNodeBeforeBusToNeighbor + ") towards the neighbor " + pNeighborName + " but it has the wrong class type");
}
}else{
Logging.warn(this, "getL2AddressOfFirstFNTowardsNeighbor() found an empty route to \"neighbor\": " + pNeighborName);
}
}else{
if(HRMConfig.Measurement.VALIDATE_RESULTS_EXTENSIVE){
Logging.warn(this, "Got for neighbor " + pNeighborName + " the route: " + tRoute); //HINT: this could also be a local loop -> throw only a warning
}
}
}else{
// we were ask for a route to our central FN: route is []
}
}else{
Logging.warn(this, "getL2AddressOfFirstFNTowardsNeighbor() found an invalid neighbor name");
}
return tResult;
}
/**
* This function gets called if the HRMController appl. was started
*/
@Override
protected void started()
{
mApplicationStarted = true;
// register in the global HRMController database
synchronized (mRegisteredHRMControllers) {
mRegisteredHRMControllers.add(this);
}
/**
* Reset global NMS is needed
*/
if(sResetNMS){
/**
* Reset the DNS
*/
// register the HRMID in the hierarchical DNS for the local router
HierarchicalNameMappingService<HRMID> tNMS = null;
try {
tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation());
} catch (RuntimeException tExc) {
HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation());
}
tNMS.clear();
sResetNMS = false;
}
}
/**
* This function gets called if the HRMController appl. should exit/terminate right now
*/
@Override
public synchronized void exit()
{
if(!mApplicationStarted){
Logging.err(this, "This instance is already terminated.");
return;
}
mApplicationStarted = false;
Logging.log(this, "\n\n\n############## Exiting..");
Logging.log(this, " ..destroying clusterer-thread");
if(mProcessorThread != null){
mProcessorThread.exit();
mProcessorThread = null;
}
Logging.log(this, " ..destroying all clusters/coordinators");
for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){
LinkedList<Cluster> tClusters = getAllClusters(i);
for(Cluster tCluster : tClusters){
tCluster.eventClusterRoleInvalid();
}
}
synchronized (mCommunicationSessions) {
for (ComSession tComSession : mCommunicationSessions){
tComSession.stopConnection();
}
}
// register in the global HRMController database
Logging.log(this, " ..removing from the global HRMController database");
synchronized (mRegisteredHRMControllers) {
mRegisteredHRMControllers.remove(this);
}
}
/**
* Return if the HRMController application is running
*
* @return true if the HRMController application is running, otherwise false
*/
@Override
public boolean isRunning()
{
return mApplicationStarted;
}
/**
* Returns the list of known HRMController instances for this physical simulation machine
*
* @return the list of HRMController references
*/
@SuppressWarnings("unchecked")
public static LinkedList<HRMController> getALLHRMControllers()
{
LinkedList<HRMController> tResult = null;
synchronized (mRegisteredHRMControllers) {
tResult = (LinkedList<HRMController>) mRegisteredHRMControllers.clone();
}
return tResult;
}
/**
* Creates a Description, which directs a connection to another HRMController instance
* @return the new description
*/
private Description createHRMControllerDestinationDescription()
{
Description tResult = new Description();
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "Creating a HRMController destination description");
}
tResult.set(new DestinationApplicationProperty(HRMController.ROUTING_NAMESPACE, null, null));
return tResult;
}
/**
* Registers a cluster/coordinator to the locally stored abstract routing graph (ARG)
*
* @param pNode the node (cluster/coordinator) which should be stored in the ARG
*/
private synchronized void registerNodeARG(ControlEntity pNode)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "REGISTERING NODE ADDRESS (ARG): " + pNode );
}
synchronized (mAbstractRoutingGraph) {
if(!mAbstractRoutingGraph.contains(pNode)) {
mAbstractRoutingGraph.add(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..added to ARG");
}
}else{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for ARG already known: " + pNode);
}
}
}
}
/**
* Unregisters a cluster/coordinator from the locally stored abstract routing graph (ARG)
*
* @param pNode the node (cluster/coordinator) which should be removed from the ARG
*/
private void unregisterNodeARG(ControlEntity pNode)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "UNREGISTERING NODE ADDRESS (ARG): " + pNode );
}
synchronized (mAbstractRoutingGraph) {
if(mAbstractRoutingGraph.contains(pNode)) {
mAbstractRoutingGraph.remove(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..removed from ARG");
}
}else{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for ARG wasn't known: " + pNode);
}
}
}
}
/**
* Registers a logical link between clusters/coordinators to the locally stored abstract routing graph (ARG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
* @param pLink the link between the two nodes
*/
public void registerLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo, AbstractRoutingGraphLink pLink)
{
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "REGISTERING LINK (ARG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pLink);
}
synchronized (mAbstractRoutingGraph) {
pLink.setFirstVertex(pFrom);
pLink.setSecondVertex(pTo);
mAbstractRoutingGraph.link(pFrom, pTo, pLink);
}
}
/**
* Unregisters a logical link between clusters/coordinators from the locally stored abstract routing graph (ARG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
*/
public void unregisterLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo)
{
AbstractRoutingGraphLink tLink = getLinkARG(pFrom, pTo);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, "UNREGISTERING LINK (ARG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + tLink);
}
if(tLink != null){
synchronized (mAbstractRoutingGraph) {
mAbstractRoutingGraph.unlink(tLink);
}
}
}
/**
* Determines the link between two clusters/coordinators from the locally stored abstract routing graph (ARG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
*
* @return the link between the two nodes
*/
public AbstractRoutingGraphLink getLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo)
{
AbstractRoutingGraphLink tResult = null;
List<AbstractRoutingGraphLink> tRoute = null;
synchronized (mAbstractRoutingGraph) {
tRoute = mAbstractRoutingGraph.getRoute(pFrom, pTo);
}
if((tRoute != null) && (!tRoute.isEmpty())){
if(tRoute.size() == 1){
tResult = tRoute.get(0);
}else{
/**
* We haven't found a direct link - we found a multi-hop route instead.
*/
//Logging.warn(this, "getLinkARG() expected a route with one entry but got: \nSOURCE=" + pFrom + "\nDESTINATION: " + pTo + "\nROUTE: " + tRoute);
}
}
return tResult;
}
/**
* Returns the ARG for the GraphViewer.
* (only for GUI!)
*
* @return the ARG
*/
public AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> getARGForGraphViewer()
{
AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> tResult = null;
synchronized (mAbstractRoutingGraph) {
tResult = mAbstractRoutingGraph;
}
return tResult;
}
/**
* Registers an HRMID to the locally stored hierarchical routing graph (HRG)
*
* @param pNode the node (HRMID) which should be stored in the HRG
* @param pCause the cause for this HRG update
*/
private synchronized void registerNodeHRG(HRMID pNode, String pCause)
{
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "REGISTERING NODE ADDRESS (HRG): " + pNode );
}
if(pNode.isZero()){
throw new RuntimeException(this + " detected a zero HRMID for an HRG registration");
}
synchronized (mHierarchicalRoutingGraph) {
if(!mHierarchicalRoutingGraph.contains(pNode)) {
mDescriptionHRGUpdates += "\n + " + pNode + " <== " + pCause;
mHierarchicalRoutingGraph.add(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..added to HRG");
}
}else{
mDescriptionHRGUpdates += "\n +/- " + pNode + " <== " + pCause;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for HRG already known: " + pNode);
}
}
}
}
/**
* Unregisters an HRMID from the locally stored hierarchical routing graph (HRG)
*
* @param pNode the node (HRMID) which should be removed from the HRG
* @param pCause the cause for this HRG update
*/
private void unregisterNodeHRG(HRMID pNode, String pCause)
{
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "UNREGISTERING NODE ADDRESS (HRG): " + pNode );
}
synchronized (mHierarchicalRoutingGraph) {
if(mHierarchicalRoutingGraph.contains(pNode)) {
mDescriptionHRGUpdates += "\n - " + pNode + " <== " + pCause;
mHierarchicalRoutingGraph.remove(pNode);
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..removed from HRG");
}
}else{
mDescriptionHRGUpdates += "\n -/+ " + pNode + " <== " + pCause;
if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){
Logging.log(this, " ..node for HRG wasn't known: " + pNode);
}
}
}
}
/**
* Registers a logical link between HRMIDs to the locally stored hierarchical routing graph (HRG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
* @param pRoutingEntry the routing entry for this link
*
* @return true if the link is new to the routing graph
*/
public boolean registerLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "REGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n ROUTE=" + pRoutingEntry);
}
if(!pFrom.equals(pTo)){
/**
* Derive the link
*/
double tBefore4 = HRMController.getRealTime();
pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph);
AbstractRoutingGraphLink tLink = new AbstractRoutingGraphLink(new Route(pRoutingEntry));
tLink.setTimeout(pRoutingEntry.getTimeout());
double tSpentTime4 = HRMController.getRealTime() - tBefore4;
if(tSpentTime4 > 10){
Logging.log(this, " ..registerLinkHRG()::AbstractRoutingGraphLink() took " + tSpentTime4 + " ms for processing " + pRoutingEntry);
}
/**
* Do the actual linking
*/
synchronized (mHierarchicalRoutingGraph) {
boolean tLinkAlreadyKnown = false;
double tBefore = HRMController.getRealTime();
Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom);
double tSpentTime = HRMController.getRealTime() - tBefore;
if(tSpentTime > 10){
Logging.log(this, " ..registerLinkHRG()::getOutEdges() took " + tSpentTime + " ms for processing " + pRoutingEntry);
}
if(tLinks != null){
double tBefore3 = HRMController.getRealTime();
for(AbstractRoutingGraphLink tKnownLink : tLinks){
// check if both links are equal
if(tKnownLink.equals(tLink)){
// check of the end points of the already known link are equal to the pFrom/pTo
double tBefore2 = HRMController.getRealTime();
Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink);
double tSpentTime2 = HRMController.getRealTime() - tBefore2;
if(tSpentTime2 > 10){
Logging.log(this, " ..registerLinkHRG()::getEndpoints() took " + tSpentTime2 + " ms for processing " + pRoutingEntry);
}
if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) || ((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){
tKnownLink.incRefCounter();
tLinkAlreadyKnown = true;
/**
* Update TIMEOUT
*/
if(pRoutingEntry.getTimeout() > 0){
tKnownLink.setTimeout(pRoutingEntry.getTimeout());
}
/**
* Update QOS VALUES
*/
tKnownLink.updateQoS(pRoutingEntry);
// it's time to update the HRG-GUI
notifyHRGGUI(tKnownLink);
}
}
}
double tSpentTime3 = HRMController.getRealTime() - tBefore3;
if(tSpentTime3 > 10){
Logging.log(this, " ..registerLinkHRG()::for() took " + tSpentTime3 + " ms for processing " + pRoutingEntry);
}
}
if(!tLinkAlreadyKnown){
mDescriptionHRGUpdates += "\n + " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
double tBefore1 = HRMController.getRealTime();
HRMID tFrom = pFrom.clone();
HRMID tTo = pTo.clone();
tLink.setFirstVertex(tFrom);
tLink.setSecondVertex(tTo);
mHierarchicalRoutingGraph.link(tFrom, tTo, tLink);
// it's time to update the HRG-GUI
notifyHRGGUI(tLink);
double tSpentTime1 = HRMController.getRealTime() - tBefore1;
if(tSpentTime1 > 10){
Logging.log(this, " ..registerLinkHRG()::link() took " + tSpentTime1 + " ms for processing " + pRoutingEntry);
}
}else{
/**
* The link is already known -> this can occur if:
* - both end points are located on this node and both of them try to register the same route
* - a route was reported and received as shared
*/
if(HRMConfig.DebugOutput.MEMORY_CONSUMING_OPERATIONS){
mDescriptionHRGUpdates += "\n +" + (tLinkAlreadyKnown ? "(REF)" : "") + " " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
}
}
tResult = true;
}
}else{
//Logging.warn(this, "registerLinkHRG() skipped because self-loop detected for: " + pRoutingEntry);
}
return tResult;
}
/**
* Determines all possible destinations depending on a given root node and its hierarchy level
*
* @param pRootNode the root node
*
* @return the found possible destinations
*/
public LinkedList<HRMID> getSiblingsHRG(HRMID pRootNode)
{
LinkedList<HRMID> tResult = new LinkedList<HRMID>();
HRMID tSuperCluster = pRootNode.getSuperiorClusterAddress();
int tSearchedLvl = pRootNode.getHierarchyLevel();
synchronized (mHierarchicalRoutingGraph) {
// iterate over all nodes in the HRG
Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices();
for(HRMID tNode : tNodes){
if(!tNode.equals(pRootNode)){
// does the node belong to the same hierarchy level like the root node?
if(tNode.getHierarchyLevel() == tSearchedLvl){
if(tNode.isCluster(tSuperCluster)){
tResult.add(tNode.clone());
}else{
//Logging.log(this, "Dropping " + tNode + " as sibling of " + pRootNode);
}
}
}
}
}
return tResult;
}
/**
* Determines a route in the HRG from a given node/cluster to another one
*
* @param pFrom the starting point
* @param pTo the ending point
* @param pCause the cause for this call
*
* @return the found routing entry
*/
public RoutingEntry getRoutingEntryHRG(HRMID pFrom, HRMID pTo, String pCause)
{
return getRoutingEntryHRG(mHierarchicalRoutingGraph, pFrom, pTo, pCause, null);
}
/**
* Determines a route in the HRG from a given node/cluster to another one
*
* @param pHRG the HRG which should be used
* @param pFrom the starting point
* @param pTo the ending point
* @param pCause the cause for this call
* @param pRefDeletedLinks stores the first used inter-node link which was deleted automatically (used for finding multiple routes to the destination), a value "null" deactivates the automatic deletion of links
*
* @return the found routing entry
*/
private RoutingEntry getRoutingEntryHRG(AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> pHRG, HRMID pFrom, HRMID pTo, String pCause, LinkedList<LinkedList<AbstractRoutingGraphLink>> pRefDeletedLinks)
{
boolean DEBUG = false;
RoutingEntry tResult = null;
LinkedList<AbstractRoutingGraphLink> tDeletedLinks = null;
if(pRefDeletedLinks != null){
tDeletedLinks = pRefDeletedLinks.getFirst();
}
if (DEBUG){
Logging.log(this, "getRoutingEntryHRG() searches a route from " + pFrom + " to " + pTo);
}
synchronized (pHRG){
/**********************************************
* Are the source and destination addresses equal?
*********************************************/
if(pFrom.equals(pTo)){
// create a loop route
tResult = RoutingEntry.createLocalhostEntry(pFrom, pCause);
// describe the cause for the route
tResult.extendCause(this + "::getRoutingEntry() with same source and destination address " + pFrom);
// immediate return here
return tResult;
}
/**********************************************
* Is the source address more abstract than the destination one?
* EXAMPLE 1: we are searching for a route from 1.3.0 to 1.4.2.
*********************************************/
if(pFrom.getHierarchyLevel() > pTo.getHierarchyLevel()){
/**
* EXAMPLE 1: derive cluster address 1.4.0 from 1.4.2
*/
HRMID tAbstractDestination = pTo.getClusterAddress(pFrom.getHierarchyLevel());
if (DEBUG){
Logging.log(this, "getRoutingEntryHRG() searches a more abstract route from " + pFrom + " to more abstract destination " + tAbstractDestination);
}
/**
* EXAMPLE 1: determine the route from 1.3.0 to 1.4.0
* (assumption: the found route starts at 1.3.2 and ends at 1.4.1)
*/
RoutingEntry tFirstRoutePart = getRoutingEntryHRG(pHRG, pFrom, tAbstractDestination, pCause, null);
if (DEBUG){
Logging.log(this, " ..first route part: " + tFirstRoutePart);
}
if(tFirstRoutePart != null){
HRMID tIngressGatewayToDestinationCluster = tFirstRoutePart.getLastNextHop();
/**
* EXAMPLE 1: determine the route from 1.4.1 to 1.4.2
*/
RoutingEntry tIntraClusterRoutePart = getRoutingEntryHRG(pHRG, tIngressGatewayToDestinationCluster, pTo, pCause, null);
if (DEBUG){
Logging.log(this, " ..second route part: " + tIntraClusterRoutePart);
}
if(tIntraClusterRoutePart != null){
// clone the first part and use it as first part of the result
tResult = tFirstRoutePart.clone();
/**
* EXAMPLE 1: combine routes (1.3.2 => 1.4.1) AND (1.4.1 => 1.4.2)
*/
tResult.append(tIntraClusterRoutePart, pCause);
if (DEBUG){
Logging.log(this, " ..resulting route (" + pFrom + " ==> " + tAbstractDestination + "): " + tResult);
}
/**
* EXAMPLE 1: the result is a route from gateway 1.3.2 (belonging to 1.3.0) to 1.4.2
*/
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG route from " + tIngressGatewayToDestinationCluster + " to " + pTo + " as second part for a route from " + pFrom + " to " + pTo);
}
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG route from " + pFrom + " to " + tAbstractDestination + " as first part for a route from " + pFrom + " to " + pTo);
}
return tResult;
}
int tStep = 0;
/*********************************************
* Determine the overall inter-cluster path
*********************************************/
List<AbstractRoutingGraphLink> tPath = getRouteHRG(pHRG, pFrom, pTo);
AbstractRoutingGraphLink tFirstUsedInterClusterLink = null;
if(tPath != null){
// the last cluster gateway
HRMID tLastClusterGateway = null;
HRMID tFirstForeignGateway = null;
if(!tPath.isEmpty()){
if (DEBUG){
if (DEBUG){
Logging.log(this, " ..found inter cluster path:");
}
int i = 0;
for(AbstractRoutingGraphLink tLink : tPath){
if (DEBUG){
Logging.log(this, " ..inter-cluster step[" + i + "]: " + tLink);
}
i++;
}
}
for(AbstractRoutingGraphLink tInterClusterLink : tPath){
/*****************************************************
* Determine the current INTER-cluster route part
****************************************************/
RoutingEntry tInterClusterRoutingEntry = (RoutingEntry)tInterClusterLink.getRoute().getFirst().clone();
if(tResult != null){
if(tLastClusterGateway == null){
throw new RuntimeException(this + "::getRoutingEntryHRG() should never reach this point");
}
/************************************************************************************************
* ROUTE PART: the intra-cluster route from the last gateway to the next one if needed
***********************************************************************************************/
// the next cluster gateway
HRMID tNextClusterGateway = tInterClusterRoutingEntry.getSource();
if(!tLastClusterGateway.equals(tNextClusterGateway)){
// the intra-cluster path
List<AbstractRoutingGraphLink> tIntraClusterPath = getRouteHRG(pHRG, tLastClusterGateway, tNextClusterGateway);
if(tIntraClusterPath != null){
if(!tIntraClusterPath.isEmpty()){
RoutingEntry tLogicalIntraClusterRoutingEntry = null;
AbstractRoutingGraphLink tIntraClusterLogLink = tIntraClusterPath.get(0);
/****************************************************
* Determine the INTRA-cluster route part
****************************************************/
// check if we have only one hop in intra-cluster route
if(tIntraClusterPath.size() == 1){
// get the routing entry from the last gateway to the next one
tLogicalIntraClusterRoutingEntry = (RoutingEntry) tIntraClusterLogLink.getRoute().getFirst();
}else{
tLogicalIntraClusterRoutingEntry = RoutingEntry.create(tIntraClusterPath);
if(tLogicalIntraClusterRoutingEntry == null){
if(pRefDeletedLinks == null){
Logging.warn(this, "getRoutingEntryHRG() for " + pFrom + " found a complex intra-cluster path from " + tLastClusterGateway + " to " + tNextClusterGateway + " and wasn't able to derive an aggregated logical link from it..");
Logging.warn(this, " ..path: " + tIntraClusterPath);
Logging.warn(this, " ..from: " + tLastClusterGateway);
Logging.warn(this, " ..to: " + tNextClusterGateway);
Logging.warn(this, " ..for a routing from " + pFrom + " to " + pTo);
}else{
// no further alternative route available
}
// reset
tResult = null;
// abort
break;
}
}
/*****************************************************
* Add the intra-cluster route part
****************************************************/
if(tLogicalIntraClusterRoutingEntry != null){
// chain the routing entries
if (DEBUG){
Logging.log(this, " ..step [" + tStep + "] (intra-cluster): " + tLogicalIntraClusterRoutingEntry);
}
tResult.append(tLogicalIntraClusterRoutingEntry, pCause + "append1_intra_cluster from " + tLastClusterGateway + " to " + tNextClusterGateway);
tStep++;
/**
* Determine the next hop for the resulting path
*/
if(tFirstForeignGateway == null){
if(tLogicalIntraClusterRoutingEntry.getHopCount() > 0){
tFirstForeignGateway = tLogicalIntraClusterRoutingEntry.getNextHop();
}
}
/******************************************************
* Store the first used inter-node link (is it an intra-cluster link?)
*****************************************************/
// if(tFirstUsedInterClusterLink == null){
// tFirstUsedInterClusterLink = tIntraClusterLogLink;
// tFirstUsedInterNodeLinkHopCount = tLogicalIntraClusterRoutingEntry.getHopCount();
// }else{
// if(tFirstUsedInterNodeLinkHopCount == RoutingEntry.NO_HOP_COSTS){
// tFirstUsedInterClusterLink = tIntraClusterLogLink;
// tFirstUsedInterNodeLinkHopCount = tLogicalIntraClusterRoutingEntry.getHopCount();
// }
// }
}
}else{
if(pRefDeletedLinks != null){
// do we have a gap?
if(!tLastClusterGateway.equals(tNextClusterGateway)){
// reset
tResult = null;
// abort
break;
}else{
// actually, it is an empty path because source and destination are the same
}
}else{
Logging.warn(this, "getRoutingEntryHRG() found an empty intra-cluster path..");
Logging.warn(this, " ..from: " + tLastClusterGateway);
Logging.warn(this, " ..to: " + tNextClusterGateway);
Logging.warn(this, " ..for a routing from " + pFrom + " to " + pTo);
}
}
}else{
Logging.warn(this, "getRoutingEntryHRG() couldn't find a route from " + tLastClusterGateway + " to " + tNextClusterGateway + " for a routing from " + pFrom + " to " + pTo);
// reset
tResult = null;
// abort
break;
//HINT: do not throw a RuntimeException here because such a situation could have a temporary cause
}
}else{
// tLastClusterGateway and tNextClusterGateway are equal => empty route for cluster traversal
}
/***********************************************************************************************
* ROUTE PART: the inter-cluster link
***********************************************************************************************/
// chain the routing entries
if (DEBUG){
Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry);
}
tResult.append(tInterClusterRoutingEntry, pCause + "append2_inter_cluster for a route from " + pFrom + " to " + pTo);
}else{
/***********************************************************************************************
* ROUTE PART: first step of the resulting path
***********************************************************************************************/
if (DEBUG){
Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry);
}
tInterClusterRoutingEntry.extendCause(pCause + "append3_start_inter_cluster for a route from " + pFrom + " to " + pTo);
tResult = tInterClusterRoutingEntry;
}
tStep++;
/******************************************************
* Store the first used inter-node link (is it an inter-cluster link?)
*****************************************************/
if(tFirstUsedInterClusterLink == null){
tFirstUsedInterClusterLink = tInterClusterLink;
// tFirstUsedInterNodeLinkHopCount = tInterClusterRoutingEntry.getHopCount();
// }else{
// if(tFirstUsedInterNodeLinkHopCount == RoutingEntry.NO_HOP_COSTS){
// tFirstUsedInterClusterLink = tInterClusterLink;
// tFirstUsedInterNodeLinkHopCount = tInterClusterRoutingEntry.getHopCount();
// }
}
/******************************************************
* Store the first used gateway ("next hop")
*****************************************************/
if(tFirstForeignGateway == null){
if(tInterClusterRoutingEntry.getHopCount() > 0){
tFirstForeignGateway = tInterClusterRoutingEntry.getNextHop();
}
}
//update last cluster gateway
tLastClusterGateway = tInterClusterRoutingEntry.getNextHop();
} // for()
}else{
if(pRefDeletedLinks == null){
Logging.err(this, "getRoutingEntryHRG() found an empty inter-cluster path from " + pFrom + " to " + pTo);
}else{
// no further alternative route found
}
}
if(tResult != null){
/*******************************************************
* finalize the RESULT
******************************************************/
// set the DESTINATION for the resulting routing entry
tResult.setDest(pFrom.getForeignCluster(pTo) /* aggregate the destination here */);
// reset L2Address for next hop
tResult.setNextHopL2Address(null);
/*******************************************************
* Deactivate the first used inter-cluster link if desired
******************************************************/
if(tFirstUsedInterClusterLink != null){
if(tDeletedLinks != null){
if (DEBUG){
Logging.log(this, " ..mark as deleted: " + tFirstUsedInterClusterLink);
}
/**
* Add the first used inter-node link to the list of deleted links
*/
tDeletedLinks.add(tFirstUsedInterClusterLink);
/**
* Delete the first used inter-node link from the HRG
*/
pHRG.unlink(tFirstUsedInterClusterLink);
}
}
}
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG based inter-cluster route from " + pFrom + " to " + pTo);
}
}
return tResult;
}
/**
* Determines all routes in the HRG from a given node/cluster to another one
*
* @param pFrom the starting point
* @param pTo the ending point
* @param pCause the cause for this call
*
* @return the found routing entry
*/
public RoutingTable getAllRoutingEntriesHRG(HRMID pFrom, HRMID pTo, String pCause)
{
RoutingTable tResult = new RoutingTable();
LinkedList<AbstractRoutingGraphLink> tDeletedLinks = new LinkedList<AbstractRoutingGraphLink>();
LinkedList<LinkedList<AbstractRoutingGraphLink>> tRefDeletedLinks = new LinkedList<LinkedList<AbstractRoutingGraphLink>>();
tRefDeletedLinks.clear();
tRefDeletedLinks.add(tDeletedLinks);
boolean DEBUG = false;
// if(pFrom.getLevelAddress(1) == 5){
// DEBUG = true;
// }
if(DEBUG){
Logging.log(this, "Searching for all routing entries from " + pFrom + " to " + pTo);
}
/**************************************************
* Are the source and destination addresses equal?
**************************************************/
if(pFrom.equals(pTo)){
// create a loop route
RoutingEntry tLocalLoopEntry = RoutingEntry.createLocalhostEntry(pFrom, pCause);
// describe the cause for the route
tLocalLoopEntry.extendCause(this + "::getRoutingEntry() with same source and destination address " + pFrom);
// add the RoutingEntry to the result
tResult.add(tLocalLoopEntry);
// immediate return here
return tResult;
}
/***************************************************************************************************
* Determine all known routes, avoid repeated routes by deleting already used outgoing links from "pFrom"
***************************************************************************************************/
synchronized (mHierarchicalRoutingGraph) {
RoutingEntry tEntry = null;
int i = 0;
do{
tEntry = getRoutingEntryHRG(mHierarchicalRoutingGraph, pFrom, pTo, pCause, tRefDeletedLinks);
if(tEntry != null){
if(tEntry != null){
if(!tResult.contains(tEntry)){
if(DEBUG){
Logging.log(this, " ..found entry[" + i + "]: " + tEntry);
Logging.log(this, " ..deleted " + tDeletedLinks.size() + " links");
}
// add the RoutingEntry to the result
tResult.add(tEntry);
i++;
}else{
if(DEBUG){
Logging.log(this, " ..found repeated entry: " + tEntry);
}
}
}
}
}while(tEntry != null);
}
/**************************************************
* Add again the previously deleted HRG links
**************************************************/
if(!tDeletedLinks.isEmpty()){
for(AbstractRoutingGraphLink tLink : tDeletedLinks){
if(DEBUG){
Logging.log(this, " ..restoring HRG link: " + tLink);
}
/**
* Add all previously deleted used inter-node links again to the HRG
*/
mHierarchicalRoutingGraph.link((HRMID)tLink.getFirstVertex(), (HRMID)tLink.getSecondVertex(), tLink);
}
}
/**************************************************
* Check if we have found too long routes
**************************************************/
RoutingTable tTooLongRoutes = new RoutingTable();
for(RoutingEntry tEntry : tResult){
if(tEntry.getDest().isClusterAddress()){
if(tEntry.getHopCount() > RoutingEntry.NO_HOP_COSTS){
HRMID tDestinationCluster = tEntry.getDest();
HRMID tSourceCluster = tEntry.getDest().getForeignCluster(tEntry.getSource());
RoutingEntry tShortestEntry = getRoutingEntryHRG(tSourceCluster, tDestinationCluster, this + "::getAllRoutingEntriesHRG()");
// are the source and the destination clusters directly connected?
if(tShortestEntry.getHopCount() == RoutingEntry.NO_HOP_COSTS){
if(DEBUG){
Logging.log(this, " ..removing the too long route: " + tEntry);
}
tTooLongRoutes.add(tEntry);
}
}
}
}
// delete entries with "too long routes"
tResult.delEntries(tTooLongRoutes);
return tResult;
}
/**
* Unregisters automatically old links from the HRG based on each link's timeout value
*/
public void autoRemoveObsoleteHRGLinks()
{
synchronized (mHierarchicalRoutingGraph) {
Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getEdges();
for(AbstractRoutingGraphLink tLink : tLinks){
// does the link have a timeout?
if(tLink.getTimeout() > 0){
// timeout occurred?
if(tLink.getTimeout() < getSimulationTime()){
Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tLink);
// remove the link from the HRG
mHierarchicalRoutingGraph.unlink(tLink);
mDescriptionHRGUpdates += "\n -(AUTO_DEL) " + tEndPoints.getFirst() + " to " + tEndPoints.getSecond() + " ==> " + tLink.getRoute().getFirst() + " <== unregisterAutoHRG()";
}
}
}
}
/**
* Unregister all isolated nodes
*/
unregisterNodesAutoHRG(this + "::unregisterAutoHRG()");
}
/**
* Unregisters automatically old HRM routes based on each route entrie's timeout value
*/
private void autoRemoveObsoleteHRMRoutes()
{
RoutingTable tRoutingTable = mHierarchicalRoutingService.getRoutingTable();
for(RoutingEntry tEntry : tRoutingTable){
// does the link have a timeout?
if(tEntry.getTimeout() > 0){
// timeout occurred?
if(tEntry.getTimeout() < getSimulationTime()){
RoutingEntry tDeleteThis = tEntry.clone();
tDeleteThis.extendCause(this + "::autoRemoveObsoleteHRMRoutes()");
Logging.log(this, "Timeout (" + tEntry.getTimeout() + "<" + getSimulationTime() + ") for: " + tDeleteThis);
delHRMRoute(tDeleteThis);
}
}
}
}
/**
* Unregisters a logical link between HRMIDs from the locally stored hierarchical routing graph (HRG)
*
* @param pFrom the starting point of the link
* @param pTo the ending point of the link
* @param pRoutingEntry the routing entry of the addressed link
*
* @return if the link was found in the HRG
*/
public boolean unregisterLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "UNREGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pRoutingEntry);
}
if(!pFrom.equals(pTo)){
pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph);
AbstractRoutingGraphLink tSearchPattern = new AbstractRoutingGraphLink(new Route(pRoutingEntry));
boolean tChangedRefCounter = false;
synchronized (mHierarchicalRoutingGraph) {
//Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom));
// get all outgoing HRG links of "pFrom"
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom);
if(tOutLinks != null){
// iterate over all found links
for(AbstractRoutingGraphLink tKnownLink : tOutLinks) {
//Logging.warn(this, " ..has link: " + tKnownLink);
Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink);
if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) ||
((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){
if(tKnownLink.equals(tSearchPattern)){
//Logging.warn(this, " ..MATCH");
// if(tKnownLink.getRefCounter() == 1){
// remove the link
mHierarchicalRoutingGraph.unlink(tKnownLink);
// it's time to update the HRG-GUI
notifyHRGGUI(null);
// }else{
// if(tKnownLink.getRefCounter() < 1){
// throw new RuntimeException("Found an HRG link with an invalid ref. counter: " + tKnownLink);
// }
//
// tKnownLink.decRefCounter();
// tChangedRefCounter = true;
//
// // it's time to update the HRG-GUI
// notifyHRGGUI(tKnownLink);
// }
// // we have a positive result
tResult = true;
// work is done
break;
}else{
//Logging.warn(this, " ..NO MATCH");
}
}
}
}
}
if(!tResult){
/**
* The route was already removed -> this can occur if both end points of a link are located on this node and both of them try to unregister the same route
*/
mDescriptionHRGUpdates += "\n -/+ " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
Logging.warn(this, "Haven't found " + pRoutingEntry + " as HRG link between " + pFrom + " and " + pTo);
// if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
synchronized (mHierarchicalRoutingGraph) {
Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom);
if(tLinks != null){
if(tLinks.size() > 0){
Logging.warn(this, " ..knowing FROM node: " + pFrom);
for(AbstractRoutingGraphLink tKnownLink : tLinks){
Logging.warn(this, " ..has link: " + tKnownLink);
if(tKnownLink.equals(tSearchPattern)){
Logging.err(this, " ..MATCH");
}else{
Logging.warn(this, " ..NO MATCH");
}
}
}
}
tLinks = mHierarchicalRoutingGraph.getOutEdges(pTo);
if(tLinks != null){
if(tLinks.size() > 0){
Logging.warn(this, " ..knowing TO node: " + pFrom);
for(AbstractRoutingGraphLink tKnownLink : tLinks){
Logging.warn(this, " ..has link: " + tKnownLink);
if(tKnownLink.equals(tSearchPattern)){
Logging.err(this, " ..MATCH");
}else{
Logging.warn(this, " ..NO MATCH");
}
}
}
}
}
// }
}else{
mDescriptionHRGUpdates += "\n -" + (tChangedRefCounter ? "(REF)" : "") +" " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString() + " <== " + pRoutingEntry.getCause();
/**
* Unregister all isolated nodes
*/
unregisterNodesAutoHRG(pRoutingEntry + ", " + this + "::unregisterLinkHRG()_autoDel");
}
}else{
//Logging.warn(this, "unregisterLinkHRG() skipped because self-loop detected for: " + pRoutingEntry);
}
return tResult;
}
/**
* Unregister automatically all HRG nodes which don't have a link anymore
*/
private void unregisterNodesAutoHRG(String pCause)
{
/**
* Iterate over all nodes and delete all of them which don't have any links anymore
*/
boolean tRemovedSomething = false;
synchronized (mHierarchicalRoutingGraph) {
boolean tRemovedANode;
do{
tRemovedANode = false;
Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices();
for(HRMID tKnownNode : tNodes){
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode);
Collection<AbstractRoutingGraphLink> tInLinks = mHierarchicalRoutingGraph.getInEdges(tKnownNode);
if((tOutLinks != null) && (tInLinks != null)){
if((tInLinks.size() == 0) && (tOutLinks.size() == 0)){
// unregister the HRMID in the HRG
unregisterNodeHRG(tKnownNode, pCause);
tRemovedANode = true;
tRemovedSomething = true;
break;
}
}
}
}while(tRemovedANode);
}
if(tRemovedSomething){
// it's time to update the HRG-GUI
notifyHRGGUI(null);
}
}
/**
* Returns a list of direct neighbors of the given HRMID which are stored in the HRG
*
* @param pHRMID the root HRMID
*
* @return the list of direct neighbors
*/
public LinkedList<HRMID> getNeighborsHRG(HRMID pHRMID)
{
LinkedList<HRMID> tResult = new LinkedList<HRMID>();
synchronized (mHierarchicalRoutingGraph) {
//Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom));
// get all outgoing HRG links of "pFrom"
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pHRMID);
if(tOutLinks != null){
for(AbstractRoutingGraphLink tOutLink : tOutLinks){
HRMID tNeighbor = mHierarchicalRoutingGraph.getDest(tOutLink);
tResult.add(tNeighbor.clone());
}
}
}
return tResult;
}
/**
* Returns routes to neighbors of a given HRG node
*
* @param pHRMID the HRMID of the HRG root node
*
* @return the routing table
*/
public RoutingTable getReportRoutesToNeighborsHRG(HRMID pHRMID)
{
RoutingTable tResult = new RoutingTable();
synchronized (mHierarchicalRoutingGraph) {
//Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom));
// get all outgoing HRG links of "pFrom"
Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pHRMID);
if(tOutLinks != null){
// iterate over all found links
for(AbstractRoutingGraphLink tKnownLink : tOutLinks) {
Route tKnownLinkRoute = tKnownLink.getRoute();
if(tKnownLinkRoute.size() == 1){
if(tKnownLinkRoute.getFirst() instanceof RoutingEntry){
RoutingEntry tRouteToNeighbor = ((RoutingEntry)tKnownLinkRoute.getFirst()).clone();
tRouteToNeighbor.extendCause(this + "::getRoutesWithNeighborsHRG() for " + pHRMID);
// reset next hop L2Address
tRouteToNeighbor.setNextHopL2Address(null);
tResult.add(tRouteToNeighbor);
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route type: " + tKnownLinkRoute);
}
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route size for: " + tKnownLinkRoute);
}
}
}
Collection<AbstractRoutingGraphLink> tInLinks = mHierarchicalRoutingGraph.getInEdges(pHRMID);
if(tInLinks != null){
// iterate over all found links
for(AbstractRoutingGraphLink tKnownLink : tInLinks) {
Route tKnownLinkRoute = tKnownLink.getRoute();
if(tKnownLinkRoute.size() == 1){
if(tKnownLinkRoute.getFirst() instanceof RoutingEntry){
RoutingEntry tRouteToNeighbor = ((RoutingEntry)tKnownLinkRoute.getFirst()).clone();
tRouteToNeighbor.extendCause(this + "::getRoutesWithNeighborsHRG() for " + pHRMID);
// reset next hop L2Address
tRouteToNeighbor.setNextHopL2Address(null);
tResult.add(tRouteToNeighbor);
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route type: " + tKnownLinkRoute);
}
}else{
throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route size for: " + tKnownLinkRoute);
}
}
}
}
return tResult;
}
/**
* Registers a link between two clusters.
*
* @param pFromHRMID the start of the link
* @param pToHRMID the end of the link
* @param pRoutingEntry the routing entry for this link
*
* @return true if the link is new to the routing graph
*/
private boolean registerCluster2ClusterLinkHRG(HRMID pFromHRMID, HRMID pToHRMID, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
/**
* Store/update link in the HRG
*/
tResult = registerLinkHRG(pFromHRMID, pToHRMID, pRoutingEntry);
if(tResult){
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "Stored cluster-2-cluster link between " + pFromHRMID + " and " + pToHRMID + " in the HRG as: " + pRoutingEntry);
}
}
return tResult;
}
/**
* Unregisters a link between two clusters.
*
* @param pFromHRMID the start of the link
* @param pToHRMID the end of the link
* @param pRoutingEntry the routing entry for this link
*
* @return if the link was found in the HRG
*/
private boolean unregisterCluster2ClusterLinkHRG(HRMID pFromHRMID, HRMID pToHRMID, RoutingEntry pRoutingEntry)
{
boolean tResult = false;
/**
* Store/update link in the HRG
*/
tResult = unregisterLinkHRG(pFromHRMID, pToHRMID, pRoutingEntry);
if(tResult){
if (HRMConfig.DebugOutput.GUI_SHOW_HRG_DETECTION){
Logging.log(this, "Removed cluster-2-cluster link between " + pFromHRMID + " and " + pToHRMID + " from the HRG as: " + pRoutingEntry);
}
}
return tResult;
}
/**
* Determines a path in the locally stored hierarchical routing graph (HRG).
*
* @param pSource the source of the desired route
* @param pDestination the destination of the desired route
*
* @return the determined route, null if no route could be found
*/
public List<AbstractRoutingGraphLink> getRouteHRG(HRMID pSource, HRMID pDestination)
{
return getRouteHRG(mHierarchicalRoutingGraph, pSource, pDestination);
}
/**
* Determines a path in the locally stored hierarchical routing graph (HRG).
*
* @param pHRG the HRG which should be used
* @param pSource the source of the desired route
* @param pDestination the destination of the desired route
*
* @return the determined route, null if no route could be found
*/
public List<AbstractRoutingGraphLink> getRouteHRG(AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> pHRG, HRMID pSource, HRMID pDestination)
{
List<AbstractRoutingGraphLink> tResult = null;
if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){
Logging.log(this, "GET ROUTE (HRG) from \"" + pSource + "\" to \"" + pDestination +"\"");
}
synchronized (pHRG) {
tResult = pHRG.getRoute(pSource, pDestination);
}
if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){
Logging.log(this, " ..getRouteHRG() result: " + tResult);
}
return tResult;
}
/**
* Returns the routing entry from a HRG link between two HRG nodes (neighbors)
*
* @param pSource the starting point of the searched link
* @param pDestination the ending point of the search link
*
* @return the search routing entry
*/
public RoutingEntry getNeighborRoutingEntryHRG(HRMID pSource, HRMID pDestination)
{
RoutingEntry tResult = null;
List<AbstractRoutingGraphLink> tPath = getRouteHRG(pSource, pDestination);
if(tPath != null){
if(tPath.size() == 1){
AbstractRoutingGraphLink tLink = tPath.get(0);
// get the routing entry from the last gateway to the next one
tResult = ((RoutingEntry) tLink.getRoute().getFirst()).clone();
}else{
Logging.warn(this, "getRoutingEntryHRG() found a complex intra-cluster route: " + tPath + " from " + pSource + " to " + pDestination);
}
}else{
// no route found
}
return tResult;
}
/**
* Returns the HRG for the GraphViewer.
* (only for GUI!)
*
* @return the HRG
*/
public AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> getHRGForGraphViewer()
{
AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> tResult = null;
synchronized (mHierarchicalRoutingGraph) {
tResult = mHierarchicalRoutingGraph;
}
return tResult;
}
/**
* EVENT: probe routing
*
* @param pProbeRoutingProperty the property of the received incoming connection
*/
private void eventProbeRouting(ProbeRoutingProperty pProbeRoutingProperty)
{
/**
* We have a probe-routing connection and will print some additional information about the taken route of the connection request
*/
// get the recorded route from the property
LinkedList<HRMID> tRecordedHRMIDs = pProbeRoutingProperty.getRecordedHops();
String tDesiredDataRate = "";
if(pProbeRoutingProperty.getDesiredDataRate() >= 1000000)
tDesiredDataRate += (pProbeRoutingProperty.getDesiredDataRate() / 1000000) + " Gbit/s";
else if(pProbeRoutingProperty.getDesiredDataRate() >= 1000)
tDesiredDataRate += (pProbeRoutingProperty.getDesiredDataRate() / 1000) + " Mbit/s";
else
tDesiredDataRate += pProbeRoutingProperty.getDesiredDataRate() + " kbit/s";
String tPossibleDataRate = "";
if(pProbeRoutingProperty.getRecordedDataRate() >= 1000000)
tPossibleDataRate += (pProbeRoutingProperty.getRecordedDataRate() / 1000000) + " Gbit/s";
else if(pProbeRoutingProperty.getRecordedDataRate() >= 1000)
tPossibleDataRate += (pProbeRoutingProperty.getRecordedDataRate() / 1000) + " Mbit/s";
else
tPossibleDataRate += pProbeRoutingProperty.getRecordedDataRate() + " kbit/s";
Logging.log(this, " ..detected a probe-routing connection(source=" + pProbeRoutingProperty.getSourceDescription());
Logging.log(this, " ..source: " + tRecordedHRMIDs.getFirst());
Logging.log(this, " ..destination: " + pProbeRoutingProperty.getDest());
Logging.log(this, " ..desired E2E data rate: " + tDesiredDataRate);
Logging.log(this, " ..desired E2E delay: " + pProbeRoutingProperty.getDesiredDelay() + " ms");
Logging.log(this, " ..recorded max. E2E data rate: " + tPossibleDataRate + " (this is the worst max. avilable data rate along the taken route)");
Logging.log(this, " ..recorded min. E2E delay: " + pProbeRoutingProperty.getRecordedDelay() + " ms (this is the sum of all delays of all used links)");
Logging.log(this, " ..recorded HOP count: " + pProbeRoutingProperty.getRecordedHopCount() + " nodes (this represents the list of passed physical hosts)");
Logging.log(this, " ..passed " + tRecordedHRMIDs.size() + " HRM hops: (this represents the list of passed physical interfaces)");
// print the recorded route
int i = 0;
for(HRMID tHRMID : tRecordedHRMIDs){
if(i % 2 == 0){
Logging.log(this, " ..source[" + i + "]: " + tHRMID);
}else{
Logging.log(this, " ..hop[" + i + "]: " + tHRMID);
}
i++;
}
}
/**
* This method is derived from IServerCallback and is called for incoming connection requests by the HRMController application's ServerFN.
* Such a incoming connection can either be triggered by an HRMController application or by a probe-routing request
*
* @param pConnection the incoming connection
*/
@Override
public void newConnection(Connection pConnection)
{
Logging.log(this, "INCOMING CONNECTION " + pConnection.toString() + " with requirements: " + pConnection.getRequirements());
// get the connection requirements
Description tConnectionRequirements = pConnection.getRequirements();
/**
* check if the new connection is a probe-routing connection
*/
ProbeRoutingProperty tPropProbeRouting = (ProbeRoutingProperty) tConnectionRequirements.get(ProbeRoutingProperty.class);
// do we have a probe-routing connection?
if (tPropProbeRouting == null){
/**
* Create the communication session
*/
Logging.log(this, " ..creating communication session");
ComSession tComSession = new ComSession(this);
/**
* Start the communication session
*/
Logging.log(this, " ..starting communication session for the new connection");
tComSession.startConnection(null, pConnection);
}else{
eventProbeRouting(tPropProbeRouting);
}
}
/**
* Callback for ServerCallback: gets triggered if an error is caused by the server socket
*
* @param the error cause
*/
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.application.util.ServerCallback#error(de.tuilmenau.ics.fog.facade.events.ErrorEvent)
*/
@Override
public void error(ErrorEvent pCause)
{
Logging.log(this, "Got an error message because of \"" + pCause + "\"");
}
/**
* Creates a descriptive string about this object
*
* @return the descriptive string
*/
public String toString()
{
return "HRM controller@" + getNode();
}
/**
* Determine the name of the central FN of this node
*
* @return the name of the central FN
*/
@SuppressWarnings("deprecation")
public Name getNodeName()
{
// get the name of the central FN of this node
return getHRS().getCentralFN().getName();
}
/**
* Determine the L2 address of the central FN of this node
*
* @return the L2Address of the central FN
*/
public L2Address getNodeL2Address()
{
L2Address tResult = null;
// get the recursive FoG layer
FoGEntity tFoGLayer = (FoGEntity) getNode().getLayer(FoGEntity.class);
if(tFoGLayer != null){
// get the central FN of this node
L2Address tThisHostL2Address = getHRS().getL2AddressFor(tFoGLayer.getCentralFN());
tResult = tThisHostL2Address;
}
return tResult;
}
/**
* The global name space which is used to identify the HRM instances on nodes.
*/
public final static Namespace ROUTING_NAMESPACE = new Namespace("routing");
/**
* Stores the identification string for HRM specific routing graph decorations (coordinators & HRMIDs)
*/
private final static String DECORATION_NAME_COORDINATORS_AND_HRMIDS = "HRM(1) - coordinators & HRMIDs";
/**
* Stores the identification string for HRM specific routing graph decorations (node priorities)
*/
private final static String DECORATION_NAME_NODE_PRIORITIES = "HRM(3) - node priorities";
/**
* Stores the identification string for the active HRM infrastructure
*/
private final static String DECORATION_NAME_ACTIVE_HRM_INFRASTRUCTURE = "HRM(4) - active infrastructure";
/**
* Stores the identification string for HRM specific routing graph decorations (coordinators & clusters)
*/
private final static String DECORATION_NAME_COORDINATORS_AND_CLUSTERS = "HRM(2) - coordinators & clusters";
/**
* Stores the identification string for HRM specific routing graph decorations (NMS entries)
*/
private final static String DECORATION_NAME_NMS_ENTRIES = "HRM(5) - NMS entries";
}
| [
"[email protected]"
]
| |
dd95d717d033742a5be175bb384b8b2ce6dd3183 | 3395c15ec3e3e671b211db151dd422e89e5c995a | /jalorx-services/service-i18n/src/main/java/io/jalorx/i18n/ui/CreateResource.java | ce180113d24cc035dc25f009b746253bf36b444d | []
| no_license | wangscript007/jalorx | 15e0f4d776d58280e86be98414663b9765be1d0c | e5a6e5b5ec4cf2e7d408bdba1c50b55971c6b079 | refs/heads/main | 2023-08-10T18:03:07.898660 | 2021-09-08T00:26:15 | 2021-09-08T00:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 749 | java | package io.jalorx.i18n.ui;
import io.jalorx.boot.annotation.Operation;
import io.jalorx.boot.annotation.Resource;
import io.jalorx.boot.service.BaseService;
import io.jalorx.boot.ui.BaseCreateResource;
import io.jalorx.i18n.entity.I18N;
import io.jalorx.i18n.service.I18NService;
import io.micronaut.http.annotation.Controller;
import io.micronaut.validation.Validated;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.inject.Inject;
@Controller("/i18n")
@Resource(code = 10120, desc = "I18N Resource")
@Validated
@Operation.Create
@Tag(name = "i18n")
public class CreateResource extends BaseCreateResource<I18N> {
@Inject
I18NService service;
@Override
protected BaseService<I18N> getService() {
return service;
}
}
| [
"[email protected]"
]
| |
aad441c8fa640fc3175efec88caaf0d6e99d9080 | d0bb4811fcb112ccbd54681303de2f7fe34c19a7 | /2DGameEngine/src/com/tutorial/main/Handler.java | 7b8a73ea9d2a499fa287e33c04939294567cf3bd | []
| no_license | NolShepard/2DGameTutorial | dfc06e0387fe1064001f8e3b36d87c7a1d79e682 | 6de94e81fab1f2086f667996bafa2e6b0c0446cc | refs/heads/main | 2023-03-12T13:16:27.758020 | 2021-03-05T00:35:33 | 2021-03-05T00:35:33 | 342,726,456 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,128 | java | package com.tutorial.main;
import java.awt.Graphics;
import java.util.LinkedList;
public class Handler
{
LinkedList<GameObject> object = new LinkedList<GameObject>();
public int speed = 5;
public void tick()
{
for(int i = 0; i < object.size(); i++)
{
GameObject tempObject = object.get(i);
tempObject.tick();
}
}
public void render(Graphics g)
{
for(int i = 0; i < object.size(); i++)
{
GameObject tempObject = object.get(i);
tempObject.render(g);
}
}
public void clearEnemies()
{
for(int i = 0; i < object.size(); i++)
{
GameObject tempObject = object.get(i);
if(tempObject.getID() != ID.Player)
{
removeObject(tempObject);
i--;
}
}
}
public void clearPlayerAndEnemies()
{
for(int i = 0; i < object.size(); i++)
{
GameObject tempObject = object.get(i);
removeObject(tempObject);
i--;
}
}
public void addObject(GameObject object)
{
this.object.add(object);
}
public void removeObject(GameObject object)
{
this.object.remove(object);
}
}
| [
"[email protected]"
]
| |
bb624545328bb00f6944017a7b1d7c66121b8ba1 | 97bfeb347aef8395161120ab71cb9df698df7e29 | /B1_A2.java | 16d438e8d7a54b867ab338fd5c3df6027f4883a5 | []
| no_license | andreasthaler/netze1 | 30ca2cd904f27499b5f4dc7f5fe66d761d5422de | d97d7ff89343898c8fba57e57088c1796facad6f | refs/heads/master | 2020-03-31T09:25:47.338568 | 2018-10-08T11:25:14 | 2018-10-08T11:25:14 | 152,095,963 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,684 | java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Date;
import java.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
public class B1_A2 {
private static final String FILENAME = "filename.txt";
private static final DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
while( (line = br.readLine())!=null){
if (line.equals("")) {
writeList(list);
System.exit(0);
} else {
list.add(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getDate() {
Date date = new Date();
return sdf.format(date);
}
private static void writeList(LinkedList<String> list) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
for (int i=0; i<list.size(); i++) {
bw.write(Integer.toString(i)+" "+list.get(i)+"\n");
}
System.out.println("Zugriff aufgezeichnet am " + getDate() + "!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
} | [
"[email protected]"
]
| |
36584c3a4d69302f1d82afa22026072e97f9eba3 | f89ae97df6504ce77595c9f7eb90301291d32ed8 | /CommnonStringMethod/src/RevStrWords.java | f956c7f46e87e0dda8a7d1a8170692977e5af30e | []
| no_license | Sonny1245/dynamic-registration-form | 630a60fc79ef80ee2f60f2e1dc47be0855e37d8d | 134650cb3ab9319292d47bfabaa769fbdb5d7c9a | refs/heads/master | 2023-06-24T10:26:00.016869 | 2023-06-09T20:54:59 | 2023-06-09T20:54:59 | 364,685,552 | 1 | 0 | null | 2021-05-05T21:15:05 | 2021-05-05T19:30:12 | Java | UTF-8 | Java | false | false | 519 | java | public class RevStrWords {
public static void main(String[] args) {
String str = "Welcome To Java";
String revStr = "";
String a[] = str.split(" ");
//The samne as: String a[] = str.split("\\s");
for(String w: a) {
StringBuilder sb = new StringBuilder();
sb.append(w).reverse();
revStr += sb + " ";
}
System.out.println(revStr);
}
}
| [
"[email protected]"
]
| |
8e6004925216b1ee5bf516cb088cf6eddf144d85 | 4df578c2b3d2dfeb661106bcbb1cec8df12b0ead | /src/test/java/picocli/UnmatchedArgumentExceptionTest.java | a2a83c9c383672c19e00855045fd88e194c6310c | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Classpath-exception-2.0",
"GPL-2.0-only"
]
| permissive | remkop/picocli | 2d2555762ba6cb4d58b5f0b3112342dc8191dbd3 | 8e48885fc25424bd84232a16cfca6f60d088bc96 | refs/heads/main | 2023-09-01T20:17:15.575396 | 2023-08-28T21:51:26 | 2023-08-28T21:51:26 | 80,640,282 | 4,563 | 577 | Apache-2.0 | 2023-09-14T11:43:03 | 2017-02-01T16:38:41 | Java | UTF-8 | Java | false | false | 10,623 | java | package picocli;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.UnmatchedArgumentException;
import picocli.test.Execution;
import picocli.test.Supplier;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import static java.lang.String.format;
import static org.junit.Assert.*;
public class UnmatchedArgumentExceptionTest {
// allows tests to set any kind of properties they like, without having to individually roll them back
@Rule
public final TestRule restoreSystemProperties = new RestoreSystemProperties();
@Rule
public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");
@Command
static class Example {
}
@Test(expected = NullPointerException.class)
public void testConstructorRejectsNullList() {
new UnmatchedArgumentException(new CommandLine(new Example()), (List<String>) null);
}
@Test
public void testConstructorNonNullList() {
List<String> args = Arrays.asList("a", "b", "c");
UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(new Example()), args);
assertEquals(args, ex.getUnmatched());
assertNotSame(args, ex.getUnmatched());
}
@Test
@SuppressWarnings("deprecation")
public void testUnmatchedArgumentSuggestsOptions() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CommandLine cmd = new CommandLine(new Demo.GitCommit());
cmd.parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"-fi"});
String expected = format("" +
"Unknown option: '-fi'%n" +
"Possible solutions: --fixup, --file%n");
assertEquals(expected, baos.toString());
}
@Test
@SuppressWarnings("deprecation")
public void testUnmatchedArgumentDoesNotSuggestOptionsIfNoMatch() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CommandLine cmd = new CommandLine(new Demo.GitCommit());
cmd.parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"-x"});
String actual = baos.toString();
assertTrue(actual, actual.startsWith("Unknown option: '-x'"));
assertTrue(actual, actual.contains("Usage:"));
assertFalse(actual, actual.contains("Possible solutions:"));
}
@Test
@SuppressWarnings("deprecation")
public void testUnmatchedArgumentSuggestsSubcommands() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Demo.mainCommand().parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"chekcout"});
String expected = format("" +
"Unmatched argument at index 0: 'chekcout'%n" +
"Did you mean: git checkout or git help or git branch?%n");
assertEquals(expected, baos.toString());
}
@Test
@SuppressWarnings("deprecation")
public void testUnmatchedArgumentSuggestsSubcommands2() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Demo.mainCommand().parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"me"});
String expected = format("" +
"Unmatched argument at index 0: 'me'%n" +
"Did you mean: git merge?%n");
assertEquals(expected, baos.toString());
}
@Test
public void testPrintSuggestionsPrintStream() {
CommandLine cmd = new CommandLine(new Demo.GitCommit());
UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
UnmatchedArgumentException.printSuggestions(ex, new PrintStream(baos));
String expected = format("" +
"Possible solutions: --fixup, --file%n");
assertEquals(expected, baos.toString());
}
@Test
public void testPrintSuggestionsPrintStreamAutoFlushes() {
CommandLine cmd = new CommandLine(new Demo.GitCommit());
UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
UnmatchedArgumentException.printSuggestions(ex, new PrintStream(new BufferedOutputStream(baos)));
String expected = format("" +
"Possible solutions: --fixup, --file%n");
assertEquals(expected, baos.toString());
}
@Test
public void testPrintSuggestionsPrintWriter() {
CommandLine cmd = new CommandLine(new Demo.GitCommit());
UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
StringWriter sw = new StringWriter();
UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(sw));
String expected = format("" +
"Possible solutions: --fixup, --file%n");
assertEquals(expected, sw.toString());
}
@Test
public void testPrintSuggestionsPrintWriterAutoFlushes() {
CommandLine cmd = new CommandLine(new Demo.GitCommit());
UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
StringWriter sw = new StringWriter();
UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(new BufferedWriter(sw)));
String expected = format("" +
"Possible solutions: --fixup, --file%n");
assertEquals(expected, sw.toString());
}
@Test
public void testUnmatchedListWithNullElements() {
CommandLine cmd = new CommandLine(new Demo.GitCommit());
UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi", null));
StringWriter sw = new StringWriter();
UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(sw));
String expected = format("" +
"Possible solutions: --fixup, --file%n");
assertEquals(expected, sw.toString());
}
//https://github.com/remkop/picocli/issues/887
@Test
public void testHiddenOptionsNotSuggested() {
class MyApp {
@Option(names = "--aaa", hidden = true) int a;
@Option(names = "--apples", hidden = false) int apples;
@Option(names = "--bbb", hidden = false) int b;
}
CommandLine cmd = new CommandLine(new MyApp());
UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("--a", null));
StringWriter sw = new StringWriter();
UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(sw));
String expected = format("" +
"Possible solutions: --apples%n");
assertEquals(expected, sw.toString());
}
//https://github.com/remkop/picocli/issues/887
@Test
public void testHiddenCommandsNotSuggested() {
@Command(name="Completion", subcommands = { picocli.AutoComplete.GenerateCompletion.class } )
class CompletionSubcommandDemo implements Runnable {
public void run() { }
}
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() {
CommandLine cmd = new CommandLine(new CompletionSubcommandDemo());
CommandLine gen = cmd.getSubcommands().get("generate-completion");
gen.getCommandSpec().usageMessage().hidden(true);
return cmd;
}
};
Execution execution = Execution.builder(supplier).execute("ge");
execution.assertSystemErr("" +
"Unmatched argument at index 0: 'ge'%n" +
"Usage: Completion [COMMAND]%n");
}
@Test
public void testUnmatchedExceptionStringConstructor() {
UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), "aa");
assertNotNull(ex.getUnmatched());
assertTrue(ex.getUnmatched().isEmpty());
assertTrue(ex.getSuggestions().isEmpty());
}
@Test
public void testUnmatchedExceptionListConstructor() {
UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), new ArrayList<String>());
assertNotNull(ex.getUnmatched());
assertTrue(ex.getUnmatched().isEmpty());
assertTrue(ex.getSuggestions().isEmpty());
ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), Arrays.asList("a", "b"));
assertEquals(Arrays.asList("a", "b"), ex.getUnmatched());
}
@Test
public void testUnmatchedExceptionStackConstructor() {
UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), new Stack<String>());
assertNotNull(ex.getUnmatched());
assertTrue(ex.getUnmatched().isEmpty());
assertTrue(ex.getSuggestions().isEmpty());
Stack<String> stack = new Stack<String>();
stack.push("x");
stack.push("y");
stack.push("z");
ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), stack);
assertEquals(Arrays.asList("z", "y", "x"), ex.getUnmatched());
}
@Test
public void testUnmatchedExceptionIsUnknownOption() {
CommandLine cmd = new CommandLine(CommandLine.Model.CommandSpec.create());
assertFalse("unmatch list is null", new UnmatchedArgumentException(cmd, "").isUnknownOption());
assertFalse("unmatch list is empty", new UnmatchedArgumentException(cmd, new ArrayList<String>()).isUnknownOption());
List<String> likeAnOption = Arrays.asList("-x");
assertTrue("first unmatched resembles option", new UnmatchedArgumentException(cmd, likeAnOption).isUnknownOption());
List<String> unlikeOption = Arrays.asList("xxx");
assertFalse("first unmatched doesn't resembles option", new UnmatchedArgumentException(cmd, unlikeOption).isUnknownOption());
}
}
| [
"[email protected]"
]
| |
7d56798a037eb805ef8ec389dfe1867d7a234dde | 9d615883e48477cf9ca9b2c7ba70d73f497424ed | /src/com/company/test2017/answers/Answer_011.java | d29c9f9864afea1693512d7ac86739019e4e948c | []
| no_license | qujunyao/facetopic | 3bb89f8578233bea97b7143e5740ddabdc722777 | 079cd982969f6ebd3b015755bf40691211e015de | refs/heads/master | 2020-03-28T16:56:19.706813 | 2019-05-22T08:05:16 | 2019-05-22T08:05:16 | 148,742,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 652 | java | package com.company.test2017.answers;
import java.io.*;
public class Answer_011 {
public static void main (String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=br.readLine();
char[] ch=line.toCharArray();
int[] count =new int[128];
for(int i=0 ;i<line.length();i++){
if(ch[i]>='a'&&ch[i]<='z'||ch[i]>='A'&&ch[i]<='Z'){
count[ch[i]]++;
if(count[ch[i]]==3){
System.out.print(ch[i]);
break;
}
}
}
}
}
| [
"[email protected]"
]
| |
936c3a08c1fc3b29ca0938b5dbb4f0993097a6a4 | 9120c105e86269e7ed6414a7b4c443c411ff6588 | /Java/exercicios/src/jdbc/NovaPessoa.java | 6378891fde07b9c64e0f9f49e06151bc05d6bfb9 | []
| no_license | maikcosta/Learning | da047e35d478cd3f77ba1ee782ac8c8fb3a211ef | 0efe0b3cc04e175ce400a2e6e10d7e03cbe8b29f | refs/heads/main | 2023-05-03T13:16:15.254554 | 2023-04-19T20:58:13 | 2023-04-19T20:58:13 | 241,109,324 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 655 | java | package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class NovaPessoa {
public static void main(String[] args) throws SQLException{
Scanner entrada = new Scanner(System.in);
System.out.println("Informe o nome: ");
String nome = entrada.nextLine();
Connection conexao = FabricaConexao.getConexao();
String sql = "INSERT INTO pessoas (nome) VALUES (?)";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setString(1, nome);
stmt.execute();
System.out.println("Pessoa inserida com sucesso!");
entrada.close();
}
}
| [
"[email protected]"
]
| |
b0357180ce387a2f051a117198be031ad9da1c4a | e7ee311e20b40c87bf6d23a53a1d7b11fd29d2c3 | /src/chosun/ciis/ad/tax/rec/AD_TAX_1200_MCURLISTRecord.java | 51ba45a2e8add4a21e0a2b039e128a7b2e464ed5 | []
| no_license | nosmoon/misdevteam | 4e3695ef7bbdcd231bb84d7d8d7df54a23ff0a60 | 1829d5bd489eb6dd307ca244f0e183a31a1de773 | refs/heads/master | 2020-04-15T15:57:05.480056 | 2019-01-10T01:12:01 | 2019-01-10T01:12:01 | 164,812,547 | 1 | 0 | null | null | null | null | UHC | Java | false | false | 1,610 | java | /***************************************************************************************************
* ํ์ผ๋ช
: .java
* ๊ธฐ๋ฅ :
* ์์ฑ์ผ์ : 2009-01-29
* ์์ฑ์ : ๊นํ๊ธธ
***************************************************************************************************/
/***************************************************************************************************
* ์์ ๋ด์ญ :
* ์์ ์ :
* ์์ ์ผ์ :
* ๋ฐฑ์
:
***************************************************************************************************/
package chosun.ciis.ad.tax.rec;
/**
*
*/
public class AD_TAX_1200_MCURLISTRecord extends java.lang.Object implements java.io.Serializable{
public String cd;
public String cdnm;
public String cd_abrv_nm;
public String cdnm_cd;
public String cdabrvnm_cd;
public AD_TAX_1200_MCURLISTRecord(){}
public void setCd(String cd){
this.cd = cd;
}
public void setCdnm(String cdnm){
this.cdnm = cdnm;
}
public void setCd_abrv_nm(String cd_abrv_nm){
this.cd_abrv_nm = cd_abrv_nm;
}
public void setCdnm_cd(String cdnm_cd){
this.cdnm_cd = cdnm_cd;
}
public void setCdabrvnm_cd(String cdabrvnm_cd){
this.cdabrvnm_cd = cdabrvnm_cd;
}
public String getCd(){
return this.cd;
}
public String getCdnm(){
return this.cdnm;
}
public String getCd_abrv_nm(){
return this.cd_abrv_nm;
}
public String getCdnm_cd(){
return this.cdnm_cd;
}
public String getCdabrvnm_cd(){
return this.cdabrvnm_cd;
}
}
/* ์์ฑ์๊ฐ : Thu Mar 19 09:39:54 KST 2009 */ | [
"[email protected]"
]
| |
c48b2826b373ae3030ac8d3ea3e5d2e045640b39 | f50dba6461e393503ee8e38e7d5bd8839c975b9f | /L3_Sorting_Searching/Examples/DistanceFromOriginComparator.java | d7dc03f0cbf0934d7decfe6086c2f19226f068fb | []
| no_license | xiaoyexy/DataStructure-UCSD | 8d483e6f44468fdffa868ad5b354d72e6433906d | af9c75567829ec230109c1b43b17aaf6d5cf770d | refs/heads/master | 2023-02-01T03:54:28.160332 | 2020-12-18T07:31:06 | 2020-12-18T07:31:06 | 283,427,072 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 528 | java | // DistanceFromOriginComparator.java
package L3_Sorting_Searching.Examples;
import java.util.Comparator;
// Compare two circles using distance from origin
public class DistanceFromOriginComparator implements Comparator<Circle> {
public int compare(Circle c1, Circle c2) {
if (c1.getDistanceFromOrigin() < c2.getDistanceFromOrigin()) {
return -1;
}
if (c1.getDistanceFromOrigin() > c2.getDistanceFromOrigin()) {
return 1;
}
return 0;
}
}
| [
"[email protected]"
]
| |
b33c8e7cf07659c43f83241453a884553ef4c354 | 716d02929e938a3a916a7379c00f2514b01c9ad8 | /Princeton-Algorithm1/week3/Point.java | a38b5954dc4bb28fdeb4dac44222649f100d0453 | []
| no_license | lszhuhaichao/MOOC-Course | 902627bf073935dc55c558fda0684e184d3b7d0f | 80a0ddb04f9b00eed1f20fed635f2e36cb5090a7 | refs/heads/master | 2020-12-04T10:24:00.732229 | 2016-02-29T01:33:48 | 2016-02-29T01:33:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,406 | java | /*************************************************************************
* Name:
* Email:
*
* Compilation: javac Point.java
* Execution:
* Dependencies: StdDraw.java
*
* Description: An immutable data type for points in the plane.
*
*************************************************************************/
import java.util.Comparator;
public class Point implements Comparable<Point> {
// compare points by slope
public final Comparator<Point> SLOPE_ORDER = new SlopeOrder(); // YOUR DEFINITION HERE
private final int x; // x coordinate
private final int y; // y coordinate
// create the point (x, y)
public Point(int x, int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
// plot this point to standard drawing
public void draw() {
/* DO NOT MODIFY */
StdDraw.point(x, y);
}
// draw line between this point and that point to standard drawing
public void drawTo(Point that) {
/* DO NOT MODIFY */
StdDraw.line(this.x, this.y, that.x, that.y);
}
// slope between this point and that point
public double slopeTo(Point that) {
double res;
if(this.x == that.x && this.y == that.y) res = Double.NEGATIVE_INFINITY;
else if(this.x == that.x) res = Double.POSITIVE_INFINITY;
else if(this.y == that.y) res = +0.0;
else res = (this.y - that.y)*1.0/(this.x - that.x);
return res;
}
// is this point lexicographically smaller than that one?
// comparing y-coordinates and breaking ties by x-coordinates
public int compareTo(Point that) {
if(this.y < that.y) return -1;
if(this.y == that.y && this.x < that.x) return -1;
if(this.y == that.y && this.x == that.x) return 0;
return 1;
}
// return string representation of this point
public String toString() {
/* DO NOT MODIFY */
return "(" + x + ", " + y + ")";
}
private class SlopeOrder implements Comparator<Point>
{
public int compare(Point q1, Point q2)
{
double f1 = slopeTo(q1);
double f2 = slopeTo(q2);
if(f1 < f2) return -1;
else if(f1 == f2) return 0;
return 1;
}
}
// unit test
public static void main(String[] args) {
/* YOUR CODE HERE */
}
} | [
"[email protected]"
]
| |
e461c2646b8e735105805df1d74dc48af5a8bb29 | e5fb18465d43ce0e5ec0a94b7813959e28edf406 | /src/ch21/l.java | 40ede6f9cf82462990eeaed4031912e94fb4e87a | []
| no_license | MahmoudMabrok/Introduction | 98add3477c82cdecc8faf93aba37858af5dd8b01 | a85efaf4765c1758e06239e6770c3d7621b549be | refs/heads/master | 2021-01-20T03:56:27.416208 | 2018-03-06T05:36:04 | 2018-03-06T05:36:04 | 101,373,246 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 234 | java | package ch21;
/**
* this is
* Created by mo3tamed on 1/24/18.
*/
//gdgdfdf
public class l {
String l = " new oo " ;
public static void main(String[] args) {
System.out.println("new ll +"+" if ");
}
}
| [
"[email protected]"
]
| |
b82f314eda388bc59db0b0489332340f0ab48666 | 0d5d7951cae5bb3f21ab0a772053bbaa1d2c3874 | /OpenArms/app/src/main/java/com/example/openarms/StudentSignup.java | 289d42ead8363d6bc0f7d44042bbfa8543c2531c | [
"MIT"
]
| permissive | KianSalehi/OpenArms | c2335ed8bb7d3c3d1d6ee5b9a1094fea8ce7c1eb | 06ca362173a2c1c5c5210fc66a7ab61dbb8f26d5 | refs/heads/main | 2023-03-13T02:06:31.464724 | 2021-03-02T16:29:34 | 2021-03-02T16:29:34 | 336,423,275 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,072 | java | package com.example.openarms;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class StudentSignup extends AppCompatActivity {
private FirebaseAuth mAuth;
TextView email;
TextView pass;
TextView name;
TextView login;
Button signUp;
Map<String, Object> userInfo = new HashMap<>();
String userEmail;
String userPass;
String userName;
private final String TAG= "StudentSignup";
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_signup);
mAuth = FirebaseAuth.getInstance();
email = findViewById(R.id.studentSignupEmailInput);
pass = findViewById(R.id.studentSignupPasswordInput);
name = findViewById(R.id.studentSignupNameInput);
signUp = findViewById(R.id.studentSignUpButton);
login = findViewById(R.id.studentSignupLogin);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(StudentSignup.this, Login.class));
}
});
// On Click listener for sign up button and the sign up function for firebase
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
userEmail = email.getText().toString();
userName = name.getText().toString();
userPass = pass.getText().toString();
mAuth.createUserWithEmailAndPassword(userEmail, userPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(userName).build();
user.updateProfile(profileUpdates);
userInfo.put("Name", userName);
userInfo.put("Email", user.getEmail());
userInfo.put("ID", user.getUid());
db.collection("students").document(user.getUid())
.set(userInfo);
updateUI(user);
}
}
});
}
});
//function to signup
}
public void updateUI(FirebaseUser user){
if (user != null) {
Toast.makeText(this, "You Signed In Successfully!", Toast.LENGTH_LONG).show();
startActivity(new Intent(this, StudentMainPage.class));
}else{
Toast.makeText(this, "Something went wrong please check your email and password", Toast.LENGTH_SHORT).show();
}
}
} | [
"[email protected]"
]
| |
3d0ec848c241e5db7c607e4873019e43bc08274b | 82dfbecde34009d33db1c02d5815d1d67d0b446d | /_extend/solon.boot.undertow/src/main/java/org/noear/solon/boot/undertow/XPluginUndertowJsp.java | ba5f8e74ee46e12a5cccac4de01a117faf9613cc | [
"Apache-2.0"
]
| permissive | sun3Lu/solon | 4afa62d4b94cf735be1f77655d0d92761ac28e89 | 0bae2564c45d3546e6f61aa7a6749a42c35f79c2 | refs/heads/master | 2022-11-30T03:59:52.174826 | 2020-08-06T03:45:24 | 2020-08-06T03:45:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,046 | java | package org.noear.solon.boot.undertow;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.jsp.HackInstanceManager;
import io.undertow.jsp.JspServletBuilder;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.servlet.util.DefaultClassIntrospector;
import org.apache.jasper.deploy.JspPropertyGroup;
import org.apache.jasper.deploy.TagLibraryInfo;
import org.noear.solon.XApp;
import org.noear.solon.XUtil;
import org.noear.solon.boot.undertow.jsp.JspResourceManager;
import org.noear.solon.boot.undertow.jsp.JspTldLocator;
import org.noear.solon.core.XClassLoader;
import org.noear.solon.core.XPlugin;
import javax.servlet.MultipartConfigElement;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
/**
* @Created by: Yukai
* @Date: 2019/3/28 15:50
* @Description : Yukai is so handsome xxD
*/
public class XPluginUndertowJsp implements XPlugin {
private static Undertow.Builder serverBuilder = null;
private static Undertow _server = null;
@Override
public void start(XApp app) {
try {
setupJsp(app);
} catch (Exception e) {
e.printStackTrace();
}
_server.start();
}
public void setupJsp(XApp app) throws Exception {
final ServletContainer container = ServletContainer.Factory.newInstance();
MultipartConfigElement configElement = new MultipartConfigElement(System.getProperty("java.io.tmpdir"));
String fileRoot = getResourceRoot();
DeploymentInfo builder = new DeploymentInfo()
.setClassLoader(XPluginUndertowJsp.class.getClassLoader())
.setDeploymentName("solon")
.setContextPath("/")
.setDefaultEncoding(XServerProp.encoding_request)
.setDefaultMultipartConfig(configElement)
.setClassIntrospecter(DefaultClassIntrospector.INSTANCE);
builder.setResourceManager(new JspResourceManager(XClassLoader.global(), fileRoot))
.addServlet(JspServletBuilder.createServlet("JSPServlet", "*.jsp"))
.addServlet(new ServletInfo("ACTServlet", UtHttpHandlerJsp.class).addMapping("/")); //่ฟไธชๆๆฏๆ นๆฎไธไธๆๅฏน่ฑก`XContext`่ฟ่กๅๅ
if (XServerProp.session_timeout > 0) {
builder.setDefaultSessionTimeout(XServerProp.session_timeout);
}
HashMap<String, TagLibraryInfo> tagLibraryMap = JspTldLocator.createTldInfos("WEB-INF");
JspServletBuilder.setupDeployment(builder, new HashMap<String, JspPropertyGroup>(), tagLibraryMap, new HackInstanceManager());
DeploymentManager manager = container.addDeployment(builder);
manager.deploy();
HttpHandler jsp_handler = manager.start();
//************************** init server start******************
serverBuilder = getInstance().setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false);
serverBuilder.addHttpListener(app.port(), "0.0.0.0");
serverBuilder.setHandler(jsp_handler);
_server = serverBuilder.build();
//************************* init server end********************
}
// ๅ
่ฎธๅจๅ
ถไปไปฃ็ ๅฑ่ฎฟ้ฎๅฎนๅจๆ้ ๅจๅฎไพ
public static Undertow.Builder getInstance() {
synchronized (XPluginImp.class) {
if (serverBuilder == null) {
synchronized (XPlugin.class) {
serverBuilder = Undertow.builder();
}
}
}
return serverBuilder;
}
@Override
public void stop() throws Throwable {
if (_server != null) {
_server.stop();
_server = null;
}
}
private String getResourceRoot() throws FileNotFoundException {
URL rootURL = getRootPath();
if (rootURL == null) {
throw new FileNotFoundException("Unable to find root");
}
String resURL = rootURL.toString();
boolean isDebug = XApp.cfg().isDebugMode();
if (isDebug && (resURL.startsWith("jar:") == false)) {
int endIndex = resURL.indexOf("target");
return resURL.substring(0, endIndex) + "src/main/resources/";
}
return "";
}
private URL getRootPath() {
URL root = XUtil.getResource("/");
if (root != null) {
return root;
}
try {
String path = XUtil.getResource("").toString();
if (path.startsWith("jar:")) {
int endIndex = path.indexOf("!");
path = path.substring(0, endIndex + 1) + "/";
} else {
return null;
}
return new URL(path);
} catch (MalformedURLException e) {
return null;
}
}
}
| [
"[email protected]"
]
| |
c063982f5020d453ee075a17ad9e8bf86b5685c2 | 893e7b50e70d84747ca9c2c23c0e4c8b56142e7b | /Lab7/src/lab2/PredatoryAnimal.java | 7303826bd78c7f259ece71eedb6979e00a2bc8e5 | []
| no_license | Alexandra-Panarina/JavaLab2019 | ca9f0c88f55675dc54465429a61bde3892e3d43d | 0357c30caa457598851d22f297a295184b6052c1 | refs/heads/master | 2020-09-26T17:30:46.445286 | 2019-12-24T10:41:49 | 2019-12-24T10:41:49 | 226,302,248 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 229 | java | package lab2;
public class PredatoryAnimal extends AbstractAnimal {
PredatoryAnimal(String name, int foodCount) {
super(name, foodCount);
}
@Override
public int getFoodType() {
return 2;
}
}
| [
"[email protected]"
]
| |
1e25df8d90d442991f5322515761a83bd1dae6b4 | 88e758feeea78486a0fc695a1ab63e5c0857ca2f | /src/design_model/Abstract_Factory/demo.java | 99676d3f21091e39feae517a9f921c761c8f0f9e | []
| no_license | oupc/problem | 9dc8ac10ecb8965b0e36425a21c7ae0d924ce288 | e7167fa3ba63a49c0b0d04e8ac240fc61d3bea70 | refs/heads/master | 2021-08-19T03:29:44.428467 | 2020-03-25T09:28:10 | 2020-03-25T09:28:10 | 140,676,211 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package design_model.Abstract_Factory;
public class demo {
public static void main(String[] args) {
AbstractFactory factorycolor = new Factroy().getFactory("Color");
AbstractFactory factoryshape = new Factroy().getFactory("Shape");
}
}
| [
"[email protected]"
]
| |
4057d51d5daf316beae091318a10c533b81cfad0 | e9bfb4b252881a75062abae495e2fbf32dfb51c0 | /etheder-api/src/main/java/se/webinfostudio/game/etheder/api/model/player/CityModel.java | 474c1d45a6e4a6ba6f820a665df04c5ad24569e5 | [
"MIT"
]
| permissive | johan-hanson/etheder | e96d79a43ab4ae59252c64b9a8b817d4884802be | 8d2537950bf535a0215cbfada99588a40c765fde | refs/heads/master | 2023-08-19T11:16:11.568628 | 2023-08-15T14:58:29 | 2023-08-15T14:58:29 | 175,295,902 | 0 | 0 | MIT | 2023-08-15T14:58:31 | 2019-03-12T21:03:04 | Java | UTF-8 | Java | false | false | 1,114 | java | package se.webinfostudio.game.etheder.api.model.player;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Johan Hanson
*
*/
public class CityModel {
public static final class Builder {
private String cityId;
private String name;
private String playerId;
public CityModel build() {
final CityModel cityModel = new CityModel();
cityModel.cityId = cityId;
cityModel.name = name;
cityModel.playerId = playerId;
return cityModel;
}
public Builder withCityId(final String cityId) {
this.cityId = cityId;
return this;
}
public Builder withName(final String name) {
this.name = name;
return this;
}
public Builder withPlayerId(final String playerId) {
this.playerId = playerId;
return this;
}
}
public static Builder newBuilder() {
return new Builder();
}
@JsonProperty
private String cityId;
@JsonProperty
private String name;
@JsonProperty
private String playerId;
public String getCityId() {
return cityId;
}
public String getName() {
return name;
}
public String getPlayerId() {
return playerId;
}
}
| [
"[email protected]"
]
| |
6775e19aaa8b71ed2ac5d10828ffc51d4392a985 | d9c9ec072f81d1c13071f7648df3a2d0a2cae514 | /FoundationLevel/BinaryTrees/MaximumOfBinaryTree.java | 31474b5e900a27b36b91736d0dd664a3e218869b | []
| no_license | SakshiRastogi1302/Data-Structures-And-Algorithms | 7f0752e47172c8ed2a9103799d6f7dcc649fc511 | b6945faca1b713db7100b23ce6dfd626657a530b | refs/heads/master | 2023-06-07T06:48:28.484673 | 2021-07-02T19:31:50 | 2021-07-02T19:31:50 | 372,603,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,522 | java | package FoundationLevel.BinaryTrees;
import java.io.*;
import java.util.*;
public class MaximumOfBinaryTree {
public static class Node {
int data;
Node left;
Node right;
Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
public static class Pair {
Node node;
int state;
Pair(Node node, int state) {
this.node = node;
this.state = state;
}
}
public static Node construct(Integer[] arr) {
Node root = new Node(arr[0], null, null);
Pair rtp = new Pair(root, 1);
Stack<Pair> st = new Stack<>();
st.push(rtp);
int idx = 0;
while (st.size() > 0) {
Pair top = st.peek();
if (top.state == 1) {
idx++;
if (arr[idx] != null) {
top.node.left = new Node(arr[idx], null, null);
Pair lp = new Pair(top.node.left, 1);
st.push(lp);
} else {
top.node.left = null;
}
top.state++;
} else if (top.state == 2) {
idx++;
if (arr[idx] != null) {
top.node.right = new Node(arr[idx], null, null);
Pair rp = new Pair(top.node.right, 1);
st.push(rp);
} else {
top.node.right = null;
}
top.state++;
} else {
st.pop();
}
}
return root;
}
public static void display(Node node) {
if (node == null) {
return;
}
String str = "";
str += node.left == null ? "." : node.left.data + "";
str += " <- " + node.data + " -> ";
str += node.right == null ? "." : node.right.data + "";
System.out.println(str);
display(node.left);
display(node.right);
}
public static int max(Node node) {
// write your code here
if(node==null){
return 0;
}
int leftTreeMax=max(node.left);
int rightTreeMax=max(node.right);
return Math.max(Math.max(leftTreeMax,rightTreeMax),node.data);
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
if (values[i].equals("n") == false) {
arr[i] = Integer.parseInt(values[i]);
} else {
arr[i] = null;
}
}
Node root = construct(arr);
int max = max(root);
System.out.println(max);
}
} | [
"[email protected]"
]
| |
b759f7bbe3a48f1459b7d8b566258cb5ad5d7a9e | 202cd298430d3d0db62618ee7b944286d3cde12d | /plugins/git4idea/src/git4idea/config/GitPullSettings.java | 9dc1ce84030b6011b05d409337f214b9824daa4c | [
"Apache-2.0"
]
| permissive | llzxcv2014/intellij-community | 2e4c9fc7339d92216961262f7272c6b0bc17c4c3 | 7aedec109e6dba1393fe067171633efa30da4fda | refs/heads/master | 2021-08-06T23:08:26.280264 | 2020-09-29T08:01:22 | 2020-09-29T08:01:22 | 222,669,602 | 1 | 0 | Apache-2.0 | 2020-09-29T08:01:31 | 2019-11-19T10:27:26 | null | UTF-8 | Java | false | false | 1,674 | java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.config;
import com.google.common.collect.ImmutableSet;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import git4idea.pull.GitPullOption;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.EnumSet;
import java.util.Set;
@State(name = "Git.Pull.Settings", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public class GitPullSettings implements PersistentStateComponent<GitPullSettings.State> {
private static final EnumSet<GitPullOption> NO_OPTIONS = EnumSet.noneOf(GitPullOption.class);
private State myState = new State();
public static class State {
public Set<GitPullOption> OPTIONS = NO_OPTIONS;
public String BRANCH = null;
}
@Override
public @NotNull GitPullSettings.State getState() {
return myState;
}
@Override
public void loadState(@NotNull State state) {
myState = state;
}
public @NotNull Set<GitPullOption> getOptions() {
return ImmutableSet.copyOf(myState.OPTIONS);
}
public void setOptions(@NotNull Set<GitPullOption> options) {
myState.OPTIONS = !options.isEmpty()
? EnumSet.copyOf(options)
: NO_OPTIONS;
}
public @Nullable String getBranch() {
return myState.BRANCH;
}
public void setBranch(@Nullable String branch) {
myState.BRANCH = branch;
}
}
| [
"[email protected]"
]
| |
66ceb83cd180816185cb2323bfd11e5b6d71bd71 | 119dfb0a5b1c1ff386cf71fced86f23e229d499b | /languages/structure/source_gen/jetbrains/mps/core/structure/editor/SAbstractLink_cardinality.java | 696b257865299b60727f8370c5ba2007a1b28a5b | []
| no_license | inspirer/mps-core | 4333f50514bbf5dbb795292fa8252b1c01a12dd8 | f8d519163ac04af8d9e8e93282788a8d77c75fd8 | refs/heads/master | 2021-01-01T16:31:09.407315 | 2013-10-08T11:13:15 | 2013-10-08T11:13:15 | 3,088,063 | 2 | 0 | null | 2012-07-26T20:20:44 | 2012-01-02T15:00:29 | Java | UTF-8 | Java | false | false | 4,258 | java | package jetbrains.mps.core.structure.editor;
/*Generated by MPS */
import jetbrains.mps.openapi.editor.descriptor.ConceptEditorComponent;
import java.util.Collection;
import java.util.Collections;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import jetbrains.mps.lang.editor.cellProviders.RefNodeCellProvider;
import jetbrains.mps.smodel.IOperationContext;
import jetbrains.mps.nodeEditor.EditorManager;
public class SAbstractLink_cardinality implements ConceptEditorComponent {
public Collection<String> getContextHints() {
return Collections.emptyList();
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return this.createCollection_mwl7b3_a(editorContext, node);
}
private EditorCell createCollection_mwl7b3_a(EditorContext editorContext, SNode node) {
EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node);
editorCell.setCellId("Collection_mwl7b3_a");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
editorCell.addEditorCell(this.createConstant_mwl7b3_a0(editorContext, node));
editorCell.addEditorCell(this.createRefNode_mwl7b3_b0(editorContext, node));
editorCell.addEditorCell(this.createConstant_mwl7b3_c0(editorContext, node));
return editorCell;
}
private EditorCell createConstant_mwl7b3_a0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "[");
editorCell.setCellId("Constant_mwl7b3_a0");
Style style = new StyleImpl();
default_StyleSheet.applyPunctuation(style, editorCell);
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
style.set(StyleAttributes.PUNCTUATION_RIGHT, true);
style.set(StyleAttributes.MATCHING_LABEL, "card");
editorCell.getStyle().putAll(style);
SAbstractLink_deleteCardinality.setCellActions(editorCell, node, editorContext);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_mwl7b3_b0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new RefNodeCellProvider(node, editorContext);
provider.setRole("cardinality");
provider.setNoTargetText("<no cardinality>");
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
if (editorCell.getRole() == null) {
editorCell.setRole("cardinality");
}
SAbstractLink_deleteCardinality.setCellActions(editorCell, node, editorContext);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
Class attributeKind = provider.getRoleAttributeClass();
if (attributeConcept != null) {
IOperationContext opContext = editorContext.getOperationContext();
EditorManager manager = EditorManager.getInstanceFromContext(opContext);
return manager.createRoleAttributeCell(editorContext, attributeConcept, attributeKind, editorCell);
} else
return editorCell;
}
private EditorCell createConstant_mwl7b3_c0(EditorContext editorContext, SNode node) {
EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "]");
editorCell.setCellId("Constant_mwl7b3_c0");
Style style = new StyleImpl();
default_StyleSheet.applyPunctuation(style, editorCell);
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
style.set(StyleAttributes.MATCHING_LABEL, "card");
style.set(StyleAttributes.EDITABLE, true);
style.set(StyleAttributes.RT_ANCHOR_TAG, "ext_4_RTransform");
editorCell.getStyle().putAll(style);
SAbstractLink_deleteCardinality.setCellActions(editorCell, node, editorContext);
editorCell.setDefaultText("");
return editorCell;
}
}
| [
"[email protected]"
]
| |
f7c80ad51b97842a7fb58401829609a37b55d929 | 29f78bfb928fb6f191b08624ac81b54878b80ded | /generated_SPs_SCs/IADC/SCs/SC_command/src/main/java/SP_infantry1/input/InputDataClassName_2_4.java | d3ff7be7b2e4e455d65342d86f0ccfeeaa8f9dca | []
| no_license | MSPL4SOA/MSPL4SOA-tool | 8a78e73b4ac7123cf1815796a70f26784866f272 | 9f3419e416c600cba13968390ee89110446d80fb | refs/heads/master | 2020-04-17T17:30:27.410359 | 2018-07-27T14:18:55 | 2018-07-27T14:18:55 | 66,304,158 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,805 | java | package SP_infantry1.input;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "InputDataClassName_2_4")
public class InputDataClassName_2_4 implements Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "InputName_2_4_1")
protected Float InputName_2_4_1;
@XmlElement(name = "InputName_2_4_2")
protected Integer InputName_2_4_2;
@XmlElement(name = "InputName_2_4_3")
protected Float InputName_2_4_3;
@XmlElement(name = "InputName_2_4_4")
protected String InputName_2_4_4;
@XmlElement(name = "InputName_2_4_5")
protected Float InputName_2_4_5;
@XmlElement(name = "InputName_2_4_6")
protected String InputName_2_4_6;
public Float getInputName_2_4_1() {
return InputName_2_4_1;
}
public Integer getInputName_2_4_2() {
return InputName_2_4_2;
}
public Float getInputName_2_4_3() {
return InputName_2_4_3;
}
public String getInputName_2_4_4() {
return InputName_2_4_4;
}
public Float getInputName_2_4_5() {
return InputName_2_4_5;
}
public String getInputName_2_4_6() {
return InputName_2_4_6;
}
public void setInputName_2_4_1(Float value) {
this.InputName_2_4_1 = value;
}
public void setInputName_2_4_2(Integer value) {
this.InputName_2_4_2 = value;
}
public void setInputName_2_4_3(Float value) {
this.InputName_2_4_3 = value;
}
public void setInputName_2_4_4(String value) {
this.InputName_2_4_4 = value;
}
public void setInputName_2_4_5(Float value) {
this.InputName_2_4_5 = value;
}
public void setInputName_2_4_6(String value) {
this.InputName_2_4_6 = value;
}
}
| [
"[email protected]"
]
| |
e7d62e385c5f5464c04ec33b779be99b6c8135c5 | 28f8942f4b33cb225ff521748419d747e943b69c | /src/com/sbs/java/crud/controller/MemberController.java | af573e38fbcdc16622292a3bdd74ebead83f9024 | []
| no_license | woooyoung/2021_05_sbs_crud | a9d0ebcf6f0ab3d5baa1fd997563e94334ad4845 | f3f134326e62e5f5b44803deacc69e41349922f1 | refs/heads/master | 2023-05-09T11:05:48.075790 | 2021-05-27T06:56:44 | 2021-05-28T00:54:28 | 363,348,052 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 3,616 | java | package com.sbs.java.crud.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.sbs.java.crud.container.Container;
import com.sbs.java.crud.dto.Member;
import com.sbs.java.crud.util.Util;
public class MemberController extends Controller {
private Scanner sc;
private List<Member> members;
private String command;
private String actionMethodName;
public MemberController(Scanner sc) {
this.sc = sc;
members = Container.memberDao.members;
}
public void doAction(String command, String actionMethodName) {
this.command = command;
this.actionMethodName = actionMethodName;
switch (actionMethodName) {
case "join":
doJoin();
break;
case "login":
doLogin();
break;
case "logout":
doLogout();
break;
default:
System.out.println("์กด์ฌํ์ง ์๋ ๋ช
๋ น์ด ์
๋๋ค.");
break;
}
}
private void doLogout() {
loginedMember = null;
System.out.println("๋ก๊ทธ์์ ๋์์ต๋๋ค.");
}
private void doLogin() {
System.out.printf("๋ก๊ทธ์ธ ์์ด๋ : ");
String loginId = sc.nextLine();
System.out.printf("๋ก๊ทธ์ธ ๋น๋ฐ๋ฒํธ : ");
String loginPw = sc.nextLine();
Member member = getMemberByLoginId(loginId);
if (member == null) {
System.out.println("ํด๋น ํ์์ ์กด์ฌํ์ง ์์ต๋๋ค.");
return;
}
if (member.loginPw.equals(loginPw) == false) {
System.out.println("๋น๋ฐ๋ฒํธ๋ฅผ ํ์ธํด์ฃผ์ธ์");
return;
}
loginedMember = member;
System.out.printf("๋ก๊ทธ์ธ ๋์์ต๋๋ค. %s๋ ํ์ํฉ๋๋ค.\n", loginedMember.name);
}
private Member getMemberByLoginId(String loginId) {
int index = getMemberIndexByLoginId(loginId);
if (index == -1) {
return null;
}
return members.get(index);
}
public MemberController(Scanner sc, List<Member> members) {
this.sc = sc;
this.members = members;
}
private boolean isJoinableLoginId(String loginId) {
int index = getMemberIndexByLoginId(loginId);
if (index == -1) {
return true;
}
return false;
}
private int getMemberIndexByLoginId(String loginId) {
int i = 0;
for (Member member : members) {
if (member.loginId.equals(loginId)) {
return i;
}
i++;
}
return -1;
}
private void doJoin() {
int id = members.size() + 1;
String regDate = Util.getNowDateStr();
String loginId = null;
while (true) {
System.out.printf("๋ก๊ทธ์ธ ์์ด๋ : ");
loginId = sc.nextLine();
if (isJoinableLoginId(loginId) == false) {
System.out.printf("%s๋(์) ์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์์ด๋์
๋๋ค.\n", loginId);
continue;
}
break;
}
String loginPw = null;
String loginPwConfirm = null;
while (true) {
System.out.printf("๋ก๊ทธ์ธ ๋น๋ฐ๋ฒํธ: ");
loginPw = sc.nextLine();
System.out.println("๋ก๊ทธ์ธ ๋น๋ฐ๋ฒํธ ํ์ธ: ");
loginPwConfirm = sc.nextLine();
if (loginPw.equals(loginPwConfirm) == false) {
System.out.println("๋น๋ฐ๋ฒํธ๋ฅผ ๋ค์ ์
๋ ฅํด์ฃผ์ธ์");
continue;
}
break;
}
System.out.printf("์ด๋ฆ: ");
String name = sc.nextLine();
Member member = new Member(id, regDate, loginId, loginPw, name);
members.add(member);
System.out.printf("%d๋ฒ ํ์์ด ์์ฑ ๋์์ต๋๋ค.\n", id);
}
public void makeTestData() {
System.out.println("ํ
์คํธ๋ฅผ ์ํ ํ์ ๋ฐ์ดํฐ๋ฅผ ์์ฑํฉ๋๋ค.");
members.add(new Member(1, Util.getNowDateStr(), "admin", "admin", "๊ด๋ฆฌ์"));
members.add(new Member(2, Util.getNowDateStr(), "user1", "user1", "์ ์ 1"));
members.add(new Member(3, Util.getNowDateStr(), "user2", "user2", "์ ์ 2"));
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.