blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3ba1944dede6f4f99d48c4e84791fd8e51e9cbbd | befcad493faf7d15614ff1b081e91c17496825c6 | /jax-rs-linker-processor/src/test/resources/query_parameters_misdetection/PeopleResource.java | bd6b49bb95304c474ea84dbe11360e77e14a8277 | [
"MIT"
] | permissive | vidal-community/jax-rs-linker | 1dd465a46e7cae037bc7733299bb26ff18dac00a | 1572ca9a139b6535b4328cc73952097273354bde | refs/heads/master | 2023-04-12T09:56:36.878128 | 2022-07-25T12:39:53 | 2022-07-25T12:46:39 | 27,789,592 | 2 | 0 | MIT | 2023-02-27T11:57:46 | 2014-12-09T22:06:36 | Java | UTF-8 | Java | false | false | 1,130 | java | package query_parameters_misdetection;
import fr.vidal.oss.jax_rs_linker.api.Self;
import fr.vidal.oss.jax_rs_linker.api.SubResource;
import javax.ws.rs.*;
public class PeopleResource {
@GET
@Path("/{id}")
@Self
public Stuff searchById(@PathParam("id") Integer id) {
return null;
}
@GET
@Path("/{id}/friends")
@SubResource(value = PeopleResource.class, qualifier = "friends")
public Stuff findFriendsFilteredByCityOrCountry(@PathParam("id") Integer id,
@BeanParam Localization localization) {
return null;
}
private static class Stuff {}
private static class Localization {
private final String country;
private final String city;
public Localization(@QueryParam("pays") String country,
@QueryParam("ville") String city) {
this.country = country;
this.city = city;
}
public String getCountry() {
return country;
}
public String getCity() {
return city;
}
}
}
| [
"[email protected]"
] | |
c55094641f8e0d15d55974359b228869c0a5c96f | 8fa8cea0f936cb4061b389308ede3593ccd99a49 | /DemoController.java | bb67d4896561763d70427dbd2ec6b3475dfceef4 | [] | no_license | bimalsubedi/springBootDemo | dcee625685781f23a764deb603de56f5717b1044 | 976e8fc3b8892fb38bed81bcd9e52225a1bb7f00 | refs/heads/master | 2021-01-11T11:36:09.167752 | 2017-05-01T22:19:03 | 2017-05-01T22:19:03 | 76,897,799 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,216 | java | package com.bimal.example;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@RequestMapping("/hi")
public @ResponseBody String hiThere(){
return "This is test";
}
// @RequestMapping("/hi/{name}")
// public String useTymeleaf(Map<String, String> model, @PathVariable String name) {
// model.put("name", name);
// return "hello1";
// }
// @RequestMapping("/team")
// public Team useRESTConverter() {
// return team;
// }
@Autowired
TeamDao teamDao;
@RequestMapping("/teams")
public Iterable<Team> getTeams(){
return teamDao.findAll() ;
}
@RequestMapping("/team/{name}")
public Team getTeamByname(@PathVariable String name){
return teamDao.findByName(name) ;
}
}
| [
"[email protected]"
] | |
0e3454e511d692850f67e642f1ef84ae237a5e5e | 8d33527bcc89572589b48a08b4390629c0de1412 | /Linked List/findLoopHead/FindLoopingListHead.java | 0a85968d9dcdb40ca49ffbbee5f3473bd916910a | [] | no_license | tam0202/CrackingCoding | 45ad40d45a1ab05271144307e34f057543808b4b | 89a1704d5099b07885ff4b0dc0bd678b804d7560 | refs/heads/master | 2021-05-28T07:37:19.372925 | 2015-03-04T04:57:56 | 2015-03-04T04:57:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,465 | java | /*
* Question 2.6: Given a circular linked list, implement an algorithm which returns the
* node at the beginning of the loop
*/
package findLoopHead;
import helper.linkedlist.LinkedListLoop;
import helper.linkedlist.LinkedListNode;
public class FindLoopingListHead {
public static void main (String[] args) {
int[] data = {1, 2, 3, 4, 5, 6, 7, 8};
LinkedListLoop loopedList = new LinkedListLoop(data, 4);
loopedList.printLoopStart();
loopedList.print();
LinkedListNode node = findLoopStart(loopedList.mHead);
node.print();
}
static LinkedListNode findLoopStart (LinkedListNode head) {
LinkedListNode slowRunner = head;
LinkedListNode fastRunner = head;
// Find meeting point. This will be LOOP_SIZE - k steps into the linked list.
while (fastRunner != null && fastRunner.mNext != null) {
slowRunner = slowRunner.mNext;
fastRunner = fastRunner.mNext.mNext;
if (slowRunner == fastRunner) {
break;
}
}
// Error check - no meeting point, and therefore no loop
if (fastRunner == null || fastRunner.mNext == null) {
return null;
}
/* Move slow to Head. Keep fast at Meeting Point. Each are k
* steps from the Loop Start. If they move at the same pace,
* they must meet at Loop Start. */
slowRunner = head;
while (slowRunner != fastRunner) {
slowRunner = slowRunner.mNext;
fastRunner = fastRunner.mNext;
}
// Both now point to the start of the loop
return fastRunner;
}
}
| [
"[email protected]"
] | |
715d468d3e7a071b71aabdd9b86ee6f3cddce84d | 8936384665bdfdeb87be220bce6ccda7a0a75484 | /app/src/main/java/com/fif/iclass/me/model/MeModel.java | 08784b6d8d565bf2edd80cd302d0fae9ed2b22d1 | [] | no_license | qqchen2593598460/MVPFramework | e6f8cdb694f65fcd61456c5eda946980f827831a | ea86ddbba096be2bbc1e2d0b85fb0dee21f24cea | refs/heads/master | 2020-03-13T10:40:04.559788 | 2018-04-26T09:10:59 | 2018-04-26T09:10:59 | 131,087,931 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 587 | java | package com.fif.iclass.me.model;
import android.util.ArrayMap;
import android.widget.Toast;
import com.fif.baselib.widget.toasty.Toasty;
import com.fif.iclass.common.bean.UpdateBean;
import com.fif.iclass.common.http.NetWorkRequest;
import com.fif.iclass.common.http.NetWorkSubscriber;
import com.fif.iclass.me.contract.MeContract;
/**
* Created by
*/
public class MeModel implements MeContract.MeInterface.MeIModel {
private MeContract.MeInterface.MeIListener listener;
public MeModel(MeContract.MeInterface.MeIListener listener) {
this.listener = listener;
}
}
| [
"[email protected]"
] | |
a74543b23ab29015cb4fe2006f54b684cdc38ba7 | 563eea2b0615e9b534b8db4a61a7e1ab4ec49cf6 | /lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.java | 37b4b9ac2a2a50b9f66b76a74ee6bcaff85d32ff | [] | no_license | prabhakaran302/leetcode | a20207ba6cca87111d23ee905ce8ce6fd63b5c22 | 93c9f14b1bd1f44367eafec0941e660fff5df579 | refs/heads/main | 2023-09-03T13:45:55.432595 | 2021-11-19T06:31:49 | 2021-11-19T06:31:49 | 235,970,566 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 654 | java | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return null;
if(root == p || root == q)
return root;
TreeNode l = lowestCommonAncestor(root.left, p , q);
TreeNode r = lowestCommonAncestor(root.right, p , q);
if(l != null && r != null)
return root;
return l == null ? r : l;
}
} | [
"[email protected]"
] | |
7b083e82cd643b82c6f7b1e9da47c83f3039a2ff | 65846e42555dfd9154e34d04a1926ecc53667429 | /app/src/main/java/moodlistener/blusay/model/MoodModel.java | dd01916ece31a43af07c293093c3b50b59808d0a | [
"Apache-2.0"
] | permissive | laimich/Blusay | afd76a499d987c5ea19d0d2ec6a301b2bdb40a87 | 7a0e5fa37a035b65e26a5e8b437a49ab6ed47f0a | refs/heads/master | 2021-01-22T07:48:01.165676 | 2017-12-30T00:18:06 | 2017-12-30T00:18:06 | 92,576,722 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 439 | java | package moodlistener.blusay.model;
import moodlistener.blusay.item.*;
import java.util.ArrayList;
/**
* Created by Michelle on 6/13/2017.
*/
public class MoodModel {
//for current user
private Account currentUser;
private Mood selectedMood;
private String display; //can be "light" or "dark"
//for saved info
//private AccountUnlocked unlockedAccount;
//private ArrayList<AccountLocked> lockedAccounts;
}
| [
"[email protected]"
] | |
6ba3c24c3a0d6e484f388459687197511805ccc2 | 09d0ddd512472a10bab82c912b66cbb13113fcbf | /TestApplications/WhereYouGo-0.9.3-beta/DecompiledCode/Fernflower/src/main/java/menion/android/whereyougo/gui/extension/DataInfo.java | 84e689d15ec9fe4c097c0129d49ff3ea0525918f | [] | no_license | sgros/activity_flow_plugin | bde2de3745d95e8097c053795c9e990c829a88f4 | 9e59f8b3adacf078946990db9c58f4965a5ccb48 | refs/heads/master | 2020-06-19T02:39:13.865609 | 2019-07-08T20:17:28 | 2019-07-08T20:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,235 | java | package menion.android.whereyougo.gui.extension;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import menion.android.whereyougo.geo.location.Location;
public class DataInfo implements Comparable {
private static final String TAG = "DataInfo";
public Object addData01;
public Object addData02;
private double azimuth;
private String description;
private double distance;
public boolean enabled;
private int id;
private int image;
private Bitmap imageB;
private Drawable imageD;
private Bitmap imageRight;
private String name;
public double value01;
public double value02;
public DataInfo(int var1, String var2) {
this(var1, var2, "", -1);
}
public DataInfo(int var1, String var2, Bitmap var3) {
this(var1, var2, "", var3);
}
public DataInfo(int var1, String var2, String var3) {
this(var1, var2, var3, -1);
}
public DataInfo(int var1, String var2, String var3, int var4) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.setBasics(var1, var2, var3);
this.image = var4;
}
public DataInfo(int var1, String var2, String var3, Bitmap var4) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.setBasics(var1, var2, var3);
this.imageB = var4;
}
public DataInfo(int var1, String var2, String var3, Drawable var4) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.setBasics(var1, var2, var3);
this.imageD = var4;
}
public DataInfo(String var1) {
this(-1, var1, "", -1);
}
public DataInfo(String var1, String var2) {
this(-1, var1, var2, -1);
}
public DataInfo(String var1, String var2, int var3) {
this(-1, var1, var2, var3);
}
public DataInfo(String var1, String var2, Bitmap var3) {
this(-1, var1, var2, (Bitmap)var3);
}
public DataInfo(String var1, String var2, Drawable var3) {
this(-1, var1, var2, (Drawable)var3);
}
public DataInfo(String var1, String var2, Object var3) {
this(-1, var1, var2, -1);
this.addData01 = var3;
}
public DataInfo(DataInfo var1) {
this.enabled = true;
this.distance = -1.0D;
this.azimuth = -1.0D;
this.id = var1.id;
this.name = var1.name;
this.description = var1.description;
this.image = var1.image;
this.imageD = var1.imageD;
this.imageB = var1.imageB;
this.imageRight = var1.imageRight;
this.value01 = var1.value01;
this.value02 = var1.value02;
this.distance = var1.distance;
this.addData01 = var1.addData01;
}
private void setBasics(int var1, String var2, String var3) {
this.id = var1;
this.name = var2;
this.description = var3;
this.image = -1;
this.imageD = null;
this.imageB = null;
this.imageRight = null;
}
public void addDescription(String var1) {
if (this.description != null && this.description.length() != 0) {
this.description = this.description + ", " + var1;
} else {
this.description = var1;
}
}
public void clearDistAzi() {
this.distance = -1.0D;
}
public int compareTo(DataInfo var1) {
return this.name.compareTo(var1.getName());
}
public String getDescription() {
return this.description;
}
public int getId() {
return this.id;
}
public int getImage() {
return this.image;
}
public Bitmap getImageB() {
return this.imageB;
}
public Drawable getImageD() {
return this.imageD;
}
public Bitmap getImageRight() {
return this.imageRight;
}
public Location getLocation() {
Location var1 = new Location("DataInfo");
var1.setLatitude(this.value01);
var1.setLongitude(this.value02);
return var1;
}
public String getName() {
return this.name;
}
public boolean isDistAziSet() {
boolean var1;
if (this.distance != -1.0D) {
var1 = true;
} else {
var1 = false;
}
return var1;
}
public DataInfo setAddData01(Object var1) {
this.addData01 = var1;
return this;
}
public void setCoordinates(double var1, double var3) {
this.value01 = var1;
this.value02 = var3;
}
public void setDescription(String var1) {
this.description = var1;
}
public void setDistAzi(float var1, float var2) {
this.distance = (double)var1;
this.azimuth = (double)var2;
}
public void setDistAzi(Location var1) {
Location var2 = this.getLocation();
this.distance = (double)var1.distanceTo(var2);
this.azimuth = (double)var1.bearingTo(var2);
}
public void setId(int var1) {
this.id = var1;
}
public void setImage(int var1) {
this.image = var1;
}
public void setImage(Bitmap var1) {
this.imageB = var1;
}
public DataInfo setImageRight(Bitmap var1) {
this.imageRight = var1;
return this;
}
public void setName(String var1) {
this.name = var1;
}
public String toString() {
return this.getName();
}
}
| [
"[email protected]"
] | |
cecd28595edbccd605659d9c187d458c82c65d93 | 015fa633ea034d2be6aaa92aa3e1c663b38877e9 | /src/main/java/array/others/poisk_v_otsortirovanom_masive/ArraySearching.java | 5b739a1d2dee161934c822815bd93cd94d78addb | [] | no_license | programming-practices/java-core | b510a5104f417e670d74b94d62b6beff8d829b44 | 7680e92adc6bb9310ecc401b3768fc66b3ee66c2 | refs/heads/main | 2023-03-15T09:44:59.469839 | 2021-03-01T11:53:50 | 2021-03-01T11:53:50 | 303,077,639 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 999 | java | package array.others.poisk_v_otsortirovanom_masive;
import array.others.heneratoru_dannux.RandomGenerator;
import array.others.primenenie_heneratorov_dlya_sozdania_masivov.ConvertTo;
import array.others.primenenie_heneratorov_dlya_sozdania_masivov.Generated;
import others.entities.Generator;
import java.util.Arrays;
public class ArraySearching {
public static void main(String[] args) {
Generator<Integer> gen = new RandomGenerator.Integer(1000);
int[] a = ConvertTo.primitive(Generated.array(new Integer[25], gen));
Arrays.sort(a);
System.out.println("Sorted array: " + Arrays.toString(a));
while (true) {
int r = gen.next();
int location = Arrays.binarySearch(a, r);
if (location >= 0) {
System.out.println("Location of " + r + " is " + location +
", a[" + location + "] = " + a[location]);
break; // Out of while loop
}
}
}
}
| [
"[email protected]"
] | |
0f02fd50857d6db5ff5177d95840bcbe47595d10 | 44316c9065993113d9c3c942b8112a16d089d1e8 | /src/other/UseInterface.java | b6112e36b1931ff72af1adaf69dac78179f87d25 | [] | no_license | gjain3693/Core-Java-Concepts | 31dad3150b2fe4b24b49cf6bf753fa4f7d9ea092 | b48d3baa63a9682f75863751f6fad3ce1d3bd6d6 | refs/heads/master | 2021-07-23T12:14:34.953296 | 2017-11-03T15:18:54 | 2017-11-03T15:18:54 | 106,716,231 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package other;
public class UseInterface implements Mobile {
@Override
public void dialing() {
System.out.println("Method of Interface");
}
public void extraMethod() {
System.out.println("Method Implementer");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
UseInterface useInterface = new UseInterface();
Mobile mobile = new UseInterface();
mobile.dialing();
useInterface.dialing();
}
}
| [
"[email protected]"
] | |
7bafa068b57e3eb94967924c029ab58739dad51f | cc153bdc1238b6888d309939fc683e6d1589df80 | /commonsys/qrdplus/Extension/apps/SimContacts/src/com/android/contacts/format/FormatUtils.java | cf8a81b4ca2d34707e470e15e9f500973c028ee3 | [
"Apache-2.0"
] | permissive | ml-think-tanks/msm8996-vendor | bb9aa72dabe59a9bd9158cd7a6e350a287fa6a35 | b506122cefbe34508214e0bc6a57941a1bfbbe97 | refs/heads/master | 2022-10-21T17:39:51.458074 | 2020-06-18T08:35:56 | 2020-06-18T08:35:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,930 | java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.format;
import android.database.CharArrayBuffer;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import java.util.Arrays;
/**
* Assorted utility methods related to text formatting in Contacts.
*/
public class FormatUtils {
/**
* Finds the earliest point in buffer1 at which the first part of buffer2 matches. For example,
* overlapPoint("abcd", "cdef") == 2.
*/
public static int overlapPoint(CharArrayBuffer buffer1, CharArrayBuffer buffer2) {
if (buffer1 == null || buffer2 == null) {
return -1;
}
return overlapPoint(Arrays.copyOfRange(buffer1.data, 0, buffer1.sizeCopied),
Arrays.copyOfRange(buffer2.data, 0, buffer2.sizeCopied));
}
/**
* Finds the earliest point in string1 at which the first part of string2 matches. For example,
* overlapPoint("abcd", "cdef") == 2.
*/
public static int overlapPoint(String string1, String string2) {
if (string1 == null || string2 == null) {
return -1;
}
return overlapPoint(string1.toCharArray(), string2.toCharArray());
}
/**
* Finds the earliest point in array1 at which the first part of array2 matches. For example,
* overlapPoint("abcd", "cdef") == 2.
*/
public static int overlapPoint(char[] array1, char[] array2) {
if (array1 == null || array2 == null) {
return -1;
}
int count1 = array1.length;
int count2 = array2.length;
// Ignore matching tails of the two arrays.
while (count1 > 0 && count2 > 0 && array1[count1 - 1] == array2[count2 - 1]) {
count1--;
count2--;
}
int size = count2;
for (int i = 0; i < count1; i++) {
if (i + size > count1) {
size = count1 - i;
}
int j;
for (j = 0; j < size; j++) {
if (array1[i+j] != array2[j]) {
break;
}
}
if (j == size) {
return i;
}
}
return -1;
}
/**
* Applies the given style to a range of the input CharSequence.
* @param style The style to apply (see the style constants in {@link Typeface}).
* @param input The CharSequence to style.
* @param start Starting index of the range to style (will be clamped to be a minimum of 0).
* @param end Ending index of the range to style (will be clamped to a maximum of the input
* length).
* @param flags Bitmask for configuring behavior of the span. See {@link android.text.Spanned}.
* @return The styled CharSequence.
*/
public static CharSequence applyStyleToSpan(int style, CharSequence input, int start, int end,
int flags) {
// Enforce bounds of the char sequence.
start = Math.max(0, start);
end = Math.min(input.length(), end);
SpannableString text = new SpannableString(input);
text.setSpan(new StyleSpan(style), start, end, flags);
return text;
}
public static void copyToCharArrayBuffer(String text, CharArrayBuffer buffer) {
if (text != null) {
char[] data = buffer.data;
if (data == null || data.length < text.length()) {
buffer.data = text.toCharArray();
} else {
text.getChars(0, text.length(), data, 0);
}
buffer.sizeCopied = text.length();
} else {
buffer.sizeCopied = 0;
}
}
/** Returns a String that represents the content of the given {@link CharArrayBuffer}. */
public static String charArrayBufferToString(CharArrayBuffer buffer) {
return new String(buffer.data, 0, buffer.sizeCopied);
}
/**
* Finds the index of the first word that starts with the given prefix.
* <p>
* If not found, returns -1.
*
* @param text the text in which to search for the prefix
* @param prefix the text to find, in upper case letters
*/
public static int indexOfWordPrefix(CharSequence text, String prefix) {
if (prefix == null || text == null) {
return -1;
}
int textLength = text.length();
int prefixLength = prefix.length();
if (prefixLength == 0 || textLength < prefixLength) {
return -1;
}
int i = 0;
while (i < textLength) {
// Skip non-word characters
while (i < textLength && !Character.isLetterOrDigit(text.charAt(i))) {
i++;
}
if (i + prefixLength > textLength) {
return -1;
}
// Compare the prefixes
int j;
for (j = 0; j < prefixLength; j++) {
if (Character.toUpperCase(text.charAt(i + j)) != prefix.charAt(j)) {
break;
}
}
if (j == prefixLength) {
return i;
}
// Skip this word
while (i < textLength && Character.isLetterOrDigit(text.charAt(i))) {
i++;
}
}
return -1;
}
}
| [
"[email protected]"
] | |
94d449ef0515096de35517414292f4a9b8d11c54 | baba7ae4f32f0e680f084effcd658890183e7710 | /MutationFramework/muJava/src/mujava/cmd/MutantsGenerator.java | bfa7dbd5c6822abbe76736f4b01e80d769b28183 | [
"Apache-2.0"
] | permissive | TUBS-ISF/MutationAnalysisForDBC-FormaliSE21 | 75972c823c3c358494d2a2e9ec12e0a00e26d771 | de825bc9e743db851f5ec1c5133dca3f04d20bad | refs/heads/main | 2023-04-22T21:29:28.165271 | 2021-05-17T07:43:22 | 2021-05-17T07:43:22 | 368,096,901 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,101 | java | /**
* Copyright (C) 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 src.mujava.cmd;
import java.io.*;
import src.mujava.*;
import src.mujava.util.Debug;
/**
* <p>
* Description:
* </p>
*
* @author Jeff Offutt and Yu-Seung Ma
* @version 1.0
*
*/
public class MutantsGenerator {
static public void generateMutants(String[] file_names){
generateMutants(file_names,MutationSystem.cm_operators, MutationSystem.tm_operators);
}
static public void generateClassMutants(String[] file_names){
generateMutants(file_names,MutationSystem.cm_operators, null);
}
static public void generateClassMutants(String[] file_names, String[] class_ops){
generateMutants(file_names,class_ops, null);
}
static public void generateTraditionalMutants(String[] file_names){
generateMutants(file_names, null, MutationSystem.tm_operators);
}
static public void generateTraditionalMutants(String[] file_names,String[] traditional_ops){
generateMutants(file_names, null,traditional_ops );
}
static public void generateMutants(String[] file_names, String[] class_ops, String[] traditional_ops){
// file_names = Relative path from MutationSystem.SRC_PATH
String file_name;
for(int i=0;i<file_names.length;i++){
file_name = file_names[i];
System.out.println(file_name);
try{
System.out.println(i+" : " +file_name);
String temp = file_name.substring(0,file_name.length()-".java".length());
String class_name="";
for(int ii=0;ii<temp.length();ii++){
if( (temp.charAt(ii)=='\\') || (temp.charAt(ii)=='/') ){
class_name = class_name + ".";
}else{
class_name = class_name + temp.charAt(ii);
}
}
// Class c = Class.forName(class_name);
int class_type = MutationSystem.getClassType(class_name);
if(class_type==MutationSystem.NORMAL){
}else if(class_type==MutationSystem.MAIN){
System.out.println(" -- " + file_name+ " class contains 'static void main()' method.");
System.out.println(" Pleas note that mutants are not generated for the 'static void main()' method");
}else{
switch(class_type){
case MutationSystem.MAIN :
System.out.println(" -- Can't apply because " + file_name+ " contains only 'static void main()' method.");
break;
case MutationSystem.INTERFACE :
System.out.println(" -- Can't apply because " + file_name+ " is 'interface' ");
break;
case MutationSystem.ABSTRACT :
System.out.println(" -- Can't apply because " + file_name+ " is 'abstract' class ");
break;
case MutationSystem.APPLET :
System.out.println(" -- Can't apply because " + file_name+ " is 'applet' class ");
break;
case MutationSystem.GUI :
System.out.println(" -- Can't apply because " + file_name+ " is 'GUI' class ");
break;
}
deleteDirectory();
continue;
}
// [2] Apply mutation testing
setMutationSystemPathFor(file_name);
//File[] original_files = new File[1];
//original_files[0] = new File(MutationSystem.SRC_PATH,file_name);
File original_file = new File(MutationSystem.SRC_PATH,file_name);
AllMutantsGenerator genEngine;
Debug.setDebugLevel(3);
genEngine = new AllMutantsGenerator(original_file,class_ops,traditional_ops);
genEngine.makeMutants();
genEngine.compileMutants();
}catch(OpenJavaException oje){
System.out.println("[OJException] " + file_name + " " + oje.toString());
//System.out.println("Can't generate mutants for " +file_name + " because OpenJava " + oje.getMessage());
deleteDirectory();
}catch(Exception exp){
System.out.println("[Exception] " + file_name + " " + exp.toString());
exp.printStackTrace();
//System.out.println("Can't generate mutants for " +file_name + " due to exception" + exp.getClass().getName());
//exp.printStackTrace();
deleteDirectory();
}catch(Error er){
System.out.println("[Error] " + file_names + " " + er.toString());
//System.out.println("Can't generate mutants for " +file_name + " due to error" + er.getClass().getName());
deleteDirectory();
}
}
}
static void setMutationSystemPathFor(String file_name){
try{
String temp;
temp = file_name.substring(0,file_name.length()-".java".length());
temp = temp.replace('/','.');
temp = temp.replace('\\','.');
int separator_index = temp.lastIndexOf(".");
if(separator_index>=0){
MutationSystem.CLASS_NAME=temp.substring(separator_index+1,temp.length());
}else{
MutationSystem.CLASS_NAME = temp;
}
String mutant_dir_path = MutationSystem.MUTANT_HOME+"/"+temp;
File mutant_path = new File(mutant_dir_path);
mutant_path.mkdir();
String class_mutant_dir_path = mutant_dir_path + "/" + MutationSystem.CM_DIR_NAME;
File class_mutant_path = new File(class_mutant_dir_path);
class_mutant_path.mkdir();
String traditional_mutant_dir_path = mutant_dir_path + "/" + MutationSystem.TM_DIR_NAME;
File traditional_mutant_path = new File(traditional_mutant_dir_path);
traditional_mutant_path.mkdir();
String original_dir_path = mutant_dir_path + "/" + MutationSystem.ORIGINAL_DIR_NAME;
File original_path = new File(original_dir_path);
original_path.mkdir();
MutationSystem.CLASS_MUTANT_PATH = class_mutant_dir_path;
MutationSystem.TRADITIONAL_MUTANT_PATH = traditional_mutant_dir_path;
MutationSystem.ORIGINAL_PATH = original_dir_path;
MutationSystem.DIR_NAME = temp;
}catch(Exception e){
System.err.println(e);
}
}
static void deleteDirectory(){
File originalDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME
+ "/" + MutationSystem.ORIGINAL_DIR_NAME);
while(originalDir.delete()){
}
File cmDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME
+ "/" + MutationSystem.CM_DIR_NAME);
while(cmDir.delete()){}
File tmDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME
+ "/" + MutationSystem.TM_DIR_NAME);
while(tmDir.delete()){}
File myHomeDir = new File(MutationSystem.MUTANT_HOME+"/"+MutationSystem.DIR_NAME);
while(myHomeDir.delete()){}
}
} | [
"[email protected]"
] | |
0de9af8cf684c4f9de73e3a159da46224992c401 | 92c90af534a0aabfe99015cb101e7693f7c3d902 | /src/main/java/com/wh/test/util/SystemEnv.java | 2151f9420250404a6f73dddd82b3122040f5854f | [] | no_license | leizton/whtest | 5b5b0a7d18a8aa0ac9d5249487a3453d0e3e2c5c | 29557397a722b38b7f65ecf048cdec911e9ab667 | refs/heads/master | 2022-12-03T18:27:16.219870 | 2020-07-16T05:51:28 | 2020-07-16T05:51:28 | 131,404,466 | 0 | 0 | null | 2022-11-16T07:50:39 | 2018-04-28T11:39:59 | Java | UTF-8 | Java | false | false | 166 | java | package com.wh.test.util;
/**
* 2018/4/28
*/
public class SystemEnv {
public static String getUserHomeDir() {
return System.getProperty("user.home");
}
}
| [
"[email protected]"
] | |
73bab777aa057eef8a8148a6b3892082a74af9cf | 108ab96164053ed76ba40c3ef155269e6238da92 | /examrepo.java | 150a5976a7e436c6000d86564c97c89655743aa9 | [] | no_license | Gangie/examrepo | 26be49ddfc65f0f9ca0dfd01f49c72baf6b384b7 | b824a3d1af36bf8c10dd35fb0f62c9eb7fa85a7a | refs/heads/master | 2021-01-19T14:24:09.286540 | 2017-04-13T11:42:44 | 2017-04-13T11:42:44 | 88,158,430 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 119 | java | public class Examrepo{
public static void main(String args[]){
System.out.println("Hello There");
}
}
| [
"[email protected]"
] | |
994bc9cecd9c932f7f1385a48dabb185d538a6cb | c8621066f7d3c13d5a33c1b2c73f6c22c45c7624 | /src/Client.java | b04da9f4a9955c01d5ee82bafb137d651ea9f31c | [] | no_license | DISCoders81/DIS5 | db8a9311caac970cdb96b81bfb650ca45073fa6f | 45adc6aff3fda1d27c5e3ccfaf9f296f33042c61 | refs/heads/master | 2020-12-24T17:08:10.830631 | 2014-05-26T00:45:25 | 2014-05-26T00:45:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,200 | java | /**
* @author joantomaspape This class represents a database client. The 5
* different clients have access to disjunctive sets of pages, thus
* making the access mutually exclusive.
*/
public class Client extends Thread {
int clientId;
int minPage;
int maxPage;
Transaction currentTa;
public Client(int clientId) {
this.clientId = clientId;
this.minPage = clientId * 10;
this.maxPage = minPage + 9;
}
public void run() {
int actPage = minPage;
while (actPage <= maxPage)
{
try
{
beginTransaction();
Client.sleep(1000);
write("Erster Eintrag Für Transaction " + currentTa.getTaId(),
actPage);
actPage++;
Client.sleep(1500);
write("Zweiter Eintrag Für Transaction " + currentTa.getTaId(),
actPage);
actPage++;
Client.sleep(1200);
commit();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
private void beginTransaction() {
currentTa = PersistanceManager.getInstance().beginTransaction();
}
private void write(String data, int actPage) {
currentTa.write(actPage, data);
}
private void commit() {
PersistanceManager.getInstance().commit(currentTa);
}
}
| [
"[email protected]"
] | |
fea1ff2486afd3c81375963e9a49dd7f6bc69f46 | a9b2cf65bb01492e74715dda9c18122ad1d6b02a | /Java-Study-Tasks/src/PrimeNumbersArrayList.java | 6c76b09570fef24ecda67bd05102d2202018103a | [] | no_license | StoyanKerkelov/Java-programming-Exercises | 310e8797b251c5ddf13862ea817a0b9cf77b942d | 9c24c0b2335a69ef3646cb8e10065bda4814549d | refs/heads/master | 2021-01-01T18:20:04.651417 | 2017-07-25T13:55:09 | 2017-07-25T13:55:09 | 98,307,985 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 704 | java | import java.util.ArrayList;
public class PrimeNumbersArrayList {
//Write a method that finds all primes in set interval of numbers
public static ArrayList<Integer> getPrimes(int start, int end) {
ArrayList<Integer> primesList = new ArrayList<Integer>();
for (int num = start; num <= end; num++) {
boolean prime = true;
for (int div = 2; div <= Math.sqrt(num); div++) {
if (num % div == 0) {
prime = false;
break;
}
}
if (prime)
primesList.add(num);
}
return primesList;
}
public static void main(String[] args) {
ArrayList<Integer> primes = getPrimes(1460, 2002);
for (int p : primes) {
System.out.printf("%d ", p);
}
System.out.println();
}
}
| [
"[email protected]"
] | |
ee9e001749bfe96c7c0d5913fd9f5580c5cbac28 | 3c106005060f5e58c2a4aa8ee1f11750da86260a | /src/afi/Day13.java | a65bd17a9465ebedec0575a2ce2b44bf85e484a0 | [] | no_license | gauravmahajan25/corejava | 71d11a80e0ddd2ff2f4d39eba9d17a01fd8fcdcf | da02845a98e86078bb392de97e376d3fb7ed547f | refs/heads/master | 2020-12-31T00:17:17.571167 | 2017-03-29T08:16:21 | 2017-03-29T08:16:21 | 86,555,414 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 821 | java | package afi;
import java.util.*;
abstract class Book
{
String title;
String author;
Book(String t,String a){
title=t;
author=a;
}
abstract void display();
}
class MyBook extends Book {
int price;
MyBook(String title, String author, int price) {
super(title, author);
this.price = price;
}
void display() {
System.out.println("Title: "+this.title);
System.out.println("Author: "+this.author);
System.out.println("Price: "+this.price);
}
}
public class Day13 {
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
String title=sc.nextLine();
String author=sc.nextLine();
int price=sc.nextInt();
Book new_novel=new MyBook(title,author,price);
new_novel.display();
}
}
| [
"[email protected]"
] | |
d79900a3741b6fcd43176441e73de69aa4d05ef0 | f33cb03c64e6cc1a7ef03b5d3721ad67ac4b36d2 | /src/main/java/com/mytaxi/controller/CarController.java | 9006b97c480fdc4172e5561bf35302d773995f19 | [] | no_license | AlexandreAlberti/mytaxitest | 6fdc0be1061d77833e2491881c3843bed7757e21 | 69d4549608ebd8f25a77446e105af9a1daede4d2 | refs/heads/master | 2021-04-28T07:47:33.616920 | 2018-02-25T21:33:07 | 2018-02-25T21:33:07 | 122,232,967 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,693 | java | package com.mytaxi.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.mytaxi.controller.mapper.CarMapper;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainvalue.EngineType;
import com.mytaxi.exception.ConstraintsViolationException;
import com.mytaxi.exception.EntityNotFoundException;
import com.mytaxi.service.car.CarService;
/**
* All operations with a car will be routed by this controller.
* <p/>
*/
@RestController
@RequestMapping("v1/cars")
public class CarController
{
private final CarService carService;
@Autowired
public CarController(final CarService carService)
{
this.carService = carService;
}
@GetMapping("/{carId}")
public CarDTO getCar(@Valid @PathVariable long carId) throws EntityNotFoundException
{
return carService.findDTO(carId);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CarDTO createCar(@Valid @RequestBody CarDTO carDTO) throws ConstraintsViolationException
{
return carService.createFromDTO(carDTO);
}
@PutMapping
public CarDTO updateCar(@Valid @RequestBody CarDTO carDTO) throws ConstraintsViolationException
{
return carService.createFromDTO(carDTO);
}
@DeleteMapping("/{carId}")
public void deleteCar(@Valid @PathVariable long carId) throws EntityNotFoundException
{
carService.delete(carId);
}
@GetMapping
public List<CarDTO> findCars(
@RequestParam(required = false) Boolean convertible, @RequestParam(required = false) EngineType engineType, @RequestParam(required = false) String licensePlate, @RequestParam(
required = false) Long manufacturerId, @RequestParam(required = false) Integer seatCount) throws ConstraintsViolationException, EntityNotFoundException
{
return CarMapper.makeCarDTOList(carService.findAll(convertible, engineType, licensePlate, manufacturerId, seatCount));
}
}
| [
"[email protected]"
] | |
d7b9567266c279551116aaa2095d2a4e4a51c3eb | 0e106521124839fb6831c3d918c75d25647f9bcf | /swing-util/src/main/java/nl/fw/swing/KeyAction.java | 7d032eac5a02a3e645c7da0e4a50c5917e41b884 | [] | no_license | fwi/HVLayout | 73419eecfd5523f1c286b400e441f24c285d6c44 | b623d6102552cc0356dfc25ae607bc8ae7ab2d39 | refs/heads/master | 2020-04-05T04:26:06.033310 | 2018-02-24T15:57:41 | 2018-02-24T15:58:21 | 21,492,747 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,656 | java | /*
* This software is licensed under the GNU Lesser GPL, see
* http://www.gnu.org/licenses/ for details.
* You can use this free software in commercial and non-commercial products,
* as long as you give credit to this software when you use it.
* This softwware is provided "as is" and the use of this software is
* completely at your own risk, there are absolutely no warranties.
*
*/
package nl.fw.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
/**
* An action associated with a key that can be put into an action map so that
* an action-event is fired for the appropriate event listener
* (usually a button). When the cancel-event listener is also
* related to a keyboard action (Escape key for example) via an input map,
* a window can respond properly to a user pressing the Escape key to
* indicate he/she wants to "close the window without storing changes".
* <br> See OkCancelDialog.init() for an implementation example.
* @author Fred
*
*/
public class KeyAction extends AbstractAction {
private static final long serialVersionUID = -206322771023763629L;
public static final String KEY_ACTION = "KeyAction";
private final ActionListener keyListener;
private final ActionEvent keyEvent;
public KeyAction(Object keySource, ActionListener keyActionlistener) {
super();
keyListener = keyActionlistener;
keyEvent = new ActionEvent(keySource, ActionEvent.ACTION_PERFORMED, KEY_ACTION);
}
@Override
public void actionPerformed(ActionEvent e) {
keyListener.actionPerformed(keyEvent);
}
}
| [
"[email protected]"
] | |
aecf7af212a01e9e12ba1d726f7bb504037929d4 | 2d7c079dd101161b290f708d260adb959fbc81a1 | /src/fr/ecp/sio/shapedrawer/ui/DrawablesPanel.java | 21011b7b2a7e1ae1ff0ca4d07995046391402a3b | [] | no_license | ericdaat/ShapeDrawer | 8d26f6bc23f650262a92b1bb59f8c2cbd0505f74 | 4f7cb27414241d74fe2a8936bb3d53009c91424c | refs/heads/master | 2021-01-10T11:50:30.846504 | 2015-11-19T10:18:47 | 2015-11-19T10:18:47 | 46,444,951 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,389 | java | package fr.ecp.sio.shapedrawer.ui;
import fr.ecp.sio.shapedrawer.InvalidMetricsException;
import fr.ecp.sio.shapedrawer.model.Drawable;
import javax.swing.*;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Eric on 19/11/15.
*/
public class DrawablesPanel extends JPanel{
private Iterable<Drawable> drawables;
private static final Logger LOG = Logger.getLogger(DrawablesPanel.class.getSimpleName());
public DrawablesPanel(Iterable<Drawable> drawables){
this.drawables = drawables;
}
public void setDrawables(Iterable<Drawable> drawables){
if (this.drawables == null && drawables != null){
LOG.info("First non-null Drawable List added to our Panel");
this.drawables = drawables;
repaint();
}
}
@Override
public void paint(Graphics g){
super.paint(g);
if (this.drawables == null) return;
for (Drawable drawable : this.drawables){
try {
drawable.draw(g);
} catch (InvalidMetricsException e) {
LOG.info("Shape with no area");
} catch (Exception e){
LOG.log(
Level.SEVERE,
"Failed to draw Shape",
e
);
}
}
}
}
| [
"[email protected]"
] | |
8cf2ac6394f3c35abeb2b67e17bbae594472ba45 | de5b95b8e71772adbe5a456420879e68b0981b14 | /src/main/java/com/example/marketinnovation/exception/UnexpectedException.java | f4f6b5a72e5f211e56705dbf141573ef23668f90 | [] | no_license | paolamfz/inventory-innovation | 284b4a67965f6d62c39a24a2520a267e7d71b105 | 22d2abfd222ba66492fbf2ac449c8c42a6bc7a90 | refs/heads/master | 2023-08-05T09:55:58.756235 | 2021-09-24T03:12:05 | 2021-09-24T03:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 845 | java | /**
* @author: Edson A. Terceros T.
*/
package com.example.marketinnovation.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class UnexpectedException extends RuntimeException {
public UnexpectedException() {
super();
}
public UnexpectedException(String message) {
super(message);
}
public UnexpectedException(String message, Throwable cause) {
super(message, cause);
}
public UnexpectedException(Throwable cause) {
super(cause);
}
protected UnexpectedException(String message, Throwable cause, boolean enableSuppression, boolean
writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| [
"[email protected]"
] | |
c19ef3b5638d993d279899a9b69397ab296c46ff | bfa283d187023b37398a512a8d7c863e9b013d22 | /src/Platypus.java | 9c8ac05e7fc647aab9d5a79f8b159462d761e5a7 | [] | no_license | League-Level1-Student/old-level1-module2-NikitaD111 | 3d1572ef04deb24ef9234ae1d366f1c987a16eed | 42d4752eeac9eab2127721818c1043b470422ed7 | refs/heads/master | 2020-03-31T01:41:52.049263 | 2018-11-17T02:31:01 | 2018-11-17T02:31:01 | 151,791,574 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 207 | java |
public class Platypus {
private String name;
public Platypus(String name) {
this.name = name;
}
void sayHi(){
System.out.println("The platypus " + name + " is smarter than your average platypus.");
}
}
| [
"[email protected]"
] | |
cd99258e3b843a6acd1c6adff730293fd4e082d9 | d0697b92f898c08ab262c6f7aa5086a89b3215f6 | /Assignments/A3/davinder_Weather/app/src/main/java/com/dv/davinder_weather/models/LocationContainer.java | 7e1de5d2f25aa11e569a5220bf9b57720ec9120e | [] | no_license | shersingh7/MAP524 | dc94ec2d299a502e49d38d45982f1f9620224411 | fb622885dacf3848467620bb75d923a087ff0cd4 | refs/heads/master | 2023-06-30T22:58:19.385609 | 2021-08-10T13:35:17 | 2021-08-10T13:35:17 | 370,216,667 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 322 | java | package com.dv.davinder_weather.models;
import com.google.gson.annotations.SerializedName;
public class LocationContainer {
@SerializedName("location")
private Location location;
public Location getLocation() {return location;}
public void setWeather(Location location) {this.location = location;}
}
| [
"[email protected]"
] | |
e83ddc0a61628871cbacab88c4ddd36504562fa2 | 94adf73463b12ced810d6c5ce56ea0c273df8aa1 | /user-service/src/main/java/com/cgs/dao/ResourceDAO.java | cc2e52542204a632c8899874a939336b8ef179da | [] | no_license | duanmuhan/user | 2d15459106072756f592ca3e0da0d8217ef26316 | c976dfc111e509115c5f907fa88f712d8fb34499 | refs/heads/master | 2023-03-02T09:21:24.715511 | 2021-02-08T16:40:19 | 2021-02-08T16:40:19 | 300,297,302 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | package com.cgs.dao;
import com.cgs.po.ResourcePO;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author caoguangshu
* @date 2020/12/13
* @time 下午3:00
*/
@Repository
public interface ResourceDAO {
String TABLE_NAME = "resource_info";
String COLUMNS = "resource_id, resource_name, valid, description";
@Results( id = "resultMap",value = {
@Result(property = "resourceId",column = "resource_id"),
@Result(property = "name",column = "name"),
@Result(property = "description",column = "description"),
@Result(property = "valid",column = "valid")
})
@Insert("insert into " + TABLE_NAME + "(" + COLUMNS + ")"
+ " values (#{resource.resourceId}, #{resource.name}, #{resource.description}, #{resource.valid} )")
void addResource(@Param("resource") ResourcePO resourcePO);
@Select("select * from " + TABLE_NAME + " where valid = 1 ")
@ResultMap(value = "resultMap")
List<ResourcePO> queryAllResources();
}
| [
"[email protected]"
] | |
376a6b4d644a4dd7774000c64084b1e08e36c3cb | 21dbd3e8ebc20316fa0e33c6b55af3a9da6570b1 | /src/main/java/tms/spring/entity/AutoCase.java | a818e8fca07e102ba1f7723e13f6001b4b9cdee5 | [] | no_license | caowh/TMS | 7de2ba794f0cc88c7fd9e2e235d8cfe878f83bee | 454c73882e63dcbfa75307e5365e0f2049e81926 | refs/heads/master | 2021-01-01T04:04:25.891461 | 2018-06-28T06:12:32 | 2018-06-28T06:12:32 | 97,117,804 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,159 | java | package tms.spring.entity;
import java.util.Date;
/**
* Created by user on 2017/11/8.
*/
public class AutoCase {
private Long id;
private String case_id;
private int type;
private String describes;
private String version;
private String updateReason;
private String content;
private String writer;
private Long uploaderId;
private Date time;
private String node;
private Long tpm_id;
public Long getTpm_id() {
return tpm_id;
}
public void setTpm_id(Long tpm_id) {
this.tpm_id = tpm_id;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCase_id() {
return case_id;
}
public void setCase_id(String case_id) {
this.case_id = case_id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getDescribes() {
return describes;
}
public void setDescribes(String describes) {
this.describes = describes;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getUpdateReason() {
return updateReason;
}
public void setUpdateReason(String updateReason) {
this.updateReason = updateReason;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public Long getUploaderId() {
return uploaderId;
}
public void setUploaderId(Long uploaderId) {
this.uploaderId = uploaderId;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
| [
"[email protected]"
] | |
a6a33dc6f2a4ecd0031d74e9b9bc8afaf9723c6d | 8c7ddcdbed59ee4547121db4381519edfebc2031 | /ep-pthread-ep3/Monitor.java | a498d1f1bbf9dcc6d18149fa504f7e853a46dca7 | [] | no_license | evandrofg/EP | be0552e7a1b8611ec9156dbe1d9a74a3e4dae4e2 | a6450698fa5a098230fbf07c5cb716ce4bb41a05 | refs/heads/master | 2020-09-25T11:12:28.310762 | 2016-08-24T19:18:46 | 2016-08-24T19:18:46 | 66,492,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,247 | java | public class Monitor {
private int contents;
private int Capacidade;
private int Repeticoes;
private int Contador;
private boolean ControleProdutor;
private boolean ControleConsumidor;
private boolean full = false;
private boolean empty = true;
public Monitor(int C, int R){
this.Capacidade = C;
this.Repeticoes = R;
this.Contador = 0;
this.ControleProdutor = true;
this.ControleConsumidor = true;
}
void signal() { super.notify(); }
void signal_all() { super.notifyAll(); }
public synchronized boolean get(int who, int cont) {
if (ControleConsumidor == false) return false;
while (empty == true) {
try {
wait();
} catch (InterruptedException e) { }
}
// se nao temos mais porcoes, para
if (ControleConsumidor == false) return false;
contents--;
System.out.println("Selvagem " + who + " pegou sua porção n° " + cont + ", restam " + contents +" no prato.");
if (contents == 0){
System.out.println("Selvagem " + who + " notou o pote vazio.");
empty = true;
if (ControleProdutor == false) // ninguem vai produzir mais; sair
ControleConsumidor = false;
}
full = false;
signal_all();
return ControleConsumidor;
}
public synchronized boolean enche_prato(int who, int cont) {
if (ControleProdutor == false) return false;
while (empty == false) {
try {
wait();
} catch (InterruptedException e) { }
}
// se algum produtor ja produziu o ultimo, esse termina
if (ControleProdutor == false)
return false;
contents = Capacidade;
Contador++;
full = true;
empty = false;
System.out.println("Cozinheiro " + who + " encheu o prato pela " + cont + "ª vez.");
signal_all();
if (Contador == Repeticoes){
ControleProdutor = false;
//System.out.println("Parando após " + Contador + " repetições." );
}
return ControleProdutor;
}
}
| [
"[email protected]"
] | |
a38b43c6f955b05cfd06312f2eee83f580af9fe4 | 9e8e8f50b8095036ae20f9f4335039ddda32115b | /05_代码/01_Java程序设计上机实训/实验手册(第1-8章)源程序/ch10/part1/Contest.java | 1c1a4d4d79edb6527e4bcffb34ea3d332f6e00d3 | [] | no_license | LilWingXYZ/Java-Programming-Teaching | 47dfb26908d17c98b149f34d65343de3121a8469 | 3e4866905753a8f2743bb78987c239c541f8267a | refs/heads/main | 2023-03-08T21:17:50.203883 | 2021-02-23T12:41:23 | 2021-02-23T12:41:23 | 341,548,891 | 1 | 0 | null | null | null | null | GB18030 | Java | false | false | 952 | java | package ch10.part1;
public class Contest {
public static void main(String[] args) {
Tickets t = new Tickets(10);
new Consumer(t).start();
new Producer(t).start();
}
}
class Tickets {
int number = 0; // 票号
int size; // 总票数
boolean available = false; // 表示目前是否有票可售
public Tickets(int size) { // 构造函数,传入总票数参数
this.size = size;
}
}
class Producer extends Thread {
Tickets t = null;
public Producer(Tickets t) {
this.t = t;
}
public void run() {
while (t.number <t.size) {
System.out.println("Producer puts ticket " + (++t.number));
t.available = true;
}
}
}
class Consumer extends Thread { // 售票线程
Tickets t = null;
int i = 0;
public Consumer(Tickets t) {
this.t = t;
}
public void run() {
while (i < t.size) {
if (i<t.number)
System.out.println("Consumer buys ticket " + (++i));
if (i == t.number)
t.available = false;
}
}
}
| [
"[email protected]"
] | |
9fafa7125ccac17c562fcd24551b0aca9b15f5eb | a26dd0bab14dee68346617e4bfb57b89d3615080 | /src/main/java/co/matt/decorator/WithMilk.java | 50edd28c5e744fdb1a060ab466b17a83ee12512b | [] | no_license | skipmat/Simple-Java-Design-Patterns | 2b1b1758d23240b115a6b663e6ce0c4684f4fbde | f1b4857d44ac12136caa3c705ff915cf19d607e8 | refs/heads/master | 2021-01-23T10:19:52.326194 | 2017-06-01T10:49:11 | 2017-06-01T10:49:11 | 93,047,139 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 276 | java | package co.matt.decorator;
public class WithMilk implements Purchase{
private Purchase purchase;
Integer price = 10;
public WithMilk(Purchase purchase){
this.purchase = purchase;
}
@Override
public Integer getPrice() {
return purchase.getPrice() + price;
}
}
| [
"[email protected]"
] | |
9f35b298740215f08648253291270cb27e1637da | 68aa73a83994e7ab5f87a1362c1ad50a355d6d42 | /io7m-blueberry-test-data/src/main/java/com/io7m/blueberry/test_data/TestAssumptionFailedWithOutput.java | 4b0a4730984b90b06b887913fa7c9249ff8b9022 | [] | no_license | io7m/blueberry | 1c543e8407d904496bc4fbb8b9f2de99961bfd01 | ac8ea47d306e8a5fcb88f21b12033b2806fc051d | refs/heads/develop | 2021-01-18T23:26:35.614725 | 2018-06-04T14:31:40 | 2018-06-04T14:31:40 | 41,603,738 | 0 | 1 | null | 2017-01-05T21:45:59 | 2015-08-29T18:49:05 | Java | UTF-8 | Java | false | false | 1,380 | java | /*
* Copyright © 2014 <[email protected]> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.blueberry.test_data;
import org.junit.Assume;
import org.junit.Test;
/**
* A class containing a method with a failed assumption that produces output
* before the failure.
*
* This is test suite data and not intended for use by developers.
*/
@SuppressWarnings("static-method") public final class TestAssumptionFailedWithOutput
{
/**
* Default constructor.
*/
public TestAssumptionFailedWithOutput()
{
}
/**
* A test.
*/
@Test public void testPassOne()
{
System.out.println("Some output");
Assume.assumeTrue(false);
}
}
| [
"[email protected]"
] | |
98c4478873b1995f44dbb1b356be2526c15156f9 | e391861756f75c41cc6905dd919dea2c914e201d | /frame-parent/frame-admin/src/main/java/io/frame/modules/sys/controller/SysUserController.java | c1ac406dd458c963d9c73cec887721947b855948 | [] | no_license | liyanfu/BaseFrame | e9ca9dc5081fc74a82ec0205218b8b26025647e7 | 83b9bf1a003ae58f1c8f120d5f206ae95bde7413 | refs/heads/master | 2020-04-14T15:33:17.445437 | 2019-02-22T13:49:11 | 2019-02-22T13:49:11 | 163,930,712 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,722 | java |
package io.frame.modules.sys.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.frame.common.annotation.SysLog;
import io.frame.common.utils.PageUtils;
import io.frame.common.utils.R;
import io.frame.common.validator.Assert;
import io.frame.common.validator.ValidatorUtils;
import io.frame.common.validator.group.AddGroup;
import io.frame.common.validator.group.UpdateGroup;
import io.frame.modules.sys.entity.SysUserEntity;
import io.frame.modules.sys.service.SysUserRoleService;
import io.frame.modules.sys.service.SysUserService;
import io.frame.modules.sys.shiro.ShiroUtils;
/**
* 系统用户
*
* @author Fury
*
*
*/
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
@Autowired
private SysUserService sysUserService;
@Autowired
private SysUserRoleService sysUserRoleService;
/**
* 所有用户列表
*/
@RequestMapping("/list")
@RequiresPermissions("sys:user:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = sysUserService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 获取登录的用户信息
*/
@RequestMapping("/info")
public R info(){
return R.ok().put("user", getUser());
}
/**
* 修改登录用户密码
*/
@SysLog("修改密码")
@RequestMapping("/password")
public R password(String password, String newPassword){
Assert.isBlank(newPassword, "新密码不为能空");
//原密码
password = ShiroUtils.sha256(password, getUser().getSalt());
//新密码
newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());
//更新密码
boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
if(!flag){
return R.error("原密码不正确");
}
return R.ok();
}
/**
* 用户信息
*/
@RequestMapping("/info/{userId}")
@RequiresPermissions("sys:user:info")
public R info(@PathVariable("userId") Long userId){
SysUserEntity user = sysUserService.selectById(userId);
//获取用户所属的角色列表
List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
user.setRoleIdList(roleIdList);
return R.ok().put("user", user);
}
/**
* 保存用户
*/
@SysLog("保存用户")
@RequestMapping("/save")
@RequiresPermissions("sys:user:save")
public R save(@RequestBody SysUserEntity user){
ValidatorUtils.validateEntity(user, AddGroup.class);
sysUserService.save(user);
return R.ok();
}
/**
* 修改用户
*/
@SysLog("修改用户")
@RequestMapping("/update")
@RequiresPermissions("sys:user:update")
public R update(@RequestBody SysUserEntity user){
ValidatorUtils.validateEntity(user, UpdateGroup.class);
sysUserService.update(user);
return R.ok();
}
/**
* 删除用户
*/
@SysLog("删除用户")
@RequestMapping("/delete")
@RequiresPermissions("sys:user:delete")
public R delete(@RequestBody Long[] userIds){
if(ArrayUtils.contains(userIds, 1L)){
return R.error("系统管理员不能删除");
}
if(ArrayUtils.contains(userIds, getUserId())){
return R.error("当前用户不能删除");
}
sysUserService.deleteBatchIds(Arrays.asList(userIds));
return R.ok();
}
}
| [
"[email protected]"
] | |
d660e2b9e6e04113c9c44030fa85b51cd70f3b4d | 1f5515cf8142332a5c7e14c2a5ca81af0c839e50 | /app/src/main/java/devx/app/licensee/modules/addtrailer/TrailerByAdminAdapter.java | 936e3efe397c7baf644ea88e51e79dbe571fbc33 | [] | no_license | HoangNguyenNCC/trailer-android-licensee-master | 0466b12c0eae476bedf2fdf63d14a4b74f70db05 | a9457a96e854a9ffeadc95cc046fc9a8591a42a8 | refs/heads/master | 2023-07-12T11:18:26.532225 | 2021-08-19T07:50:18 | 2021-08-19T07:50:18 | 397,861,146 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,897 | java | package devx.app.licensee.modules.addtrailer;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import devx.app.licensee.R;
import devx.app.licensee.common.custumViews.RegularTextView;
import devx.app.seller.webapi.response.trailerslist.TrailerListResp;
import devx.app.seller.webapi.response.trailerslist.Trailers;
public class TrailerByAdminAdapter extends BaseAdapter {
List<Trailers> mList;
Context context;
private LayoutInflater mInflater;
String flag;
public TrailerByAdminAdapter(List<Trailers> mList, Context context,String flg) {
this.mList = mList;
this.context = context;
mInflater = LayoutInflater.from(context);
this.flag=flg;
}
/**
* How many items are in the data set represented by this Adapter.
*
* @return Count of items.
*/
@Override
public int getCount() {
return mList.size();
}
/**
* Get the data item associated with the specified position in the data set.
*
* @param position Position of the item whose data we want within the adapter's
* data set.
* @return The data at the specified position.
*/
@Override
public Object getItem(int position) {
return mList.get(position);
}
/**
* Get the row id associated with the specified position in the list.
*
* @param position The position of the item within the adapter's data set whose row id we want.
* @return The id of the item at the specified position.
*/
@Override
public long getItemId(int position) {
return position;
}
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
TrailerByAdminAdapter.ViewHolder holder;
if (convertView == null) {
holder = new TrailerByAdminAdapter.ViewHolder();
convertView = mInflater.inflate(R.layout.sgl_spinner_item_trailer, parent, false);
holder.text = convertView.findViewById(R.id.txt);
convertView.setTag(holder);
} else {
holder = (TrailerByAdminAdapter.ViewHolder) convertView.getTag();
}
holder.text.setText(mList.get(position).getName());
return convertView;
}
class ViewHolder {
RegularTextView text;
}
}
| [
"[email protected]"
] | |
74ea1f0c7ca891a35dcb900273c638281988d2b3 | bdaf6b25d1902b418e75411a1f2b6c52b4cd90de | /app/src/main/java/ru/maksim/sample/PlayerVisualizerView.java | 40df05b6ea3d1755cba260db266f8060af2a30d9 | [] | no_license | MaksimDmitriev/Audio-Record-Playback-Visualization | 1732eb6b3b0d64dd67554380892e07a2cd3f0daf | 75b541b125ba782fb94ce8b8dd8217b776ef0438 | refs/heads/master | 2020-03-08T08:07:17.070099 | 2018-04-04T06:04:41 | 2018-04-04T06:04:41 | 128,013,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,236 | java | package ru.maksim.sample;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by maksi on 4/4/2018.
*/
public class PlayerVisualizerView extends View {
/**
* constant value for Height of the bar
*/
public static final int VISUALIZER_HEIGHT = 28;
/**
* bytes array converted from file.
*/
private byte[] bytes;
/**
* Percentage of audio sample scale
* Should updated dynamically while audioPlayer is played
*/
private float denseness;
/**
* Canvas painting for sample scale, filling played part of audio sample
*/
private Paint playedStatePainting = new Paint();
/**
* Canvas painting for sample scale, filling not played part of audio sample
*/
private Paint notPlayedStatePainting = new Paint();
private int width;
private int height;
public PlayerVisualizerView(Context context) {
super(context);
init();
}
public PlayerVisualizerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
bytes = null;
playedStatePainting.setStrokeWidth(1f);
playedStatePainting.setAntiAlias(true);
playedStatePainting.setColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
notPlayedStatePainting.setStrokeWidth(1f);
notPlayedStatePainting.setAntiAlias(true);
notPlayedStatePainting.setColor(ContextCompat.getColor(getContext(), R.color.gray));
}
/**
* update and redraw Visualizer view
*/
public void updateVisualizer(byte[] bytes) {
this.bytes = bytes;
invalidate();
}
/**
* Update player percent. 0 - file not played, 1 - full played
*
* @param percent
*/
public void updatePlayerPercent(float percent) {
denseness = (int) Math.ceil(width * percent);
if (denseness < 0) {
denseness = 0;
} else if (denseness > width) {
denseness = width;
}
invalidate();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getMeasuredWidth();
height = getMeasuredHeight();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (bytes == null || width == 0) {
return;
}
float totalBarsCount = width / dp(3);
if (totalBarsCount <= 0.1f) {
return;
}
byte value;
int samplesCount = (bytes.length * 8 / 5);
float samplesPerBar = samplesCount / totalBarsCount;
float barCounter = 0;
int nextBarNum = 0;
int y = (height - dp(VISUALIZER_HEIGHT)) / 2;
int barNum = 0;
int lastBarNum;
int drawBarCount;
for (int a = 0; a < samplesCount; a++) {
if (a != nextBarNum) {
continue;
}
drawBarCount = 0;
lastBarNum = nextBarNum;
while (lastBarNum == nextBarNum) {
barCounter += samplesPerBar;
nextBarNum = (int) barCounter;
drawBarCount++;
}
int bitPointer = a * 5;
int byteNum = bitPointer / Byte.SIZE;
int byteBitOffset = bitPointer - byteNum * Byte.SIZE;
int currentByteCount = Byte.SIZE - byteBitOffset;
int nextByteRest = 5 - currentByteCount;
value = (byte) ((bytes[byteNum] >> byteBitOffset) & ((2 << (Math.min(5,
currentByteCount
) - 1)) - 1));
if (nextByteRest > 0) {
value <<= nextByteRest;
value |= bytes[byteNum + 1] & ((2 << (nextByteRest - 1)) - 1);
}
for (int b = 0; b < drawBarCount; b++) {
int x = barNum * dp(3);
float left = x;
float top = y + dp(VISUALIZER_HEIGHT - Math.max(1,
VISUALIZER_HEIGHT * value / 31.0f
));
float right = x + dp(2);
float bottom = y + dp(VISUALIZER_HEIGHT);
if (x < denseness && x + dp(2) < denseness) {
canvas.drawRect(left, top, right, bottom, notPlayedStatePainting);
} else {
canvas.drawRect(left, top, right, bottom, playedStatePainting);
if (x < denseness) {
canvas.drawRect(left, top, right, bottom, notPlayedStatePainting);
}
}
barNum++;
}
}
}
public int dp(float value) {
if (value == 0) {
return 0;
}
return (int) Math.ceil(getContext().getResources().getDisplayMetrics().density * value);
}
} | [
"[email protected]"
] | |
68da28e032c480bc1cf86b4c4f47bd59f21fde0c | 61ad0457045ada19f7447c22ede845fc1f1720a6 | /FaceDrawProgram/src/AnsariFaceDraw.java | dadc293dee67f25c0403165b80658ca5bedfaf20 | [] | no_license | shazilansari/MyProjects | 0bfa6cfbc5fa75e20b89e18405ade11e3658f1c3 | 0918a553fad857bb6a8a76ddade60059ffee74e5 | refs/heads/master | 2020-09-28T09:38:13.691959 | 2019-12-09T00:37:02 | 2019-12-09T00:37:02 | 224,691,979 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,907 | java | /**
* FaceDraw: This program draws three different variations of faces utlizing different colors.
* The smile types, colors, and sizes of the faces are all random.
*
* @author: Shazil Ansari - 02/24/19
*
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.ArrayList;
import java.util.Random;
// This is the face model class
class Face {
// These are the data members within the face class
// Data members to hold both angles for the creation of the arch
private int smileTypeLeft;
private int smileTypeRight;
// Data member to hold color type
private Color color;
// Data members to hold size of different parts of face
private int width;
private int height;
// Data members to control location of different parts of face
private int x;
private int y;
// get and set functions for all data members
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int w) {
if (width < 0) {
width = 0;
}else {
width = w;
}
}
public int getHeight() {
return height;
}
public void setHeight(int h) {
if (height < 0) {
height = 0;
}else {
height = h;
}
}
public int getSmileTypeLeft() {
return smileTypeLeft;
}
public void setSmileTypeLeft(int smileTypeLeft) {
this.smileTypeLeft = smileTypeLeft;
}
public int getSmileTypeRight() {
return smileTypeRight;
}
public void setSmileTypeRight(int smileTypeRight) {
this.smileTypeRight = smileTypeRight;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
// constructor
public Face(int x, int y, int r) {
setX(x);
setY(y);
}
// constructor
public Face(int x, int y, int w, int h, int stl, int str, Color c) {
setX(x);
setY(y);
setWidth(w);
setHeight(h);
setSmileTypeLeft(stl);
setSmileTypeRight(str);
setColor(c);
}
// toString function
public String toString() {
return String.format("x=%d, y=%d, w=%d, h=%d, stl=%d, str=%d, color=",x,y,width,height,smileTypeLeft,smileTypeRight, color);
}
}
/**
The FaceFactory class builds Face objects.
The only function we'll put here for now is createRandomShapes.
To create random Shapes, ShapeFactory will need a random number generator.
To create random numbers, use the java.util.Random class.
*/
class FaceFactory {
private Random rnd; // this will generate random numbers to help control building the Faces
public FaceFactory() {
rnd = new Random(); // at this point, ShapeFactory has a random number generator
}
/**
This function returns an ArrayList<Face> faces - specifically, howMany of them.
They will be randomly generated.
*/
public ArrayList<Face> generateRandomShapes(int howMany) {
ArrayList<Face> result = new ArrayList<Face>();
int x,y,w,h,stl = 0, str = 0;
Color c = null;
int type; // either 0 for Smile, or 1 for Frown, or 2 for in-between face
for (int i = 0; i < howMany; i++) { // the user wanted howMany shapes, so let's build them
x = 0 + rnd.nextInt(130); // x will lie between 0 and 130
y = 0 + rnd.nextInt(130); // y will lie between 0 and 130
w = 100 + rnd.nextInt(110); // w will lie between 100 and 110
h = 120 + rnd.nextInt(130); // h will lie between 120 and 130
type = rnd.nextInt(3); // either 0,1, oe 2 will be generated
// set Arch size for smile, frown, or meh face and color of faces based on random generation
if (type == 0) {
stl = 0;
str = 180;
c = Color.RED;
} else if (type == 1){
stl = 0;
str = -180;
c = Color.BLUE;
}
else {
stl = 25;
str = 140;
c= Color.GREEN;
}
result.add(new Face(x,y,w,h,stl,str,c)); // add a brand new circle to the result list
}
return result;
}
}
class FacePanel extends JPanel{
// passed list from FaceFrame in order to draw
private ArrayList<Face> faces;
public FacePanel(ArrayList<Face> faces) {
this.faces = faces;
}
public void paintComponent(Graphics g) {
super.paintComponents(g); // background and any other things inside this panel get drawn
for (int i = 0; i < faces.size(); i++) {
// Drawing face objects where they are suppose to be and how they are suppose to look
g.setColor(faces.get(i).getColor());
g.drawOval(faces.get(i).getX(), faces.get(i).getY(), faces.get(i).getWidth(), faces.get(i).getHeight());
g.drawOval(faces.get(i).getX() + faces.get(i).getWidth() * 4/16, faces.get(i).getY() + faces.get(i).getHeight() * 3/16, faces.get(i).getWidth() / 5, faces.get(i).getHeight() / 5);
g.drawOval(faces.get(i).getX() + faces.get(i).getWidth() * 9/16, faces.get(i).getY() + faces.get(i).getHeight() * 3/16, faces.get(i).getWidth() / 5, faces.get(i).getHeight() / 5);
g.drawArc(faces.get(i).getX() + faces.get(i).getWidth() * 4/16 , faces.get(i).getY() + faces.get(i).getHeight() * 9/16, faces.get(i).getWidth() / 2, faces.get(i).getHeight() / 4, faces.get(i).getSmileTypeLeft(), faces.get(i).getSmileTypeRight());
}
}
}
class FaceFrame extends JFrame {
public void setupUI(ArrayList<Face> faces) {
// Formatting the UI window
setTitle("Displays random faces");
// Operating to close UI window
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Layout of UI window
setBounds(200, 800, 500, 500);
// Container for lightweight objects
Container c = getContentPane();
// Creation of border layout
c.setLayout(new BorderLayout());
// JPanel descendant objkect of type FacePanel that is used to hold FaceObjects
FacePanel cpan = new FacePanel(faces);
// adding FacePanel object to border layout
c.add(cpan,BorderLayout.CENTER);
}
// FaceObject passed to the list
public FaceFrame(ArrayList<Face> faces) {
setupUI(faces);
}
}
public class AnsariFaceDraw {
// Main function
public static void main(String[] args) {
//Create and randomly populate a list of face objects using face factory
FaceFactory sf = new FaceFactory();
// List in which objects are randomly populated
ArrayList<Face> faces = sf.generateRandomShapes(4);
// Creation of faceFrame object
FaceFrame ff = new FaceFrame(faces);
// Visible when program is run
ff.setVisible(true);
}
}
| [
"[email protected]"
] | |
a8e9d2601baee0c5e1696192de7be401f72fb6c7 | 1df45cb1958ba27eb9e08e59185bca2be98537b2 | /src/com/example/rest_a/model/service/RestService.java | 2a3680ca4e30353ffdb4f314b8d74402111222a9 | [] | no_license | elpy/rest_a | 7100f8473ac3eaee9038d11881c56e70e9d76c6a | 8c2539ea9a4d138a5f7ed5956c2520dd3ca19eda | refs/heads/master | 2021-01-18T11:29:31.711536 | 2013-04-13T18:40:38 | 2013-04-13T18:40:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 478 | java | package com.example.rest_a.model.service;
import com.example.rest_a.model.RequestFactory;
import com.example.rest_a.model.operations.TweetsOperation;
import com.foxykeep.datadroid.service.RequestService;
public class RestService extends RequestService {
@Override
public Operation getOperationForType(int requestType) {
switch (requestType) {
case RequestFactory.REQUEST_TWEETS:
return new TweetsOperation();
default:
return null;
}
}
}
| [
"[email protected]"
] | |
a515a4c1823c7a1a8c283cb6a008f12ec2365d5c | 09d11101f1b90ed3a2c5185f626bc766e8555000 | /src/day03/Children.java | 83d74c4752828f7c3e561ea0272abe536301dcb5 | [] | no_license | rrmqa/NewRepo2 | 7f9ac4554c0ec4a1c5d55755954e2c839507988f | cc2e88f68679009ddf3f32d540e855ce9aec87a4 | refs/heads/master | 2022-12-21T21:50:29.721984 | 2020-09-24T04:01:17 | 2020-09-24T04:01:17 | 290,591,753 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 980 | java | package day03;
public class Children {
public static void main(StringPractice[] args) {
Blueprint child1 = new Blueprint();
child1.setInfo("Ali", 3);
System.out.println(child1);
child1.gift();
System.out.println("=======================================");
Blueprint child2 = new Blueprint();
child2.setInfo("Dilshod", 6);
System.out.println(child2);
System.out.println("=======================================");
Blueprint child3 = new Blueprint();
child3.setInfo("Kamol", 10);
System.out.println(child3);
child3.gift();
System.out.println("=======================================");
Blueprint child4 = new Blueprint();
child4.setInfo("Muhtar", 1);
System.out.println(child4);
System.out.println("=======================================");
Blueprint child5 = new Blueprint();
System.out.println(child5);
}
}
| [
"[email protected]"
] | |
00bb89e37daaff300885247c05ca7828bd53326e | db08d5f745fd3f2ccc253e1ad23210bb17a10760 | /open-bidder-master/open-bidder-http/src/main/java/com/google/openbidder/http/cookie/CookieOrBuilder.java | 9d907d59851026c2f68e1f9f3f43ddff44f69415 | [
"Apache-2.0"
] | permissive | Essens/openbidder | ade2b73152dcca0ddedab9fba46ec9c2f04d94a0 | 59f724fe6e3dd969934b77ff5b059c97dc7d1d9c | refs/heads/Initial | 2021-01-22T01:42:40.351068 | 2015-08-30T06:15:46 | 2015-08-30T06:15:46 | 49,961,489 | 10 | 8 | null | 2016-01-19T15:20:14 | 2016-01-19T15:20:13 | null | UTF-8 | Java | false | false | 1,067 | java | /*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.openbidder.http.cookie;
import javax.annotation.Nullable;
/**
* Operations shared between {@link com.google.openbidder.http.Cookie}
* and {@link com.google.openbidder.http.Cookie.Builder}.
*/
public interface CookieOrBuilder {
String getName();
String getValue();
@Nullable String getDomain();
@Nullable String getPath();
boolean isSecure();
@Nullable String getComment();
int getMaxAge();
int getVersion();
}
| [
"[email protected]"
] | |
9852e71f8433d65eb883ce5c5ef7aa184717f6de | e9cefd4737fd99c4eeb7f97b2ef3f8eced2163cb | /GoogleMapsApp/app/src/main/java/com/romellbolton/googlemapsapp/MapsActivity.java | b8a17ae1ab098cffb09dfd0a2503d3caadd7359d | [] | no_license | rrbolton423/ECEN-485-App-Development-for-Android-Devices | ad9e2f42475dc95133c7d4f7fe23931de151a1fe | 4cd9a8897731ae0641705326cbc1cc4bd523512f | refs/heads/master | 2021-05-12T10:08:52.823284 | 2018-05-02T19:30:56 | 2018-05-02T19:30:56 | 117,346,278 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,360 | java | package com.romellbolton.googlemapsapp;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
// Have MapActivity extend FragmentActivity and implement the OnMapReadyCallback interface
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
// Define an instance of GoogleMap
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Use the MapFragment's getMapAsync() method to get notified when the map fragment
// is ready to be used.
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Chicago, Illinois.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
// Instantiate a GoogleMap
mMap = googleMap;
// Create a LatLang object, specifying the coordinates of Chicago, IL
LatLng chicago = new LatLng(41.850033, - 87.6500523);
// Add a marker in Chicago using the LatLang object and
// set the title of the marker to "Marker in Chicago"
mMap.addMarker(new MarkerOptions().position(chicago).title("Marker in Chicago"));
// Move the camera to the location of the LatLang object, i.e. Chicago
mMap.moveCamera(CameraUpdateFactory.newLatLng(chicago));
}
}
| [
"user.email"
] | user.email |
eda270db0314b3f91f13722d1248a5ecc8e94488 | e5d46719e29e6679069845af71102a824241c081 | /app/src/main/java/com/example/testbutton2/MainActivity.java | 689e43cac5b40aa0a3136859eaa8b354c3f5fa5c | [] | no_license | IamTouma/TestButton2 | a5f5f0ab5f280cdaf977ab51c5d55ebea774fd97 | d4a3eb25f4067a9080fc4838d577da417b1bf144 | refs/heads/master | 2020-03-12T12:33:45.960494 | 2018-04-23T00:50:45 | 2018-04-23T00:50:45 | 130,621,081 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,646 | java | package com.example.testbutton2;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// private TextView textView;
// private boolean flag = false;
// private Button button;
// private LinearLayout.LayoutParams buttonLayoutParams;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//// setContentView(R.layout.activity_main);
//
// // リニアレイアウトの設定
// LinearLayout layout = new LinearLayout(this);
// layout.setOrientation(LinearLayout.VERTICAL);
//
// layout.setLayoutParams(new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.MATCH_PARENT,
// LinearLayout.LayoutParams.MATCH_PARENT));
//
// // レイアウト中央寄せ
// layout.setGravity(Gravity.CENTER);
// setContentView(layout);
//
// // テキスト設定
// textView = new TextView(this);
// textView.setText("Hello");
// // テキストサイズ 30sp
// textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
// // テキストカラー
// textView.setTextColor(Color.rgb(0x0, 0x0, 0x0));
//
// LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.WRAP_CONTENT,
// LinearLayout.LayoutParams.WRAP_CONTENT);
//
// textView.setLayoutParams(textLayoutParams);
// layout.addView(textView);
//
// // ボタンの設定
// button = new Button(this);
// button.setText("Button");
// // dp単位を取得
// float scale = getResources().getDisplayMetrics().density;
// // 横幅 150dp, 縦 100dp に設定
// buttonLayoutParams = new LinearLayout.LayoutParams(
//// LinearLayout.LayoutParams.WRAP_CONTENT,
// (int)(150 * scale),
// LinearLayout.LayoutParams.WRAP_CONTENT);
// // マージン 20dp に設定
// int margins = (int)(20 * scale);
// buttonLayoutParams.setMargins(margins, margins, margins, margins);
//
// button.setLayoutParams(buttonLayoutParams);
// layout.addView(button);
//
// // リスナーをボタンに登録
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// // flagがtrueの時
// if (flag) {
// textView.setText("Hello");
// flag = false;
// }
// // flagがfalseの時
// else {
// textView.setText("World");
// flag = true;
//
// // いわゆるdipの代わり
// float scale = getResources().getDisplayMetrics().density;
// int buttonWidth = (int)(250 * scale);
// int buttonHeight = (int)(100 * scale);
// // 横幅 250dp に設定
// buttonLayoutParams = new LinearLayout.LayoutParams(
// buttonWidth, buttonHeight);
// int margins = (int)(20 * scale);
// // setMargins (int left, int top, int right, int bottom)
// buttonLayoutParams.setMargins((int) (5 * scale), (int)(50 * scale),
// (int)(50 * scale), (int)(20 * scale));
// button.setLayoutParams(buttonLayoutParams);
//
// }
// }
// });
// }
private RelativeLayout layout;
private RelativeLayout.LayoutParams buttonLayoutParams;
private RelativeLayout.LayoutParams textLayoutParams;
private TextView textView;
private Button button;
private int buttonWidth;
private int buttonHeight;
private float scale;
private boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// リラティブレイアウトの設定
layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
layout.setBackgroundColor(Color.rgb(220,255,240));
setContentView(layout);
// dp 設定
scale = getResources().getDisplayMetrics().density;
// テキスト設定
textView = new TextView(this);
textView.setText("Hello");
// テキストサイズ 30sp
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
// テキストカラー
textView.setTextColor(Color.rgb(0x0, 0x0, 0xff));
textLayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// setMargins (int left, int top, int right, int bottom)
textLayoutParams.setMargins((int)(150*scale), (int)(300*scale), 0, 0);
textView.setLayoutParams(textLayoutParams);
layout.addView(textView);
// ボタンの設定
button = new Button(this);
button.setText("Button");
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
// ボタンサイズ
buttonWidth = (int)(200 * scale);
buttonHeight = (int)(100 * scale);
buttonLayoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
// button margin : left, top, right, bottom
buttonLayoutParams.setMargins((int)(105*scale), (int)(360*scale), 0, 0);
button.setLayoutParams(buttonLayoutParams);
layout.addView(button);
// リスナーをボタンに登録
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// flagがtrueの時
if (flag) {
textView.setText("Hello");
buttonWidth = (int)(250 * scale);
buttonHeight = (int)(100 * scale);
buttonLayoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
// setMargins (int left, int top, int right, int bottom)
buttonLayoutParams.setMargins((int)(150*scale), (int)(360*scale), 0, 0);
button.setLayoutParams(buttonLayoutParams);
flag = false;
}
// flagがfalseの時
else {
textView.setText("World");
buttonWidth = (int)(250 * scale);
buttonHeight = (int)(100 * scale);
buttonLayoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
// setMargins (int left, int top, int right, int bottom)
buttonLayoutParams.setMargins((int) (5 * scale), (int)(50 * scale),
(int)(50 * scale), (int)(20 * scale));
button.setLayoutParams(buttonLayoutParams);
flag = true;
}
}
});
}
}
| [
"[email protected]"
] | |
5867322c0ab3d52cb4939cba8aa407359ded911b | 14c8213abe7223fe64ff89a47f70b0396e623933 | /javassist/util/proxy/ProxyFactory$3.java | 92cb63caa87996c65c1a950b8861c3b4bc516fc7 | [
"MIT"
] | permissive | PolitePeoplePlan/backdoored | c804327a0c2ac5fe3fbfff272ca5afcb97c36e53 | 3928ac16a21662e4f044db9f054d509222a8400e | refs/heads/main | 2023-05-31T04:19:55.497741 | 2021-06-23T15:20:03 | 2021-06-23T15:20:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 440 | java | package javassist.util.proxy;
import java.util.*;
static final class ProxyFactory$3 implements Comparator {
ProxyFactory$3() {
super();
}
@Override
public int compare(final Object a1, final Object a2) {
final Map.Entry v1 = (Map.Entry)a1;
final Map.Entry v2 = (Map.Entry)a2;
final String v3 = v1.getKey();
final String v4 = v2.getKey();
return v3.compareTo(v4);
}
} | [
"[email protected]"
] | |
99e1f83ee5f84e79ea36062f0480e7b12165b704 | 1092fed5204b21d04bc313b7ab2bfcd854839123 | /kyu8/repeatIt.java | 74aa3eefc8b84021d825f7eaf2b20b5343054934 | [] | no_license | yangyangisyou/codewars-collection | c86c23a2460c1e1b3651bf59a5243333f259e8af | fba1929972a0b63fec645dda1f08e63920f9df11 | refs/heads/master | 2020-05-29T14:45:56.379886 | 2019-06-13T09:03:02 | 2019-06-13T09:03:02 | 189,202,341 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 307 | java | public class RepeatIt {
public static String repeatString(final Object toRepeat, final int n) {
String s = "";
if(toRepeat instanceof String)
{
for(int i=0;i<n;i++)
s+=toRepeat;
return s;
}
return "Not a string";
}
} | [
"[email protected]"
] | |
816b63f8146ef678b6be46487055b50933cac086 | c17017451a432059cb337cd909e8138e44db3c02 | /Task_0424/김애은/Solution_합승택시요금_카카오_다익스트라.java | 5bda9b914abb434142c39bcf2f4b72953b6f74a9 | [] | no_license | AlgoStudy14/task | 0ccc26d28cd539d22c0e88fa107ce0d92ec0e290 | e93ac6e2625233e2e92c89384d32ce5e67f3f3ff | refs/heads/main | 2023-08-29T09:38:32.459130 | 2021-10-02T00:16:12 | 2021-10-02T00:16:12 | 337,013,584 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,055 | java | package 다익스트라;
/*
* 할말하않.... 다익스트라로 풀었다가 진짜 엄청 오래걸렸다...
* 최대한 많은 중복 조건을 삭제했다.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class Solution_합승택시요금_카카오 {
public static void main(String[] args) throws NumberFormatException, IOException {
int n=6,s=4,a=6,b=2;
int fares[][]= {{4,1,10},{3,5,24},{5,6,2},{3,1,41},{5,1,24},{4,6,50},{2,4,66},{2,3,22},{1,6,25}};
System.out.println(solution(n,s,a,b,fares));
}
static class Edge implements Comparable<Edge>{
int y,w;
public Edge(int y, int w) {
super();
this.y = y;
this.w = w;
}
@Override
public int compareTo(Edge o) {
return this.w-o.w;
}
}
static List<Edge> list[];
public static int solution(int n, int s, int a, int b, int[][] fares) {
list = new ArrayList[n+1];
for(int i=1;i<n+1;i++) {
list[i]=new ArrayList<>();
}
for(int i=0;i<fares.length;i++) {
int fare[] = fares[i];
int start = fare[0];
int end = fare[1];
int weight =fare[2];
list[start].add(new Edge(end,weight));
list[end].add(new Edge(start,weight));
}
ArrayList<Integer> ar = new ArrayList<>();
for(int i=1;i<n+1;i++) {
int[] p = dijkstra(n,i,a);
int[] t = dijkstra(n,s,i);
ar.add(p[a]+p[b]+t[i]);
}
Collections.sort(ar);;
return ar.get(0);
}
private static int[] dijkstra(int n,int start, int end) {
PriorityQueue<Edge> pq = new PriorityQueue<>();
int dist[] = new int[n+1];
Arrays.fill(dist, 20000001);
pq.add(new Edge(start,0));
dist[start]=0;
while(!pq.isEmpty()) {
Edge q=pq.poll();
int cur=q.y;
if(q.w>dist[cur])continue;
for(Edge ed:list[cur]) {
int cost = dist[cur]+ed.w;
if(ed.w!=0 && cost<dist[ed.y]) {
dist[ed.y]=cost;
pq.add(new Edge(ed.y,dist[ed.y]));
}
}
}
return dist;
}
}
| [
"[email protected]"
] | |
034f48246571384055b501f64869c39d25aea966 | 02e6e3e8c392207dfb8cc81e7c285ac426b20d1a | /metadata/src/main/java/com/coviam/metadata/services/impl/ProgramServiceImpl.java | bec16ae23e2fef809a7b22307abbd2c13b489a8d | [] | no_license | aniketmaurya/bhaikacms | 821b0904b5d92f2b6967af1ffad4dc635dfea8d4 | 70edb18d06f605d51c4d232a0760dd14665a04c5 | refs/heads/master | 2021-07-11T10:47:00.415577 | 2019-08-05T17:17:10 | 2019-08-05T17:17:10 | 199,983,242 | 0 | 1 | null | 2020-09-10T09:20:21 | 2019-08-01T05:30:45 | JavaScript | UTF-8 | Java | false | false | 2,487 | java | package com.coviam.metadata.services.impl;
import com.coviam.metadata.dto.request.ProgramRequest;
import com.coviam.metadata.entity.Program;
import com.coviam.metadata.repository.ProgramRepository;
import com.coviam.metadata.repository.SeasonRepository;
import com.coviam.metadata.services.ProgramServices;
import com.coviam.metadata.services.SeasonServices;
import com.coviam.metadata.utility.AuditUtility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@Slf4j
public class ProgramServiceImpl implements ProgramServices {
@Autowired
private ProgramRepository programRepository;
@Autowired
private SeasonRepository seasonRepository;
@Autowired
private SeasonServices seasonServices;
private final String ADD = "ADD";
private final String UPDATE = "UPDATE";
private final String DELETE = "DELETE";
@Transactional
@Override
public Program addProgram(Program program) {
log.info("Adding program programName: {}", program.getName());
AuditUtility.programAudit(new Program(), program, ADD);
return Optional.of(programRepository.save(program)).orElse(new Program());
}
@Override
public Boolean editProgram(ProgramRequest programRequest) {
if (!programRepository.existsById(programRequest.getId())) {
return Boolean.FALSE;
}
Program program = programRepository.findById(programRequest.getId()).get();
BeanUtils.copyProperties(programRequest, program);
programRepository.save(program);
log.info("Program update programId: {} ", programRequest.getId());
return Boolean.TRUE;
}
// we are using cascade delete constraint
@Transactional
@Override
public Boolean deleteProgramById(String programId) {
Program program = programRepository.findById(programId).orElse(new Program());
AuditUtility.programAudit(program, program, DELETE);
programRepository.deleteById(programId);
log.warn("Cascade delete action will be performed for programId: {}", programId);
return Boolean.TRUE;
}
@Override
public Program getProgramById(String programId) {
return programRepository.findById(programId).orElse(new Program());
}
} | [
"[email protected]"
] | |
9f94795f4847add54f650cdccb6bdd61414c7aad | e269f3e2a54076b1d30d84167583582328bcb772 | /src/main/java/mq/TestListener.java | aae1e839f1ef6a8c3a941e8d4213f5eea71221cb | [] | no_license | aaaaatoz/awssqs | b3bf3efd591d9decd0f771c7d5895d242fa7f4d8 | 2760044e8ec6b1dae941965e269796cb98a3297d | refs/heads/master | 2021-01-02T09:12:28.236309 | 2018-01-09T11:50:38 | 2018-01-09T11:50:38 | 99,166,297 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 712 | java | package mq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
* Created by Rafaxu on 12/6/17.
*/
public class TestListener implements MessageListener {
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
final String messageText = ((TextMessage) message).getText();
System.out.println(messageText);
}
catch (JMSException ex) {
throw new RuntimeException(ex);
}
}
else {
throw new IllegalArgumentException("Message must be of type TextMessage");
}
}
}
| [
"[email protected]"
] | |
2d31e258e0b2c82c35746034936b482a1ebd2267 | ef0fbb5466f829897afcc420422608cf21a0eba1 | /src/main/java/br/com/diop/product/repository/Products.java | 3bdf3edf3fdbb782b7b4b18b75bc436efd09eed1 | [] | no_license | DioniPinho/product | 80f469a67adb5ecc26d7725d384a5fb7cb163b5c | 1673746be48a0a0d783e0c15f32d847cdf9e87a2 | refs/heads/master | 2021-01-22T05:43:40.634546 | 2017-02-12T00:44:48 | 2017-02-12T00:44:48 | 81,692,224 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 384 | java | package br.com.diop.product.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.web.config.SpringDataWebConfigurationMixin;
import br.com.diop.product.model.Product;
public interface Products extends JpaRepository<Product, Long> {
public List<Product> findByNameContainingIgnoreCase(String name);
}
| [
"[email protected]"
] | |
86d68c0da4cda978ef97a1d9643a29fe3648540d | cc04de86cd61e67280c69a55933d7698ab3b5484 | /app/src/main/java/com/chs/myrxjavaandretrofit/MainActivity.java | 3e112c702064b50e0f0cb77325f187ce0a2c9c35 | [] | no_license | wherego/MyRxJavaAndRetrofit | a7b4ea40b7ba9deb276429a91b6d66d9c05ec987 | e00b8c9586142f77c71424f10036b236e9c0c6e2 | refs/heads/master | 2021-01-20T13:42:50.492043 | 2016-04-19T06:41:48 | 2016-04-19T06:41:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,809 | java | package com.chs.myrxjavaandretrofit;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.chs.myrxjavaandretrofit.retrofit.RetrofitActivity;
import com.chs.myrxjavaandretrofit.rxjava.RxJavaActivity;
import com.chs.myrxjavaandretrofit.rxjavaretrofit.RxJavaRetrofitActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_rxjava,btn_retrofit,btn_rxjava_retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initEvent();
}
private void initView() {
btn_rxjava = (Button) findViewById(R.id.btn_rxjava);
btn_retrofit = (Button) findViewById(R.id.btn_retrofit);
btn_rxjava_retrofit = (Button) findViewById(R.id.btn_rxjava_retrofit);
}
private void initEvent() {
btn_rxjava.setOnClickListener(this);
btn_retrofit.setOnClickListener(this);
btn_rxjava_retrofit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()){
case R.id.btn_rxjava:
intent = new Intent(this, RxJavaActivity.class);
startActivity(intent);
break;
case R.id.btn_retrofit:
intent = new Intent(this, RetrofitActivity.class);
startActivity(intent);
break;
case R.id.btn_rxjava_retrofit:
intent = new Intent(this, RxJavaRetrofitActivity.class);
startActivity(intent);
break;
}
}
}
| [
"[email protected]"
] | |
a781e173834c1583a4366142904e2d7c85ca395a | 3e8893e5731321fdf8d90d4708712889161f376f | /java-core/src/ua/com/juja/core/Lab1bits.java | d378eff4dccc04e37647ff72a500ae59926b7a0f | [] | no_license | artemburlaka/Juja_Core | 063e53c986154790dbbf564f7fd7331d232561b8 | 869507c3160bc2b6ba458aa6cfbb893dbf977d35 | refs/heads/master | 2020-12-26T03:11:20.012084 | 2016-04-24T17:47:49 | 2016-04-24T17:47:49 | 47,022,649 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 626 | java | package ua.com.juja.core;
/**
* Created by Artem on 21.11.2015.
*/
public class Lab1bits {
public static void main(String[] args) {
int b = 0b10000000_00000000_00000000_00000001;
int c = 0b11111111_11111111_11111111_11111111;
System.out.println(b);
System.out.println(c);
System.out.println(leftShift(b));
}
public static int leftShift(int arg) {
int a = 0;
if (arg <= 0b11111111_11111111_11111111_11111111)
{
a = arg << 1;
a++;
}
else {
a = arg << 1;
}
return a;
}
}
| [
"[email protected]"
] | |
8cd1f36f650b425fde178ce26a061f6dcdb5ad65 | f9382899deb178d4955a87a2436ebe9fad50c73f | /Kiderdojo/src/Model/DBSelectStat.java | 2bd1ffcd27ff745be44ddfc41531183d158a373e | [] | no_license | rmit-s3626050-Trung-Pham/hello_world | b7a9f7c6580e3689b8366cdf31c3a58a590ca4eb | c061210c2da473c5eea8de7ac8a781940e960af4 | refs/heads/master | 2021-07-06T11:51:41.742685 | 2017-09-30T12:30:31 | 2017-09-30T12:30:31 | 105,366,442 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,819 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author phamtrung
*/
public class DBSelectStat {
public DatabaseConnection dbConn = new DatabaseConnection();
public ArrayList<User> userArray = new ArrayList<>();
public ArrayList<AccountManager> arrayM = new ArrayList<>();
public ArrayList<AccountCarer> arrayC = new ArrayList<>();
public ArrayList<AccountParent> arrayP = new ArrayList<>();
public DBSelectStat(){
// selectSqlStat();
loadManagerAccount();
loadCarerAccount();
loadParentAccount();
}
public void selectSqlStat(){
}
public void loadManagerAccount(){
String query = "Select * from ManagerAccount";
Statement stat = null;
try {
stat = dbConn.conn.createStatement();
ResultSet rs = stat.executeQuery(query);
while (rs.next()){
AccountManager accMan = new AccountManager();
accMan.username = rs.getString(1);
accMan.password = rs.getString(2);
arrayM.add(accMan);
System.out.print(accMan.username);
System.out.print(" | ");
System.out.print(accMan.password);
System.out.println("");
}
} catch (SQLException ex) {
Logger.getLogger(DBSelectStat.class.getName()).log(Level.SEVERE, null, ex);
}
// for (User user : userArray) {
// System.out.print(user.username);
// System.out.print(" | ");
// System.out.print(user.password);
// System.out.println("");
// }
}
public void loadCarerAccount(){
String query = "Select * from CarerAccount";
Statement stat = null;
try {
stat = dbConn.conn.createStatement();
ResultSet rs = stat.executeQuery(query);
while (rs.next()){
AccountCarer accCar = new AccountCarer();
accCar.username = rs.getString(1);
accCar.password = rs.getString(2);
arrayC.add(accCar);
System.out.print(accCar.username);
System.out.print(" | ");
System.out.print(accCar.password);
System.out.println("");
}
} catch (SQLException ex) {
Logger.getLogger(DBSelectStat.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void loadParentAccount(){
String query = "Select * from ParentAccount";
Statement stat = null;
try {
stat = dbConn.conn.createStatement();
ResultSet rs = stat.executeQuery(query);
while (rs.next()){
AccountParent accPar = new AccountParent();
accPar.username = rs.getString(1);
accPar.password = rs.getString(2);
arrayP.add(accPar);
System.out.print(accPar.username);
System.out.print(" | ");
System.out.print(accPar.password);
System.out.println("");
}
} catch (SQLException ex) {
Logger.getLogger(DBSelectStat.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void ManagerDisplay(){
}
public static void main(String[] args) {
DBSelectStat dbSecl = new DBSelectStat();
dbSecl.selectSqlStat();
}
}
| [
"[email protected]"
] | |
ee58c95511352cecbaac45c49b2a219ac5b20726 | 997d1e6951d31fb8beda337b89c85c4105d33248 | /icql-java-algorithm/src/main/java/work/icql/java/algorithm/链表/链表_0141_环形链表.java | 6ba7cbb069e4e41426a5afb3def8f275f6f1d95d | [
"Apache-2.0"
] | permissive | icql/icql-java | af5784e200cd287b9703b2029a80f2a263746b6d | df4e1125a625a1c8c61d792975026282ea35bf63 | refs/heads/master | 2023-04-04T13:58:02.727381 | 2022-12-08T10:51:18 | 2022-12-08T10:51:18 | 207,701,114 | 1 | 0 | Apache-2.0 | 2023-03-27T22:18:24 | 2019-09-11T02:01:01 | Java | UTF-8 | Java | false | false | 1,528 | java | package work.icql.java.algorithm.链表;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class 链表_0141_环形链表 {
static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
public void traverse() {
System.out.println();
System.out.print("开始 -> ");
ListNode pointer = this;
while (Objects.nonNull(pointer)) {
System.out.print(pointer.val + " -> ");
pointer = pointer.next;
}
System.out.print("结束");
}
}
public boolean hasCycle(ListNode head) {
if (Objects.isNull(head)) {
return false;
}
ListNode pointer = head;
Set<ListNode> nodeSet = new HashSet<>();
while (Objects.nonNull(pointer)) {
if (nodeSet.contains(pointer)) {
return true;
}
nodeSet.add(pointer);
pointer = pointer.next;
}
return false;
}
public static void main(String[] args) {
链表_0141_环形链表 link = new 链表_0141_环形链表();
ListNode l1 = new ListNode(3);
l1.next = new ListNode(2);
l1.next.next = new ListNode(0);
l1.next.next.next = new ListNode(-4);
l1.next.next.next.next = l1.next;
boolean ret = link.hasCycle(l1);
System.out.println();
}
}
| [
"[email protected]"
] | |
ad3922e2ce4d283f00bd50faa9a4ea2ff1ad3036 | aed6195bb5853ee197647e67d6bb737958b834fc | /coupon/coupon-service/coupon-template/src/main/java/com/huey/service/impl/TemplateBaseServiceImpl.java | a9f808e328d82b5487d0c45dd759c41403f64e01 | [] | no_license | xuziyu/coupon | c08e739b7cdb3c6fede23e8de68cf93f737c4750 | 8958e6cef880c33408b3ee838fc543fbeb30d1b8 | refs/heads/master | 2022-06-22T17:54:22.956991 | 2020-03-11T07:50:05 | 2020-03-11T07:50:05 | 246,498,637 | 0 | 0 | null | 2022-06-21T02:57:55 | 2020-03-11T07:03:04 | Java | UTF-8 | Java | false | false | 2,754 | java | package com.huey.service.impl;
import com.huey.dao.CouponTemplateDao;
import com.huey.entity.CouponTemplate;
import com.huey.exception.CouponException;
import com.huey.service.ITemplateBaseService;
import com.huey.vo.CouponTemplateSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @Author: huey
* @Desc: 优惠券基础接口查询
*/
@Service
public class TemplateBaseServiceImpl implements ITemplateBaseService {
@Autowired
private CouponTemplateDao couponTemplateDao;
/**
* 根据优惠券模板 id 获取优惠券模板信息
* @param id 模板 id
* @return
* @throws CouponException
*/
@Override
public CouponTemplate buildTemplateInfo(Integer id) throws CouponException {
Optional<CouponTemplate> template = couponTemplateDao.findById(id);
if (!template.isPresent()) {
throw new CouponException("Template Is Not Exist: " + id);
}
return template.get();
}
/**
* 查询所有的优惠券模板
* @return
*/
@Override
public List<CouponTemplateSDK> findAllUsableTemplate() {
List<CouponTemplate> templates =
couponTemplateDao.findAllByAvailableAndExpired(
true, false);
return templates.stream()
.map(this::template2TemplateSDK).collect(Collectors.toList());
}
/**
* 获取模板 ids 到 CouponTemplateSDK 的映射
* @param ids 模板 ids
* @return
*/
@Override
public Map<Integer, CouponTemplateSDK> findIds2TemplateSDK(Collection<Integer> ids) {
List<CouponTemplate> templates = couponTemplateDao.findAllById(ids);
return templates.stream().map(this::template2TemplateSDK)
.collect(Collectors.toMap(
CouponTemplateSDK::getId, Function.identity()
));
}
/**
* <h2>将 CouponTemplate 转换为 CouponTemplateSDK</h2>
* */
private CouponTemplateSDK template2TemplateSDK(CouponTemplate template) {
return new CouponTemplateSDK(
template.getId(),
template.getName(),
template.getLogo(),
template.getDesc(),
template.getCategory().getCode(),
template.getProductLine().getCode(),
// 并不是拼装好的 Template Key
template.getKey(),
template.getTarget().getCode(),
template.getRule()
);
}
}
| [
"[email protected]"
] | |
f0a77b763d2341e537084d8e200826428e5955bc | 517bee5e5a566ed6eb92e7bfa932a1ececfa32b1 | /ProjetJava/src/interfaceHM/GererPatients.java | cfda5a0bda0f20571f6cc8819a314c5bbd62b99f | [] | no_license | youp911/cabinet-medical-projetjava | 99592b485a71bd7f642b9f203be724d8a120728a | 10b08b6fde2e2a572445911eef0a77c26ec79ba6 | refs/heads/master | 2016-09-06T13:37:04.060542 | 2014-02-07T08:51:56 | 2014-02-07T08:51:56 | 32,425,236 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 4,973 | java | package interfaceHM;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import java.util.Date;
import metier.Patient;
import dao.DaoPatient;
//GererPatients permet d'afficher et d'interagir avec l'interface de gestion des patients
//L'affichage des patients est réalisé avec une JTab (tableau)
public class GererPatients extends JInternalFrame implements ActionListener {
private JTable lstMedecin;
private Object[][] lignes;
private JPanel panel;
private JButton btnValider;
private JLabel lblNewLabel;
private static JTable table;
private JTable table_1;
private JScrollPane scrollPane_1;
private static DefaultTableModel dtm;
private JButton btnSupprimer;
private JButton btnModifier;
private JButton btnAnnuler;
// Créé la fenêtre et tout ses composants graphiques
public GererPatients()
{
setBounds(100, 100, 852, 523);
getContentPane().setLayout(null);
lblNewLabel = new JLabel("Gerer les M\u00E9decins");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 32));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(188, 11, 413, 197);
getContentPane().add(lblNewLabel);
this.table = new JTable();
this.table.setBounds(10, 11, 656, 135);
//Creation d'un JScrollPane pour obtenir les titres du JTable
this.scrollPane_1 = new JScrollPane(this.table,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
this.scrollPane_1.setBounds(31, 156, 739, 219);
getContentPane().add(this.scrollPane_1);
//btnSupprimer = new JButton("Supprimer");
//btnSupprimer.addActionListener(this);
//btnSupprimer.setBounds(418, 421, 101, 23);
//getContentPane().add(btnSupprimer);
btnModifier = new JButton("Modifier");
btnModifier.addActionListener(this);
btnModifier.setBounds(317, 421, 91, 23);
getContentPane().add(btnModifier);
btnAnnuler = new JButton("Annuler");
btnAnnuler.addActionListener(this);
btnAnnuler.setBounds(216, 421, 91, 23);
getContentPane().add(btnAnnuler);
//Met à jour le JTable
updateTable();
for(Patient unPatient : DaoPatient.getLesPatients())
{
this.ajoutPatientTableau(unPatient);
}
}
// Permet de mettre à jour la liste des patients (JTab)
private void updateTable() {
String[] titre = {"Numéro du Patient",
"Nom",
"Prénom",
"Adresse",
"Code Postal",
"Ville",
"Date de Naissance"};
Object[][] listeMedecin = new Object[0][7];
dtm = new DefaultTableModel(listeMedecin, titre){
public boolean isCellEditable(int row, int col) {
return false;
};
};
table.setModel(dtm);
}
// Permet d'ajouter un nouveau patient à la liste des patients (JTab)
public static void ajoutPatientTableau(Patient unPatient)
{
/* ajout d'une nouvelle ligne au tableau des Médecins */
dtm.addRow(new Object[]{unPatient.getNumPatient(),unPatient.getNomPatient(),unPatient.getPrenomPatient(),unPatient.getAdressePatient(),
unPatient.getCPPatient(),unPatient.getVillePatient(),unPatient.getDateNaiss()});
table.setModel(dtm);
}
// Permet l'interaction entre les composants graphiques et l'interface
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == this.btnAnnuler)
{
dispose();
}
if ( evt.getSource() == this.btnModifier)
{
int ligne = table.getSelectedRow();//Si tu veut la ligne selectionnée
Patient unPatient = new Patient((Integer)table.getValueAt(ligne, 0),(String)table.getValueAt(ligne, 1),(String)table.getValueAt(ligne, 2),
(String)table.getValueAt(ligne, 3),(String)table.getValueAt(ligne, 4),(String)table.getValueAt(ligne, 5),(String)table.getValueAt(ligne, 6));
getContentPane().removeAll();
ModifierPatient fModifierPatient;
fModifierPatient = new ModifierPatient(unPatient);
fModifierPatient.setBounds(100, 100, 852, 523);
fModifierPatient.setVisible(true);
}
//if ( evt.getSource() == this.btnSupprimer)
//{
// int ligne = table.getSelectedRow();//Si tu veut la ligne selectionnée
// Medecin m = new Medecin((String)table.getValueAt(ligne, 0),(String)table.getValueAt(ligne, 1),(String)table.getValueAt(ligne, 2),
// (String)table.getValueAt(ligne, 3),(String)table.getValueAt(ligne, 4),(String)table.getValueAt(ligne, 5));
// getContentPane().removeAll();
// DaoMedecin.SupprimerUnMedecin(m);
//}
}
}
| [
"[email protected]@2882ab87-aa1d-ec78-4d69-7bdfc76730b1"
] | [email protected]@2882ab87-aa1d-ec78-4d69-7bdfc76730b1 |
255e5b03f5b7c2e3eb53481ce0abbc70abd645ff | 106f92be149c95dbfbdab886c5e53ea8a54a513a | /backend/src/main/java/com/devsuperior/dsvendas/repositories/SaleRepository.java | 9c6caf815583ebac6e989d29bfa24bc2852e86db | [] | no_license | Frankfel/projeto-sds3 | ee6c08d5c0cc7cd5a7e5bdce7e9aeea2a054d90b | df648c2b7a5e93aa1ef063ccff7f3c106d6d3aa4 | refs/heads/master | 2023-09-05T05:50:31.358006 | 2021-11-06T07:50:01 | 2021-11-06T07:50:01 | 423,477,262 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 800 | java | package com.devsuperior.dsvendas.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.devsuperior.dsvendas.dto.SaleSuccessDTO;
import com.devsuperior.dsvendas.dto.SalesSumDTO;
import com.devsuperior.dsvendas.entities.Sale;
public interface SaleRepository extends JpaRepository<Sale, Long> {
@Query("SELECT new com.devsuperior.dsvendas.dto.SalesSumDTO(obj.seller, SUM(obj.amount)) "
+ "FROM Sale AS obj GROUP BY obj.seller")
List<SalesSumDTO> amountGroupedBySeller();
@Query("SELECT new com.devsuperior.dsvendas.dto.SaleSuccessDTO(obj.seller, SUM(obj.visited), SUM(obj.deals)) "
+ "FROM Sale AS obj GROUP BY obj.seller")
List<SaleSuccessDTO> successGroupedBySeller();
} | [
"[email protected]"
] | |
ee684fff2bf6bb4e532fea6247f1c2682dff7785 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/18/18_20f21462f7dcd8c0151fe6ba3488b2d0142c09f8/HRMController/18_20f21462f7dcd8c0151fe6ba3488b2d0142c09f8_HRMController_s.java | 97786af407ea15267ac59a7e476d80c9fe8cb82c | [] | 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 | 164,054 | 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.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Date;
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.BullyPriority;
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.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 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
*/
private static LinkedList<HRMController> mRegisteredHRMControllers = new LinkedList<HRMController>();
/**
* 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_BULLY_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 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 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;
/**
* @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());
// 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 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] = 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 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, mDecoratorForCoordinatorsAndHRMIDs);
/**
* 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();
}
/**
* 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!?");
}
synchronized (mLocalCoordinators) {
// register as known coordinator
mLocalCoordinators.add(pCoordinator);
}
// 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());
}
}
// 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
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
*/
//TODO // 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
// tNMS.registerName(tLocalRouterName, pOldHRMID, 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 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);
/**
* 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);
}
/**
* 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 Bully priority is the right one, avoid race conditions here
pCoordinatorAsClusterMember.setPriority(BullyPriority.create(this, getHierarchyNodePriority(pCoordinatorAsClusterMember.getHierarchyLevel())));
if(!mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){
// register as known coordinator-as-cluster-member
mLocalCoordinatorAsClusterMemebers.add(pCoordinatorAsClusterMember);
tNewEntry = true;
}
}
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 Bully priority is the right one, avoid race conditions here
pClusterMember.setPriority(BullyPriority.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.toString() + " 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);
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)
{
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 given HRMID is a local one.
*
* @param pHRMID the HRMID of the Cluster
*
* @return true if the local node belongs to the given Cluster
*/
private boolean isLocalCluster(HRMID pHRMID)
{
boolean tResult = false;
if(pHRMID.isClusterAddress()){
synchronized(mRegisteredOwnHRMIDs){
for(HRMID tKnownHRMID : mRegisteredOwnHRMIDs){
//Logging.err(this, "Checking isCluster for " + tKnownHRMID + " and if it is " + pHRMID);
if(tKnownHRMID.isCluster(pHRMID)){
//Logging.err(this, " ..true");
tResult = true;
break;
}
}
}
}else{
Logging.err(this, "isLocalCluster() cannot operate on a given L0 node HRMID");
}
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)
{
for(RoutingEntry tNewEntry : pReceivedSharedRoutingTable){
RoutingEntry tSharedEntry = tNewEntry.clone();
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
// Logging.err(this, " ..received shared route: " + tNewEntry + ", aggregated foreign destination: " + aggregateForeignHRMID(tNewEntry.getDest()));
}
/**
* Mark as shared entry
*/
tSharedEntry.setSharedLink(pSenderHRMID);
/**
* Store all routes, which start at this node
*/
if(isLocal(tSharedEntry.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(!isLocalCluster(tSharedEntry.getDest())){
if(tSharedEntry.getHopCount() > 1){
RoutingEntry tNewLocalRoutingEntry = tSharedEntry.clone();
// 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(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, "Adding shared route (timeout=" + tNewLocalRoutingEntry.getTimeout() + ", time-offset=" + tTimeoffset + "): " + tNewLocalRoutingEntry);
}
addHRMRoute(tNewLocalRoutingEntry);
}else{
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE_REDUNDANT_ROUTES){
Logging.warn(this, " ..dropping uninteresting (leads to a direct neighbor node/cluster) route: " + tSharedEntry);
}
}
}else{
if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE_REDUNDANT_ROUTES){
Logging.warn(this, " ..dropping uninteresting (has same next hop like an existing entry) route: " + tSharedEntry);
}
}
}
}
}
/**
* 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 registerLinkL2(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().registerLinkL2(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
*/
private 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;
/**
* 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_COORDINATOR_ANNOUNCEMENTS = true;
mSimulationTimeOfLastCoordinatorAnnouncementWithImpact = 0;
}
/**
* 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 priority (" + pPriority + ") update (" + 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
*/
mProcessorThread.eventNewHierarchyPriority(pHierarchyLevel);
//HINT: for synchronous execution use here "distributeHierarchyNodePriorityUpdate(pHierarchyLevel)"
// instead of "mProcessorThread.eventNewHierarchyPriority(pHierarchyLevel)"
/**
* Trigger: hierarchy data changed
*/
eventHierarchyDataChanged();
}
/**
* Increases base Bully 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 " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// increase priority
tPriority += BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionConnectivityPriorityUpdates += "\n + " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor;
// update priority
setConnectivityPriority(tPriority);
Logging.log(this, "Increasing hierarchy node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// get the current priority
long tHierarchyPriority = mNodeHierarchyPriority[1];
// increase priority
tHierarchyPriority += BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionHierarchyPriorityUpdates += "\n + " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor;
// update priority
setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1));
}
/**
* Decreases base Bully 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 " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// increase priority
tPriority -= BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionConnectivityPriorityUpdates += "\n - " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor;
// update priority
setConnectivityPriority(tPriority);
Logging.log(this, "Decreasing hierarchy node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY);
// get the current priority
long tHierarchyPriority = mNodeHierarchyPriority[1];
// increase priority
tHierarchyPriority -= BullyPriority.OFFSET_FOR_CONNECTIVITY;
mDesriptionHierarchyPriorityUpdates += "\n - " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor;
// update priority
setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1));
}
/**
* Increases hierarchy Bully 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 = 256; //TODO: use a definition here
}
if((tDistance >= 0) && (tDistance <= tMaxDistance)){
// get the current priority
long tPriority = mNodeHierarchyPriority[tHierLevel];
float tOffset = 0;
if (pCausingEntity.getHierarchyLevel().isBaseLevel()){
tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance);
}else{
tOffset = (float)BullyPriority.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);
mDesriptionHierarchyPriorityUpdates += "\n + " + tOffset + "-L" + tHierLevel + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity;
// update priority
setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel));
}else{
Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance);
}
}
}
/**
* Decreases hierarchy Bully 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 = 256; //TODO: use a definition here
}
if((tDistance >= 0) && (tDistance <= tMaxDistance)){
// get the current priority
long tPriority = mNodeHierarchyPriority[tHierLevel];
float tOffset = 0;
if (pCausingEntity.getHierarchyLevel().isBaseLevel()){
tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance);
}else{
tOffset = (float)BullyPriority.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);
mDesriptionHierarchyPriorityUpdates += "\n - " + tOffset + "-L" + tHierLevel + " <== 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)){
Logging.log(this, "\n######### Detected lost network interface: " + pInterfaceToNeighbor);
mLocalNetworkInterfaces.remove(pInterfaceToNeighbor); //TODO: multiple nodes!?
}
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) {
if(!mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){
Logging.log(this, "\n######### Detected new network interface: " + pInterfaceToNeighbor);
mLocalNetworkInterfaces.add(pInterfaceToNeighbor);
}
//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.
*/
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 > HRMConfig.Hierarchy.COORDINATOR_TIMEOUT * 2){
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_REPORTING_SHARING){
autoActivateReportingSharing();
}
}
}
}
}
}
/**
* 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;
}
/**
* 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(GUI_USER_CTRL_REPORT_TOPOLOGY){
/**
* report phase
*/
for (Coordinator tCoordinator : getAllCoordinators()) {
tCoordinator.reportPhase();
}
if(GUI_USER_CTRL_SHARE_ROUTES){
/**
* share phase
*/
for (Coordinator tCoordinator : getAllCoordinators()) {
tCoordinator.sharePhase();
}
}
}
/**
* auto-remove old HRM routes
*/
autoRemoveObsoleteHRMRoutes();
/**
* register next trigger
*/
mAS.getTimeBase().scheduleIn(HRMConfig.Routing.GRANULARITY_SHARE_PHASE, this);
}
/**
* Calculate the time period between "share phases"
*
* @param pHierarchyLevel the hierarchy level
* @return the calculated time period
*/
public double getPeriodSharePhase(int pHierarchyLevelValue)
{
return (double) 2 * HRMConfig.Routing.GRANULARITY_SHARE_PHASE * pHierarchyLevelValue; //TODO: use an exponential time distribution here
}
/**
* Calculate the time period between "share phases"
*
* @param pHierarchyLevel the hierarchy level
* @return the calculated time period
*/
public double getPeriodReportPhase(HierarchyLevel pHierarchyLevel)
{
return (double) HRMConfig.Routing.GRANULARITY_SHARE_PHASE * (pHierarchyLevel.getValue() - 1); //TODO: use an exponential time distribution here
}
/**
* 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(Name pNeighborName)
{
L2Address tResult = null;
if (pNeighborName != null){
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{
Logging.warn(this, "Got for neighbor " + pNeighborName + " the route: " + tRoute); //HINT: this could also be a local loop -> throw only a warning
}
}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);
}
}
/**
* This function gets called if the HRMController appl. should exit/terminate right now
*/
@Override
public synchronized void exit()
{
mApplicationStarted = false;
Logging.log(this, "\n\n\n############## Exiting..");
Logging.log(this, " ..destroying clusterer-thread");
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) {
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; //TODO: use a new clone() method here
}
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;
if(pRoutingEntry.getTimeout() > 0){
tKnownLink.setTimeout(pRoutingEntry.getTimeout());
}
// 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();
mHierarchicalRoutingGraph.link(pFrom.clone(), pTo.clone(), 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)
{
boolean DEBUG = false;
RoutingEntry tResult = null;
if (DEBUG){
Logging.log(this, "getRoutingEntryHRG() searches a route from " + pFrom + " to " + pTo);
}
/**
* 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 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(pFrom, tAbstractDestination, pCause);
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(tIngressGatewayToDestinationCluster, pTo, pCause);
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;
// get the inter-cluster path to the possible destination
List<AbstractRoutingGraphLink> tPath = getRouteHRG(pFrom, pTo);
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 tLink : tPath){
RoutingEntry tInterClusterRoutingEntry = (RoutingEntry)tLink.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(tLastClusterGateway, tNextClusterGateway);
if(tIntraClusterPath != null){
if(!tIntraClusterPath.isEmpty()){
RoutingEntry tLogicalIntraClusterRoutingEntry = null;
/**
* Determine the intra-cluster route part
*/
// check if we have only one hop in intra-cluster route
if(tIntraClusterPath.size() == 1){
AbstractRoutingGraphLink tIntraClusterLogLink = tIntraClusterPath.get(0);
// 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){
Logging.warn(this, "getRoutingEntryHRG() for " + pFrom + " found a complex intra-cluster path 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);
// 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();
}
}
}
}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++;
/**
* Determine the next hop for the resulting path
*/
if(tFirstForeignGateway == null){
if(tInterClusterRoutingEntry.getHopCount() > 0){
tFirstForeignGateway = tInterClusterRoutingEntry.getNextHop();
}
}
//update last cluster gateway
tLastClusterGateway = tInterClusterRoutingEntry.getNextHop();
}
}else{
Logging.err(this, "getRoutingEntryHRG() found an empty path from " + pFrom + " to " + pTo);
}
if(tResult != null){
// set the DESTINATION for the resulting routing entry
tResult.setDest(pFrom.getForeignCluster(pTo) /* aggregate the destination here */);
// set the NEXT HOP for the resulting routing entry
if(tFirstForeignGateway != null){
// tResult.setNextHop(tFirstForeignGateway);
}
// reset L2Address for next hop
tResult.setNextHopL2Address(null);
}
}else{
Logging.err(this, "getRoutingEntryHRG() couldn't determine an HRG route from " + pFrom + " to " + pTo);
}
return tResult;
}
/**
* Unregisters automatically old links from the HRG based on each link's timeout value
*/
public void autoRemoveObsoleteHRGLinks()
{
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 getRoutesWithNeighborsHRG(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);
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);
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)
{
List<AbstractRoutingGraphLink> tResult = null;
if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){
Logging.log(this, "GET ROUTE (HRG) from \"" + pSource + "\" to \"" + pDestination +"\"");
}
synchronized (mHierarchicalRoutingGraph) {
tResult = mHierarchicalRoutingGraph.getRoute(pSource, pDestination);
}
if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){
Logging.log(this, " ..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; //TODO: use a new clone() method here
}
return tResult;
}
/**
* 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{
/**
* 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 = tPropProbeRouting.getRecordedHops();
Logging.log(this, " ..detected a probe-routing connection(source=" + tPropProbeRouting.getSourceDescription() + " with " + tRecordedHRMIDs.size() + " recorded hops");
// print the recorded route
int i = 0;
for(HRMID tHRMID : tRecordedHRMIDs){
Logging.log(this, " [" + i + "]: " + tHRMID);
i++;
}
}
}
/**
* 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";
}
| [
"[email protected]"
] | |
73dbd8ec0544902d8cce9c2469e42cb1f1e515f4 | 2470e949ef929d41084bcc59bf048bb35461b3d0 | /cql-migrations-dbsupport/src/test/java/in/vagmim/cqlmigrations/MigrationTest.java | bbac5d1b818cf522c6ce0482d34009970bbcb4ad | [] | no_license | vagmi/cql-migrations | 5b3ddef38eb206718bbaa365398cb3facb754180 | 149e82831852435c7c6d5a24bb3ff4590596e33a | refs/heads/master | 2021-01-01T18:34:29.131299 | 2014-05-01T23:02:21 | 2014-05-01T23:02:21 | 19,328,574 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,199 | java | package in.vagmim.cqlmigrations;
import in.vagmim.cqlmigrations.exceptions.MigrationException;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import static org.junit.Assert.assertEquals;
public class MigrationTest extends AbstractCassandraTest {
Migration migration;
@Before
public void setupMigration() {
Resource migrationResource = new ClassPathResource("cql/migrations/20140501232323_create_test_tables.cql");
migration = new Migration(migrationResource);
}
@Test
public void shouldMigrate() throws Exception {
migration.migrate(session,TESTKEYSPACE);
session.execute("use " + TESTKEYSPACE + ";");
session.execute("select * from customers;");
session.execute("select * from orders;");
}
@Test
public void shouldGetFileName() throws Exception {
assertEquals("20140501232323_create_test_tables.cql", migration.getFileName());
}
@Test
public void shouldGetVersion() throws Exception, MigrationException {
assertEquals(new Long(20140501232323l), migration.getVersion());
}
}
| [
"[email protected]"
] | |
c09824faf32ecadfc3a2d683dd5787f4ff33f8bc | f4e02e4164fad3d79c9652e165ad3b026263b08f | /src/test/ApplicationClient.java | 4188ba6a5f6a608a3ad9cb2cbd4933aeaf378f7c | [] | no_license | Oumaymaazmi/Vote-electronique | 7f50e1add2b7b6cc85478d963be24d1db77c46a3 | 315c1e8dd635358fde53e317c16425ed3ff36db8 | refs/heads/master | 2023-07-11T09:08:33.699082 | 2021-08-05T10:43:24 | 2021-08-05T10:43:24 | 393,003,305 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,651 | java | package test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import bean.User;
import service.UserService;
public class ApplicationClient {
public static void main(String[] args)
throws NotBoundException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, CertificateException, IOException, KeyStoreException, UnrecoverableEntryException {
// ServiceVote stub= (ServiceVote) Naming.lookup("rmi://localhost:1011/SI");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null);
Certificate certificate = keyStore.getCertificate("receiverKeyPair");
PublicKey publicKey1 = certificate.getPublicKey();
PrivateKey privateKey =
(PrivateKey) keyStore.getEntry(null, null);
User user = new User(privateKey, publicKey1);
UserService userService = new UserService(user);
byte[] sug = userService.signature("oumayma", publicKey1);
userService.decripto(sug);
}
}
| [
"[email protected]"
] | |
967f72502d73948aaeb17bed56b6e6854cd8af85 | 1c524f5e470045beb69a473c0f4a2e34064739bd | /src/main/java/com/elderresearch/wargaming/WargamingStaticClient.java | 4a25c3586319042d39d7d844361ecbda34e12904 | [
"Apache-2.0"
] | permissive | ElderResearch/wargaming-java-sdk | f7286efbc4e757ac543bc5ce609986a6b24e1501 | 5a1968617d3f604751d5c7bf4e3c45a3656a4bba | refs/heads/develop | 2022-02-05T02:06:40.810153 | 2020-10-27T13:30:22 | 2020-10-27T13:30:22 | 188,481,757 | 0 | 0 | Apache-2.0 | 2022-01-04T16:34:41 | 2019-05-24T20:11:29 | Java | UTF-8 | Java | false | false | 1,026 | java | /*******************************************************************************
* Copyright (c) 2017 Elder Research, Inc.
* All rights reserved.
*******************************************************************************/
package com.elderresearch.wargaming;
import org.glassfish.jersey.logging.LoggingFeature;
import com.elderresearch.commons.rest.client.RestClient;
import com.elderresearch.commons.rest.client.WebParam.WebTemplateParam;
import lombok.experimental.Accessors;
import lombok.extern.java.Log;
@Log
@Accessors(fluent = true)
public class WargamingStaticClient extends RestClient {
private static final String BASE = "https://cwxstatic-{realm}.wargaming.net/v25/";
WargamingStaticClient(WargamingConfig config) {
super(builderWithFeatures(new LoggingFeature(log, config.getLogLevel(), config.getLogVerbosity(), LoggingFeature.DEFAULT_MAX_ENTITY_SIZE))
.register(WargamingClient.JSON_PROVIDER));
setBase(BASE);
setPerpetualParams(WebTemplateParam.of("realm", config.getRealm()));
}
}
| [
"[email protected]"
] | |
567c27e4a04c5b058dbfa7b43a7ada086a092a71 | d03bcc429f7034a9bba21fc5d8ff8b4584612e36 | /app/src/test/java/com/reactive/dailydish/ExampleUnitTest.java | c1fc34a918e2fba8b4f1e286cd7bcd90cd5e0b2d | [] | no_license | smoil-ali/DailyDish | a949ae116f1317edf8ff6bff8910f3ae493ef66c | a45cdef755547b48288fe81c94709f39611d2484 | refs/heads/master | 2023-04-15T16:49:11.847073 | 2021-04-25T12:28:34 | 2021-04-25T12:28:34 | 361,422,533 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package com.reactive.dailydish;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
0d4f4cc3c8abf71212c49922d9481dafc82831be | 64d383a904007a939eb90e9e1b3b85d5b1c67794 | /aliyun-java-sdk-vod/src/main/java/com/aliyuncs/vod/model/v20170321/SubmitAIVideoCensorJobRequest.java | 2fd28d0aea5a8365983477a3c284afbcd0f7a7dd | [
"Apache-2.0"
] | permissive | 15271091213/aliyun-openapi-java-sdk | ff76968c2f28a4e13b0002aea55af1de2c79fa4e | 9dabde5f53ae890769feb5fff3a69dfc566a974d | refs/heads/master | 2020-03-06T14:42:23.803542 | 2018-03-27T04:32:26 | 2018-03-27T04:32:26 | 126,940,526 | 1 | 0 | null | 2018-03-27T06:38:21 | 2018-03-27T06:38:21 | null | UTF-8 | Java | false | false | 3,309 | 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.aliyuncs.vod.model.v20170321;
import com.aliyuncs.RpcAcsRequest;
/**
* @author auto create
* @version
*/
public class SubmitAIVideoCensorJobRequest extends RpcAcsRequest<SubmitAIVideoCensorJobResponse> {
public SubmitAIVideoCensorJobRequest() {
super("vod", "2017-03-21", "SubmitAIVideoCensorJob", "vod");
}
private String userData;
private String resourceOwnerId;
private String aIVideoCensorConfig;
private String resourceOwnerAccount;
private String ownerAccount;
private String ownerId;
private String mediaId;
public String getUserData() {
return this.userData;
}
public void setUserData(String userData) {
this.userData = userData;
if(userData != null){
putQueryParameter("UserData", userData);
}
}
public String getResourceOwnerId() {
return this.resourceOwnerId;
}
public void setResourceOwnerId(String resourceOwnerId) {
this.resourceOwnerId = resourceOwnerId;
if(resourceOwnerId != null){
putQueryParameter("ResourceOwnerId", resourceOwnerId);
}
}
public String getAIVideoCensorConfig() {
return this.aIVideoCensorConfig;
}
public void setAIVideoCensorConfig(String aIVideoCensorConfig) {
this.aIVideoCensorConfig = aIVideoCensorConfig;
if(aIVideoCensorConfig != null){
putQueryParameter("AIVideoCensorConfig", aIVideoCensorConfig);
}
}
public String getResourceOwnerAccount() {
return this.resourceOwnerAccount;
}
public void setResourceOwnerAccount(String resourceOwnerAccount) {
this.resourceOwnerAccount = resourceOwnerAccount;
if(resourceOwnerAccount != null){
putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
}
public String getOwnerAccount() {
return this.ownerAccount;
}
public void setOwnerAccount(String ownerAccount) {
this.ownerAccount = ownerAccount;
if(ownerAccount != null){
putQueryParameter("OwnerAccount", ownerAccount);
}
}
public String getOwnerId() {
return this.ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
if(ownerId != null){
putQueryParameter("OwnerId", ownerId);
}
}
public String getMediaId() {
return this.mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
if(mediaId != null){
putQueryParameter("MediaId", mediaId);
}
}
@Override
public Class<SubmitAIVideoCensorJobResponse> getResponseClass() {
return SubmitAIVideoCensorJobResponse.class;
}
}
| [
"[email protected]"
] | |
4c693345120e3a0dd5d241b8c498ed837cb658ca | 9e6175752640891f54aad0dca18fd3bca13b6c45 | /src/main/java/io/jboot/web/cors/CORSInterceptorBuilder.java | 0c705d819ee2e92b5e914258ad0f886f1d5bdf97 | [
"Apache-2.0"
] | permissive | c2cn/jboot | 68a28b59d9ee3a413a746ac7cdfc71b51d5161b0 | 66b5b015f1024912c2f95133ae07b89ad00e07b6 | refs/heads/master | 2023-04-19T16:57:52.314575 | 2021-05-08T05:15:33 | 2021-05-08T05:15:33 | 288,644,695 | 0 | 0 | Apache-2.0 | 2021-05-08T05:15:33 | 2020-08-19T05:46:39 | null | UTF-8 | Java | false | false | 1,285 | java | /**
* Copyright (c) 2015-2021, Michael Yang 杨福海 ([email protected]).
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.web.cors;
import com.jfinal.ext.cors.EnableCORS;
import io.jboot.aop.InterceptorBuilder;
import io.jboot.aop.Interceptors;
import io.jboot.aop.annotation.AutoLoad;
import java.lang.reflect.Method;
/**
* @author michael yang ([email protected])
*/
@AutoLoad
public class CORSInterceptorBuilder implements InterceptorBuilder {
@Override
public void build(Class<?> targetClass, Method method, Interceptors interceptors) {
if (Util.isController(targetClass) && Util.hasAnnotation(targetClass, method, EnableCORS.class)) {
interceptors.addToFirst(CORSInterceptor.class);
}
}
}
| [
"[email protected]"
] | |
92df4cc4636b84c0448248195fa8af59b410ce8d | b8f4ab4dff3d0b44ebcbc1234c05277d16a61010 | /ApplicationAppApi/src/edu/hm/hs/application/api/communication/request/IContactInfoService.java | 94098a181663c552783d0d621576e02bf16ab824 | [] | no_license | st3ffwo3/application_app | 6c5416b8ad9b830b30dd77ad716ac0d9edc4b4ca | ade5e88cc6eb09cd8797aea6e869862c78c63c14 | refs/heads/master | 2021-01-01T15:44:45.520632 | 2013-01-20T21:09:51 | 2013-01-20T21:09:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,214 | java | package edu.hm.hs.application.api.communication.request;
import java.util.List;
import javax.ejb.Local;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import edu.hm.hs.application.api.object.resource.ContactInfo;
/**
* REST-Service für die ContactInfo.
*
* @author Stefan Wörner
*/
@Local
@Path( "/users/{user_id}/profile/contactinfos" )
@Produces( { MediaType.APPLICATION_JSON } )
@Consumes( { MediaType.APPLICATION_JSON } )
public interface IContactInfoService
{
/**
* Liste aller ContactInfos.
*
* @param userId
* Benutzeridentifikator
* @return ContactInfoliste
*/
@GET
@Path( "" )
List<ContactInfo> findAll( @PathParam( "user_id" ) long userId );
/**
* Erzeugt ein neues ContactInfo-Objekt.
*
* @param userId
* Benutzeridentifikator
* @param contactInfo
* ContactInfo
* @return erzeugtes Benutzer-Profil
*/
@POST
@Path( "" )
ContactInfo create( @PathParam( "user_id" ) long userId, ContactInfo contactInfo );
/**
* Liefert den ContactInfo.
*
* @param userId
* Benutzeridentifikator
* @param contactInfoId
* ContactInfoidentifikator
* @return ContactInfo
*/
@GET
@Path( "{cinfo_id}" )
ContactInfo find( @PathParam( "user_id" ) long userId, @PathParam( "cinfo_id" ) long contactInfoId );
/**
* Überschreibe ContactInfo.
*
* @param userId
* Benutzeridentifikator
* @param contactInfoId
* ContactInfoidentifikator
* @param contactInfo
* ContactInfo
* @return ContactInfo
*/
@PUT
@Path( "{cinfo_id}" )
ContactInfo update( @PathParam( "user_id" ) long userId, @PathParam( "cinfo_id" ) long contactInfoId, ContactInfo contactInfo );
/**
* ContactInfo löschen.
*
* @param userId
* Benutzeridentifikator
* @param contactInfoId
* ContactInfoidentifikator
*/
@DELETE
@Path( "{cinfo_id}" )
void remove( @PathParam( "user_id" ) long userId, @PathParam( "cinfo_id" ) long contactInfoId );
}
| [
"[email protected]"
] | |
2c3a7b5b13c91389f613f05605984432649def1d | a20d7596a06380f9af952f57061db17c09bf1727 | /coding-bo/src/main/java/com/alpha/coding/bo/validation/validator/ExcludeValidator.java | bddec772f6198e912cf9a67e52c5580efe96af40 | [
"Apache-2.0"
] | permissive | prettyhe/alpha-coding4j | 766604deeeb891c0f621994e0373196fc7419a1f | fe9687050245c8a26adfccaecb2d54abf2362b35 | refs/heads/master | 2023-08-08T11:41:08.544909 | 2023-08-01T02:17:53 | 2023-08-01T02:17:53 | 265,445,252 | 0 | 1 | Apache-2.0 | 2022-12-10T05:54:47 | 2020-05-20T03:57:15 | Java | UTF-8 | Java | false | false | 897 | java | package com.alpha.coding.bo.validation.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.alpha.coding.bo.validation.constraint.Exclude;
/**
* ExcludeValidator
*
* @version 1.0
* Date: 2020/12/17
*/
public class ExcludeValidator implements ConstraintValidator<Exclude, Object> {
private String[] excludes;
@Override
public void initialize(Exclude constraintAnnotation) {
this.excludes = constraintAnnotation.value();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null || excludes.length == 0) {
return true; // 为空时不校验
}
for (String in : excludes) {
if (in.equals(String.valueOf(value))) {
return false;
}
}
return true;
}
}
| [
"prettyhe"
] | prettyhe |
64b70a9b99345dca6edc19b04e9e837f5ddfc3ff | b6f61e4f09815086b6ebca584009f9808a9f4a31 | /app/src/main/java/com/yogeshborhade/shaktidevelopers/NavigationDrawer/NavDrawerItem.java | 8c1f9fabeb5a9c68b66caa76e1ecddfc310d93b4 | [] | no_license | kingYog/ShaktiDevelopers | 5d5840f5585cd99a39c174f28d1362a6886a9871 | 5f79658042b62a28b74be5503c49d0246b47be59 | refs/heads/master | 2020-03-28T13:11:24.731215 | 2018-09-11T20:16:06 | 2018-09-11T20:16:10 | 148,373,294 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 670 | java | package com.yogeshborhade.shaktidevelopers.NavigationDrawer;
/**
* Created by admin on 3/22/2018.
*/
public class NavDrawerItem {
private boolean showNotify;
private String title;
public NavDrawerItem() {
}
public NavDrawerItem(boolean showNotify, String title) {
this.showNotify = showNotify;
this.title = title;
}
public boolean isShowNotify() {
return showNotify;
}
public void setShowNotify(boolean showNotify) {
this.showNotify = showNotify;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| [
"[email protected]"
] | |
c03f15a99ef9781ff3ff9b686d5ab349f68c2ca7 | 4066351a0ae06134be1fbb27190f333f14e7a17d | /app/src/main/java/com/atguigu/atguigu_code/glide/activity/GlideRecyclerviewActivity.java | da6aa4b516caf4285693c6174d643d95fe3a9510 | [] | no_license | chenyou520/Atguigu_Code | 333eda6d4d7b5d4eca40151e5e246ecdb4dc04cc | a46aa8b3accdb21bcb57bd1c6d66be41f24c2ed4 | refs/heads/master | 2023-03-13T10:31:54.527197 | 2021-03-06T15:34:53 | 2021-03-06T15:34:53 | 293,490,007 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,215 | java | package com.atguigu.atguigu_code.glide.activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.atguigu.atguigu_code.R;
import com.atguigu.atguigu_code.glide.adapter.GlideRecyclerviewAdapter;
import butterknife.Bind;
import butterknife.ButterKnife;
public class GlideRecyclerviewActivity extends Activity {
@Bind(R.id.tv_titlebar_name)
TextView tvTitlebarName;
@Bind(R.id.rv_glide)
RecyclerView rvGlide;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glide_recyclerview);
ButterKnife.bind(this);
initData();
}
private void initData() {
tvTitlebarName.setText("Glide在RecyclerView中加载图片");
// 初始化Recyclerview
GlideRecyclerviewAdapter glideRecyclerviewAdapter = new GlideRecyclerviewAdapter(this);
rvGlide.setAdapter(glideRecyclerviewAdapter);
rvGlide.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
}
| [
"[email protected]"
] | |
daa2bff34d443a8bda40b1104ac80a21228ebe2c | 2c5e6c066297c7d394ec036c4912eaac52d3b144 | /mvvmfx-validation/src/test/java/de/saxsys/mvvmfx/utils/validation/cssvisualizer/CssVisualizerExampleApp.java | b104a367b8402089ea86793411653b17ac8c100b | [
"Apache-2.0"
] | permissive | sialcasa/mvvmFX | 49bacf5cb32657b09a0ccf4cacb0d1c4708c4407 | f195849ca98020ad74056991f147a05db9ce555a | refs/heads/develop | 2023-08-30T00:43:20.250600 | 2019-10-21T14:30:56 | 2019-10-21T14:30:56 | 12,903,179 | 512 | 160 | Apache-2.0 | 2022-06-24T02:09:43 | 2013-09-17T18:16:16 | Java | UTF-8 | Java | false | false | 574 | java | package de.saxsys.mvvmfx.utils.validation.cssvisualizer;
import de.saxsys.mvvmfx.FluentViewLoader;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class CssVisualizerExampleApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent parent = FluentViewLoader.fxmlView(CssVisualizerView.class).load().getView();
primaryStage.setScene(new Scene(parent));
primaryStage.show();
}
}
| [
"[email protected]"
] | |
891a1554364a0e4f3015e76e9f10de1c86dd7298 | 888d32aebf68bbe38aed66794371c9663fa5d004 | /app/src/test/java/com/example/android/contactapp/ExampleUnitTest.java | 07b5e72646e7d67d4e6f1c9aef171a1e993908a2 | [] | no_license | abhihansu/ContactApp | 24bac11c10f5950be84fb351e1d3b5ca781cd934 | eb0e89174ff3e00c0f6db362acdeb00f87228e46 | refs/heads/master | 2020-06-27T14:54:33.647899 | 2019-08-01T05:16:09 | 2019-08-01T05:16:09 | 199,981,596 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package com.example.android.contactapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
56be63d210824b8d5d8f60d032abf6e7f59cdcb7 | ad3d6b2a33875807dd445a4bc990103deb37aef1 | /StudyRoomProj/src/manager_p/panelDialog_p/LockerRoom.java | e32d0f8739c0dcb14aa864d98f9071722488bfb0 | [] | no_license | tmdghks7836/StdRoomProject | b7df255960a81f809213890b43c9227be833bfcd | 0101e1198f02009e7b34967a87cb677c502f5b20 | refs/heads/master | 2022-11-14T02:03:01.619155 | 2020-07-07T12:57:12 | 2020-07-07T12:57:12 | 273,134,677 | 0 | 2 | null | null | null | null | UHC | Java | false | false | 12,423 | java | package manager_p.panelDialog_p;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import client_p.ui_p.LockerMain;
import java.awt.BorderLayout;
public class LockerRoom extends JPanel {
TestFrame tfram;
public static void main(String[] args) {
JFrame f = new JFrame();
JTabbedPane tabbedPane = new JTabbedPane();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(40, 100, 1000, 800);
f.getContentPane().add(tabbedPane);
tabbedPane.add("사물함", new LockerRoom());
f.setVisible(true);
}
public LockerRoom() {
setLayout(new BorderLayout(0, 0));
// public LockerRoom(TestFrame tfram) {
// this.tfram = tfram;
// this.tfram.tabbedPane.addTab("사물함 관리", this);
JPanel panel_1_1 = new JPanel();
add(panel_1_1);
GridBagLayout gbl_panel_1_1 = new GridBagLayout();
gbl_panel_1_1.columnWidths = new int[] { 337, 618, 0 };
gbl_panel_1_1.rowHeights = new int[] { 717, 0 };
gbl_panel_1_1.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_panel_1_1.rowWeights = new double[] { 1.0, Double.MIN_VALUE };
panel_1_1.setLayout(gbl_panel_1_1);
JPanel panel_7_1_1 = new JPanel();
GridBagConstraints gbc_panel_7_1_1 = new GridBagConstraints();
gbc_panel_7_1_1.insets = new Insets(0, 0, 0, 5);
gbc_panel_7_1_1.fill = GridBagConstraints.BOTH;
gbc_panel_7_1_1.gridx = 0;
gbc_panel_7_1_1.gridy = 0;
panel_1_1.add(panel_7_1_1, gbc_panel_7_1_1);
GridBagLayout gbl_panel_7_1_1 = new GridBagLayout();
gbl_panel_7_1_1.columnWidths = new int[]{112, 0};
gbl_panel_7_1_1.rowHeights = new int[]{88, 0, 30, 0, 30, 0, 30, 0, 30, 0, 87, 0, 0, 0};
gbl_panel_7_1_1.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel_7_1_1.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
panel_7_1_1.setLayout(gbl_panel_7_1_1);
JLabel lblNewLabel_6_1 = new JLabel("\uC0AC\uBB3C\uD568 \uC815\uBCF4");
lblNewLabel_6_1.setFont(new Font("휴먼엑스포", Font.PLAIN, 35));
GridBagConstraints gbc_lblNewLabel_6_1 = new GridBagConstraints();
gbc_lblNewLabel_6_1.fill = GridBagConstraints.VERTICAL;
gbc_lblNewLabel_6_1.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_6_1.gridx = 0;
gbc_lblNewLabel_6_1.gridy = 1;
panel_7_1_1.add(lblNewLabel_6_1, gbc_lblNewLabel_6_1);
JPanel panel_23 = new JPanel();
GridBagConstraints gbc_panel_23 = new GridBagConstraints();
gbc_panel_23.insets = new Insets(0, 0, 5, 0);
gbc_panel_23.fill = GridBagConstraints.BOTH;
gbc_panel_23.gridx = 0;
gbc_panel_23.gridy = 3;
panel_7_1_1.add(panel_23, gbc_panel_23);
JLabel lblNewLabel_7_2_1 = new JLabel(" \uC0AC\uBB3C\uD568 ");
lblNewLabel_7_2_1.setFont(new Font("새굴림", Font.BOLD, 20));
panel_23.add(lblNewLabel_7_2_1);
JLabel lblNewLabel_7_2_2 = new JLabel("1\uBC88");
lblNewLabel_7_2_2.setFont(new Font("새굴림", Font.BOLD, 20));
panel_23.add(lblNewLabel_7_2_2);
JPanel panel_16_2 = new JPanel();
GridBagConstraints gbc_panel_16_2 = new GridBagConstraints();
gbc_panel_16_2.insets = new Insets(0, 0, 5, 0);
gbc_panel_16_2.fill = GridBagConstraints.BOTH;
gbc_panel_16_2.gridx = 0;
gbc_panel_16_2.gridy = 5;
panel_7_1_1.add(panel_16_2, gbc_panel_16_2);
GridBagLayout gbl_panel_16_2 = new GridBagLayout();
gbl_panel_16_2.columnWidths = new int[]{210, 0, 0};
gbl_panel_16_2.rowHeights = new int[]{0, 0};
gbl_panel_16_2.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel_16_2.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel_16_2.setLayout(gbl_panel_16_2);
JLabel lblNewLabel_7_2 = new JLabel(" \uC0AC\uBB3C\uD568 \uC0AC\uC6A9\uC790 \uC774\uB984:");
lblNewLabel_7_2.setFont(new Font("새굴림", Font.BOLD, 20));
GridBagConstraints gbc_lblNewLabel_7_2 = new GridBagConstraints();
gbc_lblNewLabel_7_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_7_2.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_7_2.gridx = 0;
gbc_lblNewLabel_7_2.gridy = 0;
panel_16_2.add(lblNewLabel_7_2, gbc_lblNewLabel_7_2);
JLabel lbLockUser = new JLabel("");
GridBagConstraints gbc_lbLockUser = new GridBagConstraints();
gbc_lbLockUser.anchor = GridBagConstraints.WEST;
gbc_lbLockUser.gridx = 1;
gbc_lbLockUser.gridy = 0;
panel_16_2.add(lbLockUser, gbc_lbLockUser);
JPanel panel_16 = new JPanel();
GridBagConstraints gbc_panel_16 = new GridBagConstraints();
gbc_panel_16.fill = GridBagConstraints.BOTH;
gbc_panel_16.insets = new Insets(0, 0, 5, 0);
gbc_panel_16.gridx = 0;
gbc_panel_16.gridy = 7;
panel_7_1_1.add(panel_16, gbc_panel_16);
GridBagLayout gbl_panel_16 = new GridBagLayout();
gbl_panel_16.columnWidths = new int[]{210, 0, 0};
gbl_panel_16.rowHeights = new int[]{0, 0};
gbl_panel_16.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel_16.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel_16.setLayout(gbl_panel_16);
JLabel lblNewLabel_7 = new JLabel("\uC0AC\uBB3C\uD568 \uC774\uC6A9\uC5EC\uBD80:");
lblNewLabel_7.setFont(new Font("새굴림", Font.BOLD, 20));
GridBagConstraints gbc_lblNewLabel_7 = new GridBagConstraints();
gbc_lblNewLabel_7.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_7.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_7.gridx = 0;
gbc_lblNewLabel_7.gridy = 0;
panel_16.add(lblNewLabel_7, gbc_lblNewLabel_7);
JLabel lbLockIsUsing = new JLabel("");
GridBagConstraints gbc_lbLockIsUsing = new GridBagConstraints();
gbc_lbLockIsUsing.anchor = GridBagConstraints.WEST;
gbc_lbLockIsUsing.gridx = 1;
gbc_lbLockIsUsing.gridy = 0;
panel_16.add(lbLockIsUsing, gbc_lbLockIsUsing);
JPanel panel_16_1 = new JPanel();
GridBagConstraints gbc_panel_16_1 = new GridBagConstraints();
gbc_panel_16_1.fill = GridBagConstraints.BOTH;
gbc_panel_16_1.insets = new Insets(0, 0, 5, 0);
gbc_panel_16_1.gridx = 0;
gbc_panel_16_1.gridy = 9;
panel_7_1_1.add(panel_16_1, gbc_panel_16_1);
GridBagLayout gbl_panel_16_1 = new GridBagLayout();
gbl_panel_16_1.columnWidths = new int[]{210, 0, 0};
gbl_panel_16_1.rowHeights = new int[]{0, 0};
gbl_panel_16_1.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel_16_1.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel_16_1.setLayout(gbl_panel_16_1);
JLabel lblNewLabel_7_1 = new JLabel("\uC0AC\uBB3C\uD568 \uBE44\uBC00\uBC88\uD638:");
lblNewLabel_7_1.setFont(new Font("새굴림", Font.BOLD, 20));
GridBagConstraints gbc_lblNewLabel_7_1 = new GridBagConstraints();
gbc_lblNewLabel_7_1.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_7_1.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel_7_1.gridx = 0;
gbc_lblNewLabel_7_1.gridy = 0;
panel_16_1.add(lblNewLabel_7_1, gbc_lblNewLabel_7_1);
JLabel lbLockPw = new JLabel("");
GridBagConstraints gbc_lbLockPw = new GridBagConstraints();
gbc_lbLockPw.anchor = GridBagConstraints.WEST;
gbc_lbLockPw.gridx = 1;
gbc_lbLockPw.gridy = 0;
panel_16_1.add(lbLockPw, gbc_lbLockPw);
JPanel panel_11 = new JPanel();
GridBagConstraints gbc_panel_11 = new GridBagConstraints();
gbc_panel_11.fill = GridBagConstraints.VERTICAL;
gbc_panel_11.gridx = 1;
gbc_panel_11.gridy = 0;
panel_1_1.add(panel_11, gbc_panel_11);
GridBagLayout gbl_panel_11 = new GridBagLayout();
gbl_panel_11.columnWidths = new int[] { 39, 173, 136, 145, 15, 0 };
gbl_panel_11.rowHeights = new int[] { 150, 0, 0, 0, 0 };
gbl_panel_11.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
gbl_panel_11.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel_11.setLayout(gbl_panel_11);
JButton btnNewButton_4_1_1 = new JButton("\uC0AC\uBB3C\uD568 1\uBC88");
btnNewButton_4_1_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_4_1_1.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1_1.setFont(new Font("새굴림", Font.BOLD, 25));
GridBagConstraints gbc_btnNewButton_4_1_1 = new GridBagConstraints();
gbc_btnNewButton_4_1_1.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_4_1_1.gridx = 1;
gbc_btnNewButton_4_1_1.gridy = 1;
panel_11.add(btnNewButton_4_1_1, gbc_btnNewButton_4_1_1);
JButton btnNewButton_4_1 = new JButton("\uC0AC\uBB3C\uD568 2\uBC88");
btnNewButton_4_1.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_1 = new GridBagConstraints();
gbc_btnNewButton_4_1.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_4_1.gridx = 2;
gbc_btnNewButton_4_1.gridy = 1;
panel_11.add(btnNewButton_4_1, gbc_btnNewButton_4_1);
JButton btnNewButton_4_2 = new JButton("\uC0AC\uBB3C\uD568 3\uBC88");
btnNewButton_4_2.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_2.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_2 = new GridBagConstraints();
gbc_btnNewButton_4_2.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_4_2.gridx = 3;
gbc_btnNewButton_4_2.gridy = 1;
panel_11.add(btnNewButton_4_2, gbc_btnNewButton_4_2);
JButton btnNewButton_4_1_2 = new JButton("\uC0AC\uBB3C\uD568 4\uBC88");
btnNewButton_4_1_2.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1_2.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_1_2 = new GridBagConstraints();
gbc_btnNewButton_4_1_2.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_4_1_2.gridx = 1;
gbc_btnNewButton_4_1_2.gridy = 2;
panel_11.add(btnNewButton_4_1_2, gbc_btnNewButton_4_1_2);
JButton btnNewButton_4_3 = new JButton("\uC0AC\uBB3C\uD568 5\uBC88");
btnNewButton_4_3.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_3.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_3 = new GridBagConstraints();
gbc_btnNewButton_4_3.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_4_3.gridx = 2;
gbc_btnNewButton_4_3.gridy = 2;
panel_11.add(btnNewButton_4_3, gbc_btnNewButton_4_3);
JButton btnNewButton_4_1_3 = new JButton("\uC0AC\uBB3C\uD568 6\uBC88");
btnNewButton_4_1_3.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1_3.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_1_3 = new GridBagConstraints();
gbc_btnNewButton_4_1_3.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_4_1_3.gridx = 3;
gbc_btnNewButton_4_1_3.gridy = 2;
panel_11.add(btnNewButton_4_1_3, gbc_btnNewButton_4_1_3);
JButton btnNewButton_4_1_4 = new JButton("\uC0AC\uBB3C\uD568 7\uBC88");
btnNewButton_4_1_4.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1_4.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_1_4 = new GridBagConstraints();
gbc_btnNewButton_4_1_4.insets = new Insets(0, 0, 0, 5);
gbc_btnNewButton_4_1_4.gridx = 1;
gbc_btnNewButton_4_1_4.gridy = 3;
panel_11.add(btnNewButton_4_1_4, gbc_btnNewButton_4_1_4);
JButton btnNewButton_4_1_5 = new JButton("\uC0AC\uBB3C\uD568 8\uBC88");
btnNewButton_4_1_5.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1_5.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_1_5 = new GridBagConstraints();
gbc_btnNewButton_4_1_5.insets = new Insets(0, 0, 0, 5);
gbc_btnNewButton_4_1_5.gridx = 2;
gbc_btnNewButton_4_1_5.gridy = 3;
panel_11.add(btnNewButton_4_1_5, gbc_btnNewButton_4_1_5);
JButton btnNewButton_4_1_6 = new JButton("\uC0AC\uBB3C\uD568 9\uBC88");
btnNewButton_4_1_6.setPreferredSize(new Dimension(170, 126));
btnNewButton_4_1_6.setFont(new Font("새굴림", Font.BOLD, 26));
GridBagConstraints gbc_btnNewButton_4_1_6 = new GridBagConstraints();
gbc_btnNewButton_4_1_6.insets = new Insets(0, 0, 0, 5);
gbc_btnNewButton_4_1_6.gridx = 3;
gbc_btnNewButton_4_1_6.gridy = 3;
panel_11.add(btnNewButton_4_1_6, gbc_btnNewButton_4_1_6);
Dimension size1 = new Dimension();// 사이즈를 지정하기 위한 객체 생성
size1.setSize(900, 1000);// 객체의 사이즈를 지정
LockerMain lockerMain = new LockerMain();
lockerMain.setPreferredSize(size1);
}
}
| [
"[email protected]"
] | |
1525588e08e47df6d0ee673220aac1affc33d366 | f8191c8760bf5c830d642dfe94d5bb1872fed429 | /src/main/java/com/tfg/dao/util/DuplicateInstanceException.java | 30a0695d784bd23e2ba0681b6200f103eccc2f5d | [] | no_license | javilb26/Service | 043dbb13edac82778df0e3f75b6ff06a58110dae | 8be42e4d8b0c897df5600e90b511bb6ed75e9d97 | refs/heads/master | 2020-12-09T14:32:11.375186 | 2016-08-14T19:09:36 | 2016-08-14T19:09:36 | 53,069,735 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 260 | java | package com.tfg.dao.util;
@SuppressWarnings("serial")
public class DuplicateInstanceException extends InstanceException {
public DuplicateInstanceException(Object key, String className) {
super("Duplicate instance", key, className);
}
}
| [
"[email protected]"
] | |
ecbe8262d3918c1259f6a31bf5cad18acd4f4f05 | eb4efe398daf95d71c32a4cdb6aa7e8ef57cb250 | /src/paternmatch/KMPAlgo.java | c6026ffe81a3c59960ae12d827286cf5dbeb368d | [] | no_license | tosyngy/String-Pattern-Match | 62005dd63be446e4e0629d2d96c3c03abd587ded | 4282466b3967c780b3c4bcd38bc699960dc01220 | refs/heads/master | 2020-04-15T15:42:20.221549 | 2019-01-09T07:10:42 | 2019-01-09T07:10:42 | 164,805,248 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,036 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package paternmatch;
public class KMPAlgo {
/**
* Pre processes the pattern array based on proper prefixes and proper
* suffixes at every position of the array
*
* @param ptrn word that is to be searched in the search string
* @return partial match table which indicates
*/
public int[] preProcessPattern(char[] ptrn) {
int i = 0, j = -1;
int ptrnLen = ptrn.length;
int[] b = new int[ptrnLen + 1];
b[i] = j;
while (i < ptrnLen) {
while (j >= 0 && ptrn[i] != ptrn[j]) {
// if there is mismatch consider next widest border
j = b[j];
}
i++;
j++;
b[i] = j;
}
for (int c : b) {
System.out.println(c);
}
// print pettern, partial match table and index
System.out
.println("printing pattern, partial match table, and its index");
System.out.print(" ");
for (char c : ptrn) {
System.out.print(c + " ");
}
System.out.println(" ");
for (int tmp : b) {
System.out.print(tmp + " ");
}
System.out.print("\n ");
for (int l = 0; l < ptrn.length; l++) {
System.out.print(l + " ");
}
System.out.println();
return b;
}
/**
* Based on the pre processed array, search for the pattern in the text
*
* @param text text over which search happens
* @param ptrn pattern that is to be searched
*/
public void searchSubString(char[] text, char[] ptrn) {
int i = 0, j = 0;
// pattern and text lengths
int ptrnLen = ptrn.length;
int txtLen = text.length;
// initialize new array and preprocess the pattern
int[] b = preProcessPattern(ptrn);
while (i < txtLen) {
while (j >= 0 && text[i] != ptrn[j]) {
System.out.println("Mismatch happened, between text char "
+ text[i] + " and pattern char " + ptrn[j]
+ ", \nhence jumping the value of " + "j from " + j
+ " to " + b[j] + " at text index i at " + i
+ " based on partial match table");
j = b[j];
}
i++;
j++;
// a match is found
if (j == ptrnLen) {
System.out.println("FOUND SUBSTRING AT i " + i + " and index:"
+ (i - ptrnLen));
System.out.println("Setting j from " + j + " to " + b[j]);
j = b[j];
}
}
}
// only for test purposes
public static void main(String[] args) {
KMPAlgo stm = new KMPAlgo();
// pattern
char[] ptrn = "io".toCharArray();
//char[] ptrn = "abcabdabc".toCharArray();
String test;
char[] text = "dimesion".toCharArray();
System.out.print(" ");
for (char c : text) {
System.out.print(c + " ");
}
System.out.println();
// search for pattern in the string
stm.searchSubString(text, ptrn);
}
}
/**
*
* @author akisft-xisys
*/
| [
"[email protected]"
] | |
45d59f24df97da25698d91fc3647ae28cd2f5ad5 | 528baeee135eafca3406b1036f00653ad140f17a | /ViewWindow.java | 6ac25d3b481b5bee67487ee18a87ba1365d484e4 | [] | no_license | JonathanKurish/Watchlist | 4e4c9f4e7b48490870f112bd7a1e499ffc30f4b8 | 5c29ead06a0d70034f9f892a4cae647c9f9e878c | refs/heads/master | 2020-06-04T07:17:03.848933 | 2014-06-12T12:07:00 | 2014-06-12T12:07:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,099 | java | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.net.*;
public class ViewWindow extends JDialog {
JLabel stockSymbol, currentPrice, MACDpos, MACDneg, GC, DC,
EMA8, EMA12, EMA20, SMA50, SMA200, highvol, OB, OS, RSIover, RSIunder,
high, low,
targetPrice, MACDline, MACDtrigger, GC2, DC2, EMA82, EMA122, EMA202,
SMA502, SMA2002, highvol2, OB2, OS2, rsi;
JButton changeCriteria;
JPanel line1;
private Watchlist watchlist;
private Frame frame;
public static Stock stock;
public ViewWindow(Frame frame, Watchlist parent) {
super(frame, "View Stock", true);
watchlist = parent;
Container pane = this.getContentPane();
pane.setLayout(new GridLayout(10,2,2,2));
line1 = new JPanel();
line1.setLayout(new GridLayout(1,1));
line1.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
line1.setBackground(Color.WHITE);
stockSymbol = new JLabel("");
stockSymbol.setHorizontalAlignment(JLabel.CENTER);
stockSymbol.setFont(new Font("Arial", Font.PLAIN, 32));
line1.add(stockSymbol);
pane.add(line1);
JPanel line2 = new JPanel();
line2.setLayout(new GridLayout(1,2));
currentPrice = new JLabel("Current Price: ");
line2.add(currentPrice);
targetPrice = new JLabel("Target Price: ");
line2.add(targetPrice);
pane.add(line2);
JPanel line25 = new JPanel();
line25.setLayout(new GridLayout(1,2));
high = new JLabel("High of day: ");
line25.add(high);
low = new JLabel("Low of day: ");
line25.add(low);
pane.add(line25);
JPanel line3 = new JPanel();
line3.setLayout(new GridLayout(2,2));
MACDpos = new JLabel("MACDpos set: ");
line3.add(MACDpos);
MACDline = new JLabel("MACDline: ");
line3.add(MACDline);
MACDneg = new JLabel("MACDneg set: ");
line3.add(MACDneg);
MACDtrigger = new JLabel("MACDtrigger: ");
line3.add(MACDtrigger);
pane.add(line3);
JPanel line4 = new JPanel();
line4.setLayout(new GridLayout(2,2));
GC = new JLabel("Golden Cross set: ");
line4.add(GC);
//current goldencross value
DC = new JLabel("Death Cross set: ");
line4.add(DC);
//current deathcross value
pane.add(line4);
JPanel line5 = new JPanel();
line5.setLayout(new GridLayout(3,2));
EMA8 = new JLabel("Target EMA8: ");
line5.add(EMA8);
EMA82 = new JLabel("Current EMA8: ");
line5.add(EMA82);
EMA12 = new JLabel("Target EMA12: ");
line5.add(EMA12);
EMA122 = new JLabel("Current EMA12: ");
line5.add(EMA122);
EMA20 = new JLabel("Target EMA20: ");
line5.add(EMA20);
EMA202 = new JLabel("Current EMA20: ");
line5.add(EMA202);
pane.add(line5);
JPanel line6 = new JPanel();
line6.setLayout(new GridLayout(2,2));
SMA50 = new JLabel("Target SMA50: ");
line6.add(SMA50);
SMA502 = new JLabel("Current SMA50: ");
line6.add(SMA502);
SMA200 = new JLabel("Target SMA200: ");
line6.add(SMA200);
SMA2002 = new JLabel("Current SMA200: ");
line6.add(SMA2002);
pane.add(line6);
JPanel line7 = new JPanel();
line7.setLayout(new GridLayout(3,2));
highvol = new JLabel("High Volume set: ");
line7.add(highvol);
highvol2 = new JLabel("Current Volume: ");
line7.add(highvol2);
OB = new JLabel("Overbought set: ");
line7.add(OB);
rsi = new JLabel("Current rsi: ");
line7.add(rsi);
OS = new JLabel("Oversold set: ");
line7.add(OS);
pane.add(line7);
JPanel line8 = new JPanel();
line8.setLayout(new GridLayout(2,2));
RSIover = new JLabel("Target RSIover: ");
line8.add(RSIover);
RSIunder = new JLabel("Target RSIunder: ");
line8.add(RSIunder);
pane.add(line8);
JPanel line9 = new JPanel();
line9.setLayout(new FlowLayout());
changeCriteria = new JButton("Change Criteria");
line9.add(changeCriteria);
pane.add(line9);
ChangeClass cc = new ChangeClass();
changeCriteria.addActionListener(cc);
}
public class ChangeClass implements ActionListener {
public void actionPerformed(ActionEvent cc) {
try {
setVisible(false);
watchlist.openAddAsChange(stock);
} catch (Exception ex) {}
}
}
} | [
"[email protected]"
] | |
be1fc6332c8c281167910df4086e1287f578d860 | 9ab654aaf3116ddb4122941573ad07692114b8ef | /house-biz/src/main/java/com/xunqi/house/biz/service/HouseService.java | 9d3c392178811f86093c88a8662a9c607c84e7e7 | [] | no_license | GitJie111/SpringCloud-House | 6b6a4857473dc9aa8bfd0f9702d2bdd0de096fb1 | 756b52a4973ad20ae2f9cbd1102bb52fb3847697 | refs/heads/master | 2022-09-17T14:54:13.460443 | 2020-04-08T10:53:54 | 2020-04-08T10:53:54 | 254,082,487 | 0 | 0 | null | 2022-09-01T23:23:19 | 2020-04-08T12:33:13 | CSS | UTF-8 | Java | false | false | 1,839 | java | package com.xunqi.house.biz.service;
import com.xunqi.house.common.enums.HouseUserType;
import com.xunqi.house.common.page.PageData;
import com.xunqi.house.common.page.PageParams;
import com.xunqi.house.common.pojo.*;
import java.util.List;
/**
* @Created with IntelliJ IDEA.
* @author: 夏沫止水
* @create: 2020-04-02 08:44
**/
public interface HouseService {
/**
* 分页多条件查询房屋列表
* @param query
* @param pageParams
* @return
*/
PageData<House> queryHouse(House query, PageParams pageParams);
/**
* 查询头像图片地址
* @param query
* @param pageParams
* @return
*/
public List<House> queryAndSetImg(House query, PageParams pageParams);
/**
* 根据id查询房屋信息
* @param id
* @return
*/
House queryOneHouse(Long id);
/**
* 添加用户留言信息
* @param userMsg
*/
void addUserMsg(UserMsg userMsg);
public HouseUser getHouseUser(Long houseId);
/**
* 查询全部小区列表
* @return
*/
List<Community> getAllCommunitys();
/**
* 1.添加房产图片
* 2.添加户型图片
* 3.插入房产信息
* 4.绑定用户到房产的关系
* @param house
* @param user
*/
void addHouse(House house, User user);
/**
* 绑定用户信息
* @param houseId
* @param userId
* @param isCollect
*/
public void bindUser2House(Long houseId, Long userId, boolean isCollect);
/**
* 更新星级
* @param id
* @param rating
*/
void updateRating(Long id, Double rating);
/**
* 解绑收藏(删除收藏)
* @param id
* @param userId
* @param type
*/
void unbindUser2House(Long id, Long userId, HouseUserType type);
}
| [
"[email protected]"
] | |
3f4e3e62d61ac62060e441377a1c53d689a0ea7d | 97f044c207a0bc1bf45689fce6766f1667d6706a | /android/Monitor/app/src/main/java/com/wenjiehe/monitor/ChooseActivity.java | 4b6745edffd6909e08e296600973199ef93e52da | [
"MIT"
] | permissive | starsight/hackathon | 1298f3d7935a33efc47f6df205a1d78471e68d12 | 7101a8348b041609378ba2d7af66ffdc934ed072 | refs/heads/master | 2021-04-22T13:26:33.054464 | 2016-12-09T12:33:14 | 2016-12-09T12:33:14 | 75,475,722 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 14,310 | java | package com.wenjiehe.monitor;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class ChooseActivity extends BaseActivity {
Button bt_login;
Button bt_register;
//TextView tv_loginForgetPassword;//login
EditText et_loginUserName, et_loginPassword;
EditText et_regUserName, et_regPassword;//register
Button bt_chooseLogin, bt_chooseRegister;//启动选择登陆or注册
ImageView iv_choose_icon;
boolean isEnterLoginOrReg = false;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose);
//AVAnalytics.trackAppOpened(getIntent());
//AVService.initPushService(this);
bt_chooseLogin = (Button) findViewById(R.id.bt_choose_login);
bt_chooseRegister = (Button) findViewById(R.id.bt_choose_register);
iv_choose_icon = (ImageView) findViewById(R.id.iv_choose_icon);
if (getUserId() != null) {
Intent mainIntent = new Intent(activity, MainActivity.class);
mainIntent.putExtra("username", getUserName());
startActivity(mainIntent);
activity.finish();
}
bt_chooseLogin.setOnClickListener(chooseLoginListener);
bt_chooseRegister.setOnClickListener(chooseRegisterListener);
bt_chooseRegister.setOnTouchListener(regTouchListener);
bt_chooseLogin.setOnTouchListener(loginTouchListener);
}
View.OnTouchListener loginTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.print(bt_chooseRegister.getY());
System.out.print("---" + event.getY());
//按钮按下逻辑
bt_chooseLogin.setTextColor(getResources().getColor(R.color.white));
break;
case MotionEvent.ACTION_MOVE:
if (event.getY() > 25 + bt_chooseLogin.getHeight() || event.getY() < -25) {
bt_chooseLogin.setTextColor(getResources().getColor(R.color.black));
}
if (event.getX() > 25 + bt_chooseLogin.getWidth() || event.getX() < -25) {
bt_chooseLogin.setTextColor(getResources().getColor(R.color.black));
}
break;
}
return false;
}
};
View.OnTouchListener regTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//按钮按下逻辑
bt_chooseRegister.setTextColor(getResources().getColor(R.color.white));
break;
case MotionEvent.ACTION_MOVE:
if (event.getY() > 25 + bt_chooseRegister.getHeight() || event.getY() < -25) {
bt_chooseRegister.setTextColor(getResources().getColor(R.color.black));
}
if (event.getX() > 25 + bt_chooseRegister.getWidth() || event.getX() < -25) {
bt_chooseRegister.setTextColor(getResources().getColor(R.color.black));
}
break;
case MotionEvent.ACTION_UP:
bt_chooseRegister.setTextColor(getResources().getColor(R.color.black));
//按钮弹起逻辑
break;
}
return false;
}
};
View.OnClickListener loginListener = new View.OnClickListener() {
@SuppressLint("NewApi")
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void onClick(View arg0) {
String username = et_loginUserName.getText().toString();
if (username.equals("")) {
showUserNameEmptyError();
return;
}
String passwd = et_loginPassword.getText().toString();
if (passwd.isEmpty()) {
showUserPasswordEmptyError();
return;
}
progressDialogShow();
login(username, passwd);
}
};
//选择登陆
View.OnClickListener chooseLoginListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//iv_choose_icon.setVisibility(View.GONE);
//bt_chooseLogin.setBackground(R.color.choose_log_reg_background);
isEnterLoginOrReg = true;
setContentView(R.layout.choose_login);
bt_login = (Button) findViewById(R.id.bt_login);
//tv_loginForgetPassword = (TextView) findViewById(R.id.tv_loginForgetPassword);
et_loginUserName = (EditText) findViewById(R.id.et_loginUserName);
et_loginPassword = (EditText) findViewById(R.id.et_loginPassword);
bt_login.setOnClickListener(loginListener);
//tv_loginForgetPassword.setOnClickListener(forgetPasswordListener);
}
};
//选择注册
View.OnClickListener chooseRegisterListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
isEnterLoginOrReg = true;
setContentView(R.layout.choose_register);
bt_register = (Button) findViewById(R.id.bt_register);
et_regUserName = (EditText) findViewById(R.id.et_regUserName);
et_regPassword = (EditText) findViewById(R.id.et_regPasswd);
bt_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!et_regUserName.getText().toString().isEmpty()) {
if (!et_regPassword.getText().toString().isEmpty()) {
progressDialogShow();
register(et_regUserName.getText().toString(), et_regPassword.getText().toString());
} else {
showError(activity
.getString(R.string.error_register_password_null));
}
} else {
showError(activity
.getString(R.string.error_register_user_name_null));
}
}
});
}
};
private void progressDialogDismiss() {
if (progressDialog != null)
progressDialog.dismiss();
}
private void progressDialogShow() {
progressDialog = ProgressDialog
.show(activity,
activity.getResources().getText(
R.string.dialog_message_title),
activity.getResources().getText(
R.string.dialog_text_wait), true, false);
}
private void showLoginError() {
new AlertDialog.Builder(activity)
.setTitle(
activity.getResources().getString(
R.string.dialog_message_title))
.setMessage(
activity.getResources().getString(
R.string.error_login_error))
.setNegativeButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
}
private void showUserPasswordEmptyError() {
new AlertDialog.Builder(activity)
.setTitle(
activity.getResources().getString(
R.string.dialog_error_title))
.setMessage(
activity.getResources().getString(
R.string.error_register_password_null))
.setNegativeButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
}
private void showUserNameEmptyError() {
new AlertDialog.Builder(activity)
.setTitle(
activity.getResources().getString(
R.string.dialog_error_title))
.setMessage(
activity.getResources().getString(
R.string.error_register_user_name_null))
.setNegativeButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
}
public void login(final String uname, final String upasswd) {
new Thread() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder().get()
.url("http://123.206.214.17:8080/Supervisor/user.do?method=login&uname="+uname+"&upwd="+upasswd+"&userRight=1")
.build();
try {
okHttpClient.newCall(request).execute();
//// TODO: 2016/12/9
Message m = new Message();
m.what = IS_LOG_OK;
handler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
public void register(final String uname, final String upasswd) {
//Log.d("register",uname+upasswd);
new Thread() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder().get()
.url("http://123.206.214.17:8080/Supervisor/user.do?method=register&uname=" + uname + "&upwd=" + upasswd)
.build();
try {
okHttpClient.newCall(request).execute();
//// TODO: 2016/12/9
Message m = new Message();
m.what = IS_REG_OK;
handler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void showRegisterSuccess() {
new AlertDialog.Builder(activity)
.setTitle(
activity.getResources().getString(
R.string.dialog_message_title))
.setMessage(
activity.getResources().getString(
R.string.success_register_success))
.setNegativeButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
}
@Override
public void onBackPressed() {
//
if (isEnterLoginOrReg == true) {
setContentView(R.layout.activity_choose);
bt_chooseLogin = (Button) findViewById(R.id.bt_choose_login);
bt_chooseRegister = (Button) findViewById(R.id.bt_choose_register);
iv_choose_icon = (ImageView) findViewById(R.id.iv_choose_icon);
//bt_chooseRegister.setVisibility(View.VISIBLE);
//Button bt_chooseRegister2 = (Button) findViewById(R.id.bt_choose_register2);
//bt_chooseRegister2.setVisibility(View.GONE);
bt_chooseLogin.setOnClickListener(chooseLoginListener);
bt_chooseRegister.setOnClickListener(chooseRegisterListener);
bt_chooseRegister.setOnTouchListener(regTouchListener);
bt_chooseLogin.setOnTouchListener(loginTouchListener);
} else
super.onBackPressed();
isEnterLoginOrReg = false;
//System.out.println("按下了back键 onBackPressed()");
}
public final static int IS_REG_OK = 0;
public final static int IS_LOG_OK = 1;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case IS_REG_OK:
progressDialogDismiss();
Intent intent = new Intent(ChooseActivity.this, MainActivity.class);
startActivity(intent);
finish();
break;
case IS_LOG_OK:
progressDialogDismiss();
Intent intent2 = new Intent(ChooseActivity.this, MainActivity.class);
startActivity(intent2);
finish();
break;
default:
break;
}
}
};
}
| [
"[email protected]"
] | |
412a3a5dfa6d089f1b79c644bcbf9c90515115ec | 0361509e7e9d49c1d99c5c30acee07b7f00d95f9 | /src/main/java/com/atguigu/study/juc/AQSDemo.java | 8f3867d6e6d390d56af7deb45ffb0178d678e1e7 | [] | no_license | huzhipeng123/thread | 64bbb09f193aead55c7969ecd012f7d2d3e60224 | b46007646bb6d8cf98190e7e3ad902e05a20968b | refs/heads/master | 2023-04-21T02:51:52.596757 | 2021-04-18T13:32:06 | 2021-04-18T13:32:06 | 346,738,085 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,662 | java | package com.atguigu.study.juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author huzhpm
* @Date 2021/4/3 14:43
* @Version 1.0
* @Content 抽象的队列同步器
*/
public class AQSDemo {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"thread \t----come in");
try {
TimeUnit.MINUTES.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}finally {
lock.unlock();
}
}, "A").start();
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"thread \t----come in");
try {
TimeUnit.MINUTES.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}finally {
lock.unlock();
}
}, "B").start();
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"thread \t----come in");
try {
TimeUnit.MINUTES.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}finally {
lock.unlock();
}
}, "B").start();
}
}
| [
"[email protected]"
] | |
840c558955ab8dd82353998c255d307eed1dde61 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/14/14_c28ba180ec842856c39d1c778be7f8682097c05f/NewWorklogNotificationBuilder/14_c28ba180ec842856c39d1c778be7f8682097c05f_NewWorklogNotificationBuilder_t.java | f2994237f20636327487965bd0aebcf0aa5f00a1 | [] | 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 | 2,737 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tadamski.arij.worklog.notification;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import com.tadamski.arij.R;
import com.tadamski.arij.account.service.LoginInfo;
import com.tadamski.arij.issue.dao.Issue;
import com.tadamski.arij.worklog.activity.NewWorklogActivity_;
import java.text.DateFormat;
import java.util.Date;
/**
* @author tmszdmsk
*/
public class NewWorklogNotificationBuilder {
private static final DateFormat TIME_FORMAT = DateFormat.getTimeInstance(DateFormat.SHORT);
private static int NOTIFICATION_ID = 12366234;
private static int PENDING_REQUETS_ID = 0;
public static void createNotification(Context ctx, Issue issue, Date startDate, LoginInfo loginInfo) {
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = NewWorklogActivity_.intent(ctx)
.issue(issue)
.loginInfo(loginInfo)
.startDate(startDate)
.flags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS).get();
Notification notification =
new NotificationCompat.Builder(ctx).
setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_stat_new_worklog)).
setSmallIcon(R.drawable.ic_stat_new_worklog).
setOngoing(true).
setContentTitle(issue.getSummary().getKey() + ": " + issue.getSummary().getSummary()).
setAutoCancel(false).
setContentText("Started at: " + TIME_FORMAT.format(startDate)).
setContentIntent(PendingIntent.getActivity(ctx, PENDING_REQUETS_ID++, intent, PendingIntent.FLAG_CANCEL_CURRENT)).
setTicker("Work on " + issue.getSummary().getKey() + " started").
getNotification();
notificationManager.notify(issue.getSummary().getKey(), NOTIFICATION_ID, notification);
}
public static void cancelNotification(Context ctx, String issueKey) {
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(issueKey, NOTIFICATION_ID);
}
}
| [
"[email protected]"
] | |
c1145ee934e3bf03153b8c1c590864b0b841d160 | 6f67d6b6e31e97d578c5cf8f3d29bfddde05d489 | /core/src/main/java/com/novoda/imageloader/core/bitmap/BitmapUtil.java | 92f3cff819a2892a7759e2e607ac4261da40542f | [
"Apache-2.0"
] | permissive | pratikvarma/ImageLoader | fd277bb10aa2ce6c46f0a554e5c682c18371d1f1 | 983389f5c6c97be2f09c46bda99c66b43cc84a06 | refs/heads/master | 2021-01-15T17:46:42.855250 | 2012-05-02T09:20:07 | 2012-05-02T09:20:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,114 | java | /**
* Copyright 2012 Novoda Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.novoda.imageloader.core.bitmap;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.novoda.imageloader.core.model.ImageWrapper;
public class BitmapUtil {
private static final int BUFFER_SIZE = 64 * 1024;
public Bitmap decodeFileAndScale(File f, int width, int height) {
updateLastModifiedForCache(f);
int suggestedSize = height;
if (width > height) {
suggestedSize = height;
}
Bitmap unscaledBitmap = decodeFile(f, suggestedSize);
if (unscaledBitmap == null) {
return null;
}
return scaleBitmap(unscaledBitmap, width, height);
}
public Bitmap scaleResourceBitmap(Context c, int width, int height, int resourceId) {
Bitmap b = null;
try {
b = BitmapFactory.decodeResource(c.getResources(), resourceId);
return scaleBitmap(b, width, height);
} catch (final Throwable e) {
System.gc();
}
return null;
}
public Bitmap scaleBitmap(Bitmap b, int width, int height) {
int imageHeight = b.getHeight();
int imageWidth = b.getWidth();
if (imageHeight <= height && imageWidth <= width) {
return b;
}
int finalWidth = width;
int finalHeight = height;
if (imageHeight > imageWidth) {
float factor = ((float) height) / ((float) imageHeight);
finalHeight = new Float(imageHeight * factor).intValue();
finalWidth = new Float(imageWidth * factor).intValue();
} else {
float factor = ((float) width) / ((float) imageWidth);
finalHeight = new Float(imageHeight * factor).intValue();
finalWidth = new Float(imageWidth * factor).intValue();
}
Bitmap scaled = null;
try {
scaled = Bitmap.createScaledBitmap(b, finalWidth, finalHeight, true);
} catch (final Throwable e) {
System.gc();
}
recycle(b);
return scaled;
}
public Bitmap scaleResourceBitmap(ImageWrapper w, int resId) {
return scaleResourceBitmap(w.getContext(), w.getWidth(), w.getHeight(), resId);
}
private void recycle(Bitmap scaled) {
try {
scaled.recycle();
} catch (Exception e) {
//
}
}
private void updateLastModifiedForCache(File f) {
f.setLastModified(System.currentTimeMillis());
}
private Bitmap decodeFile(File f, int suggestedSize) {
Bitmap bitmap = null;
FileInputStream fis = null;
try {
int scale = evaluateScale(f, suggestedSize);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scale;
options.inTempStorage = new byte[BUFFER_SIZE];
options.inPurgeable = true;
fis = new FileInputStream(f);
bitmap = BitmapFactory.decodeStream(fis, null, options);
} catch (final Throwable e) {
System.gc();
} finally {
closeSilently(fis);
}
return bitmap;
}
private int evaluateScale(File f, int suggestedSize) {
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
decodeFileToPopulateOptions(f, o);
return calculateScale(suggestedSize, o.outWidth, o.outHeight);
}
private void decodeFileToPopulateOptions(File f, final BitmapFactory.Options o) {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
closeSilently(fis);
} catch (final Throwable e) {
System.gc();
} finally {
closeSilently(fis);
}
}
private void closeSilently(Closeable c) {
try {
if (c != null) {
c.close();
}
} catch (Exception e) {
}
}
private int calculateScale(final int requiredSize, int widthTmp, int heightTmp) {
int scale = 1;
while (true) {
if ((widthTmp / 2) < requiredSize || (heightTmp / 2) < requiredSize) {
break;
}
widthTmp /= 2;
heightTmp /= 2;
scale *= 2;
}
return scale;
}
}
| [
"[email protected]"
] | |
a763d9b65e37f547362d0ee429634bbc5f7d0adb | 30172f9b9ec0e50a0d1e6df67602af9bd79d7fd4 | /Phonebook/src/phonebook05/file/Menu.java | 8b048c96a68e4f07ef3bfdbde451164241a5213e | [] | no_license | koys0818/JavaWork-1 | d5ede0fb297e8c6a0cc95ad525f259ff5d643683 | dec7598c4063d8ed79cfffdc4d2e8d793c423da4 | refs/heads/master | 2022-11-06T01:15:13.349492 | 2020-06-16T08:51:26 | 2020-06-16T08:51:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package phonebook05.file;
public interface Menu {
public static final int MENU_QUIT = 0;
public static final int MENU_INSERT = 1;
public static final int MENU_LIST = 2;
public static final int MENU_UPDATE = 3;
public static final int MENU_DELETE = 4;
}
| [
"[email protected]"
] | |
add07f15e7c415dab7289f9e32862e44afcdf47f | 680e00a2c23f620fd8b3b867023abac8f83c65a1 | /src/main/java/org/xdove/jwt/entity/common/Header.java | 21cb51e8f90ba4946f708a63920f639bb20cbe94 | [
"MIT"
] | permissive | Wszl/jwt | b2927c38dfd2b0ebbbf9bd10b0f16694f878d06e | 68856ec477f9e900b3b1b8d55f4679d2e749a127 | refs/heads/master | 2022-07-12T02:54:07.473836 | 2022-06-19T01:22:57 | 2022-06-19T01:22:57 | 110,336,395 | 0 | 0 | MIT | 2022-06-19T01:22:58 | 2017-11-11T10:23:14 | Java | UTF-8 | Java | false | false | 949 | java | package org.xdove.jwt.entity.common;
import org.xdove.jwt.entity.AbstractContains;
import org.xdove.jwt.entity.IHeader;
import java.util.Map;
public class Header extends AbstractContains implements IHeader {
public static final String TYP = "JWT";
public static final String ALG = "Hmacsha256";
public Header() {
this.setTyp(TYP);
this.setAlg(ALG);
}
@Override
public String getTyp() {
return (String) this.get(IHeader.TYP);
}
@Override
public void setTyp(String typ) {
this.put(IHeader.TYP, typ);
}
@Override
public String getAlg() {
return (String) this.get(IHeader.ALG);
}
@Override
public void setAlg(String alg) {
this.put(IHeader.ALG, alg);
}
@Override
public void add(String key, String value) {
this.put(key, value);
}
@Override
public void add(Map map) {
this.putAll(map);
}
}
| [
"[email protected]"
] | |
d9bd0c1e3742a1c6fdeea187655f88be29b5e4c5 | d85028f6a7c72c6e6daa1dd9c855d4720fc8b655 | /io/netty/channel/socket/nio/NioDatagramChannel.java | e16e30637fcf41fd4d074fdc4ee5b30da64f0c29 | [] | no_license | RavenLeaks/Aegis-src-cfr | 85fb34c2b9437adf1631b103f555baca6353e5d5 | 9815c07b0468cbba8d1efbfe7643351b36665115 | refs/heads/master | 2022-10-13T02:09:08.049217 | 2020-06-09T15:31:27 | 2020-06-09T15:31:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,985 | java | /*
* Decompiled with CFR <Could not determine version>.
*/
package io.netty.channel.socket.nio;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.AddressedEnvelope;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultAddressedEnvelope;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.nio.AbstractNioChannel;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramChannelConfig;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.channel.socket.nio.NioDatagramChannelConfig;
import io.netty.channel.socket.nio.ProtocolFamilyConverter;
import io.netty.util.ReferenceCounted;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SuppressJava6Requirement;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ProtocolFamily;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.MembershipKey;
import java.nio.channels.SelectableChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public final class NioDatagramChannel
extends AbstractNioMessageChannel
implements DatagramChannel {
private static final ChannelMetadata METADATA = new ChannelMetadata((boolean)true);
private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
private static final String EXPECTED_TYPES = " (expected: " + StringUtil.simpleClassName(DatagramPacket.class) + ", " + StringUtil.simpleClassName(AddressedEnvelope.class) + '<' + StringUtil.simpleClassName(ByteBuf.class) + ", " + StringUtil.simpleClassName(SocketAddress.class) + ">, " + StringUtil.simpleClassName(ByteBuf.class) + ')';
private final DatagramChannelConfig config;
private Map<InetAddress, List<MembershipKey>> memberships;
private static java.nio.channels.DatagramChannel newSocket(SelectorProvider provider) {
try {
return provider.openDatagramChannel();
}
catch (IOException e) {
throw new ChannelException((String)"Failed to open a socket.", (Throwable)e);
}
}
@SuppressJava6Requirement(reason="Usage guarded by java version check")
private static java.nio.channels.DatagramChannel newSocket(SelectorProvider provider, InternetProtocolFamily ipFamily) {
if (ipFamily == null) {
return NioDatagramChannel.newSocket((SelectorProvider)provider);
}
NioDatagramChannel.checkJavaVersion();
try {
return provider.openDatagramChannel((ProtocolFamily)ProtocolFamilyConverter.convert((InternetProtocolFamily)ipFamily));
}
catch (IOException e) {
throw new ChannelException((String)"Failed to open a socket.", (Throwable)e);
}
}
private static void checkJavaVersion() {
if (PlatformDependent.javaVersion() >= 7) return;
throw new UnsupportedOperationException((String)"Only supported on java 7+.");
}
public NioDatagramChannel() {
this((java.nio.channels.DatagramChannel)NioDatagramChannel.newSocket((SelectorProvider)DEFAULT_SELECTOR_PROVIDER));
}
public NioDatagramChannel(SelectorProvider provider) {
this((java.nio.channels.DatagramChannel)NioDatagramChannel.newSocket((SelectorProvider)provider));
}
public NioDatagramChannel(InternetProtocolFamily ipFamily) {
this((java.nio.channels.DatagramChannel)NioDatagramChannel.newSocket((SelectorProvider)DEFAULT_SELECTOR_PROVIDER, (InternetProtocolFamily)ipFamily));
}
public NioDatagramChannel(SelectorProvider provider, InternetProtocolFamily ipFamily) {
this((java.nio.channels.DatagramChannel)NioDatagramChannel.newSocket((SelectorProvider)provider, (InternetProtocolFamily)ipFamily));
}
public NioDatagramChannel(java.nio.channels.DatagramChannel socket) {
super(null, (SelectableChannel)socket, (int)1);
this.config = new NioDatagramChannelConfig((NioDatagramChannel)this, (java.nio.channels.DatagramChannel)socket);
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
public DatagramChannelConfig config() {
return this.config;
}
@Override
public boolean isActive() {
java.nio.channels.DatagramChannel ch = this.javaChannel();
if (!ch.isOpen()) return false;
if (this.config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION).booleanValue()) {
if (this.isRegistered()) return true;
}
if (!ch.socket().isBound()) return false;
return true;
}
@Override
public boolean isConnected() {
return this.javaChannel().isConnected();
}
@Override
protected java.nio.channels.DatagramChannel javaChannel() {
return (java.nio.channels.DatagramChannel)super.javaChannel();
}
@Override
protected SocketAddress localAddress0() {
return this.javaChannel().socket().getLocalSocketAddress();
}
@Override
protected SocketAddress remoteAddress0() {
return this.javaChannel().socket().getRemoteSocketAddress();
}
@Override
protected void doBind(SocketAddress localAddress) throws Exception {
this.doBind0((SocketAddress)localAddress);
}
private void doBind0(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
SocketUtils.bind((java.nio.channels.DatagramChannel)this.javaChannel(), (SocketAddress)localAddress);
return;
}
this.javaChannel().socket().bind((SocketAddress)localAddress);
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@Override
protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
if (localAddress != null) {
this.doBind0((SocketAddress)localAddress);
}
boolean success = false;
try {
this.javaChannel().connect((SocketAddress)remoteAddress);
success = true;
boolean bl = true;
return bl;
}
finally {
if (!success) {
this.doClose();
}
}
}
@Override
protected void doFinishConnect() throws Exception {
throw new Error();
}
@Override
protected void doDisconnect() throws Exception {
this.javaChannel().disconnect();
}
@Override
protected void doClose() throws Exception {
this.javaChannel().close();
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
int pos;
java.nio.channels.DatagramChannel ch = this.javaChannel();
DatagramChannelConfig config = this.config();
RecvByteBufAllocator.Handle allocHandle = this.unsafe().recvBufAllocHandle();
ByteBuf data = allocHandle.allocate((ByteBufAllocator)config.getAllocator());
allocHandle.attemptedBytesRead((int)data.writableBytes());
boolean free = true;
try {
ByteBuffer nioData = data.internalNioBuffer((int)data.writerIndex(), (int)data.writableBytes());
pos = nioData.position();
InetSocketAddress remoteAddress = (InetSocketAddress)ch.receive((ByteBuffer)nioData);
if (remoteAddress == null) {
int n = 0;
return n;
}
allocHandle.lastBytesRead((int)(nioData.position() - pos));
buf.add((Object)new DatagramPacket((ByteBuf)data.writerIndex((int)(data.writerIndex() + allocHandle.lastBytesRead())), (InetSocketAddress)this.localAddress(), (InetSocketAddress)remoteAddress));
free = false;
int n = 1;
return n;
}
catch (Throwable cause) {
PlatformDependent.throwException((Throwable)cause);
pos = -1;
return pos;
}
finally {
if (free) {
data.release();
}
}
}
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
SocketAddress remoteAddress;
ByteBuf data;
if (msg instanceof AddressedEnvelope) {
AddressedEnvelope envelope = (AddressedEnvelope)msg;
remoteAddress = (SocketAddress)envelope.recipient();
data = (ByteBuf)envelope.content();
} else {
data = (ByteBuf)msg;
remoteAddress = null;
}
int dataLen = data.readableBytes();
if (dataLen == 0) {
return true;
}
ByteBuffer nioData = data.nioBufferCount() == 1 ? data.internalNioBuffer((int)data.readerIndex(), (int)dataLen) : data.nioBuffer((int)data.readerIndex(), (int)dataLen);
int writtenBytes = remoteAddress != null ? this.javaChannel().send((ByteBuffer)nioData, remoteAddress) : this.javaChannel().write((ByteBuffer)nioData);
if (writtenBytes <= 0) return false;
return true;
}
@Override
protected Object filterOutboundMessage(Object msg) {
if (msg instanceof DatagramPacket) {
DatagramPacket p = (DatagramPacket)msg;
ByteBuf content = (ByteBuf)p.content();
if (!NioDatagramChannel.isSingleDirectBuffer((ByteBuf)content)) return new DatagramPacket((ByteBuf)this.newDirectBuffer((ReferenceCounted)p, (ByteBuf)content), (InetSocketAddress)((InetSocketAddress)p.recipient()));
return p;
}
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf)msg;
if (!NioDatagramChannel.isSingleDirectBuffer((ByteBuf)buf)) return this.newDirectBuffer((ByteBuf)buf);
return buf;
}
if (!(msg instanceof AddressedEnvelope)) throw new UnsupportedOperationException((String)("unsupported message type: " + StringUtil.simpleClassName((Object)msg) + EXPECTED_TYPES));
AddressedEnvelope e = (AddressedEnvelope)msg;
if (!(e.content() instanceof ByteBuf)) throw new UnsupportedOperationException((String)("unsupported message type: " + StringUtil.simpleClassName((Object)msg) + EXPECTED_TYPES));
ByteBuf content = (ByteBuf)e.content();
if (!NioDatagramChannel.isSingleDirectBuffer((ByteBuf)content)) return new DefaultAddressedEnvelope<ByteBuf, A>(this.newDirectBuffer((ReferenceCounted)e, (ByteBuf)content), e.recipient());
return e;
}
private static boolean isSingleDirectBuffer(ByteBuf buf) {
if (!buf.isDirect()) return false;
if (buf.nioBufferCount() != 1) return false;
return true;
}
@Override
protected boolean continueOnWriteError() {
return true;
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress)super.localAddress();
}
@Override
public InetSocketAddress remoteAddress() {
return (InetSocketAddress)super.remoteAddress();
}
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress) {
return this.joinGroup((InetAddress)multicastAddress, (ChannelPromise)this.newPromise());
}
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress, ChannelPromise promise) {
try {
return this.joinGroup((InetAddress)multicastAddress, (NetworkInterface)NetworkInterface.getByInetAddress((InetAddress)this.localAddress().getAddress()), null, (ChannelPromise)promise);
}
catch (SocketException e) {
promise.setFailure((Throwable)e);
return promise;
}
}
@Override
public ChannelFuture joinGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
return this.joinGroup((InetSocketAddress)multicastAddress, (NetworkInterface)networkInterface, (ChannelPromise)this.newPromise());
}
@Override
public ChannelFuture joinGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface, ChannelPromise promise) {
return this.joinGroup((InetAddress)multicastAddress.getAddress(), (NetworkInterface)networkInterface, null, (ChannelPromise)promise);
}
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
return this.joinGroup((InetAddress)multicastAddress, (NetworkInterface)networkInterface, (InetAddress)source, (ChannelPromise)this.newPromise());
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@SuppressJava6Requirement(reason="Usage guarded by java version check")
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source, ChannelPromise promise) {
NioDatagramChannel.checkJavaVersion();
if (multicastAddress == null) {
throw new NullPointerException((String)"multicastAddress");
}
if (networkInterface == null) {
throw new NullPointerException((String)"networkInterface");
}
try {
MembershipKey key = source == null ? this.javaChannel().join((InetAddress)multicastAddress, (NetworkInterface)networkInterface) : this.javaChannel().join((InetAddress)multicastAddress, (NetworkInterface)networkInterface, (InetAddress)source);
NioDatagramChannel nioDatagramChannel = this;
// MONITORENTER : nioDatagramChannel
List<MembershipKey> keys = null;
if (this.memberships == null) {
this.memberships = new HashMap<InetAddress, List<MembershipKey>>();
} else {
keys = this.memberships.get((Object)multicastAddress);
}
if (keys == null) {
keys = new ArrayList<MembershipKey>();
this.memberships.put((InetAddress)multicastAddress, keys);
}
keys.add((MembershipKey)key);
// MONITOREXIT : nioDatagramChannel
promise.setSuccess();
return promise;
}
catch (Throwable e) {
promise.setFailure((Throwable)e);
}
return promise;
}
@Override
public ChannelFuture leaveGroup(InetAddress multicastAddress) {
return this.leaveGroup((InetAddress)multicastAddress, (ChannelPromise)this.newPromise());
}
@Override
public ChannelFuture leaveGroup(InetAddress multicastAddress, ChannelPromise promise) {
try {
return this.leaveGroup((InetAddress)multicastAddress, (NetworkInterface)NetworkInterface.getByInetAddress((InetAddress)this.localAddress().getAddress()), null, (ChannelPromise)promise);
}
catch (SocketException e) {
promise.setFailure((Throwable)e);
return promise;
}
}
@Override
public ChannelFuture leaveGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
return this.leaveGroup((InetSocketAddress)multicastAddress, (NetworkInterface)networkInterface, (ChannelPromise)this.newPromise());
}
@Override
public ChannelFuture leaveGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface, ChannelPromise promise) {
return this.leaveGroup((InetAddress)multicastAddress.getAddress(), (NetworkInterface)networkInterface, null, (ChannelPromise)promise);
}
@Override
public ChannelFuture leaveGroup(InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
return this.leaveGroup((InetAddress)multicastAddress, (NetworkInterface)networkInterface, (InetAddress)source, (ChannelPromise)this.newPromise());
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@SuppressJava6Requirement(reason="Usage guarded by java version check")
@Override
public ChannelFuture leaveGroup(InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source, ChannelPromise promise) {
List<MembershipKey> keys;
NioDatagramChannel.checkJavaVersion();
if (multicastAddress == null) {
throw new NullPointerException((String)"multicastAddress");
}
if (networkInterface == null) {
throw new NullPointerException((String)"networkInterface");
}
NioDatagramChannel nioDatagramChannel = this;
// MONITORENTER : nioDatagramChannel
if (this.memberships != null && (keys = this.memberships.get((Object)multicastAddress)) != null) {
Iterator<MembershipKey> keyIt = keys.iterator();
while (keyIt.hasNext()) {
MembershipKey key = keyIt.next();
if (!networkInterface.equals((Object)key.networkInterface()) || (source != null || key.sourceAddress() != null) && (source == null || !source.equals((Object)key.sourceAddress()))) continue;
key.drop();
keyIt.remove();
}
if (keys.isEmpty()) {
this.memberships.remove((Object)multicastAddress);
}
}
// MONITOREXIT : nioDatagramChannel
promise.setSuccess();
return promise;
}
@Override
public ChannelFuture block(InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress sourceToBlock) {
return this.block((InetAddress)multicastAddress, (NetworkInterface)networkInterface, (InetAddress)sourceToBlock, (ChannelPromise)this.newPromise());
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@SuppressJava6Requirement(reason="Usage guarded by java version check")
@Override
public ChannelFuture block(InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress sourceToBlock, ChannelPromise promise) {
NioDatagramChannel.checkJavaVersion();
if (multicastAddress == null) {
throw new NullPointerException((String)"multicastAddress");
}
if (sourceToBlock == null) {
throw new NullPointerException((String)"sourceToBlock");
}
if (networkInterface == null) {
throw new NullPointerException((String)"networkInterface");
}
NioDatagramChannel nioDatagramChannel = this;
// MONITORENTER : nioDatagramChannel
if (this.memberships != null) {
List<MembershipKey> keys = this.memberships.get((Object)multicastAddress);
for (MembershipKey key : keys) {
if (!networkInterface.equals((Object)key.networkInterface())) continue;
try {
key.block((InetAddress)sourceToBlock);
}
catch (IOException e) {
promise.setFailure((Throwable)e);
}
}
}
// MONITOREXIT : nioDatagramChannel
promise.setSuccess();
return promise;
}
@Override
public ChannelFuture block(InetAddress multicastAddress, InetAddress sourceToBlock) {
return this.block((InetAddress)multicastAddress, (InetAddress)sourceToBlock, (ChannelPromise)this.newPromise());
}
@Override
public ChannelFuture block(InetAddress multicastAddress, InetAddress sourceToBlock, ChannelPromise promise) {
try {
return this.block((InetAddress)multicastAddress, (NetworkInterface)NetworkInterface.getByInetAddress((InetAddress)this.localAddress().getAddress()), (InetAddress)sourceToBlock, (ChannelPromise)promise);
}
catch (SocketException e) {
promise.setFailure((Throwable)e);
return promise;
}
}
@Deprecated
@Override
protected void setReadPending(boolean readPending) {
super.setReadPending((boolean)readPending);
}
void clearReadPending0() {
this.clearReadPending();
}
@Override
protected boolean closeOnReadError(Throwable cause) {
if (!(cause instanceof SocketException)) return super.closeOnReadError((Throwable)cause);
return false;
}
}
| [
"[email protected]"
] | |
06ac7567d8ca2f1ca4ba3adce99652df99bf7aff | 0c9b71a9c8bd1f73c4c14a47a239929d99ef355c | /edu-sysmanage/src/main/java/com/zhihuixueai/sysmgr/tools/EmailFormat.java | 7c1ed5d93c110eeb0150cee780b25e22f85777e9 | [] | no_license | micjerry/jdbcexample | 150ddb31486222eda27bbea75ca9e466886eaad8 | 8a7cead3455a7a64b2403cf95c862f12b34fe639 | refs/heads/master | 2023-02-03T01:05:01.213580 | 2020-12-23T09:53:26 | 2020-12-23T09:53:26 | 323,863,974 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 278 | java | package com.zhihuixueai.sysmgr.tools;
public class EmailFormat {
public static boolean isEmail(String email) {
String regex = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
return email.matches(regex);
}
}
| [
"[email protected]"
] | |
36163a35d32f7132c5505bcd871a36ba8e404f04 | 8979fc82ea7b34410b935fbea0151977a0d46439 | /src/company/ibm/oa/MinSwaps.java | 511b32d69680653e9063abf22cd5c284960a7480 | [
"MIT"
] | permissive | YC-S/LeetCode | 6fa3f4e46c952b3c6bf5462a8ee0c1186ee792bd | 452bb10e45de53217bca52f8c81b3034316ffc1b | refs/heads/master | 2021-11-06T20:51:31.554936 | 2021-10-31T03:39:38 | 2021-10-31T03:39:38 | 235,529,949 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,484 | java | package company.ibm.oa;
import java.util.Arrays;
import java.util.List;
public class MinSwaps {
static int findMinSwaps(List<Integer> arr) {
int n = arr.size();
// Array to store count of zeroes
int[] noOfZeroes = new int[n];
int[] noOfOnes = new int[n];
int i, count1 = 0, count2 = 0;
// Count number of zeroes
// on right side of every one.
noOfZeroes[n - 1] = 1 - arr.get(n - 1);
for (i = n - 2; i >= 0; i--) {
noOfZeroes[i] = noOfZeroes[i + 1];
if (arr.get(i) == 0)
noOfZeroes[i]++;
}
// Count total number of swaps by adding number
// of zeroes on right side of every one.
for (i = 0; i < n; i++) {
if (arr.get(i) == 1)
count1 += noOfZeroes[i];
}
noOfOnes[0] = 1 - arr.get(0);
for (i = 1; i < n; ++i) {
noOfOnes[i] = noOfOnes[i - 1];
if (arr.get(i) == 1) {
noOfOnes[i]++;
}
}
for (i = 0; i < n; ++i) {
if (arr.get(i) == 0) {
count2 += noOfOnes[i];
}
}
return Math.min(count1, count2);
}
// Driver Code
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(0, 0, 1, 0, 1, 0, 1, 1);
List<Integer> arr1 = Arrays.asList(1, 1, 1, 1, 0, 0, 0, 0);
System.out.println(findMinSwaps(arr1));
}
}
| [
"[email protected]"
] | |
4e42b94472fa67fe767cedad5bf177fbc98c2fa7 | b5c6913686cf96866d3cb0d7f331234ff49f7848 | /app/src/main/java/zhao/faker/com/commontest/SchemeActivity.java | ae6f85fcbf5dd7ea42aa6244dc691decdcd5886a | [] | no_license | zjutzhaodj/AndroidDemo | e26868cc261cc7894d7d6d2c1b03f5257c6869fd | e7575c4cab13d1007c0515876e7e717a5cac5c4b | refs/heads/master | 2020-03-09T22:59:33.547228 | 2018-04-11T10:11:24 | 2018-04-11T10:11:24 | 129,048,195 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,176 | java | package zhao.faker.com.commontest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
/**
* @author [email protected]
* @description
* @date 2018\4\11 0011
*/
public class SchemeActivity extends AppCompatActivity {
private static final String TAG = "SchemeActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheme);
Intent intent = getIntent();
if (intent != null){
Uri uri = intent.getData();
if (uri != null){
String dataString = intent.getDataString();
String scheme = uri.getScheme();
String host = uri.getHost();
String path = uri.getPath();
String query = uri.getQuery();
Log.i(TAG,"dataString = " + dataString + " | scheme = " + scheme + " | host = " + host+ " | path = " + path + " | query = " + query);
}
}
}
}
| [
"[email protected]"
] | |
4eaaa2ccfd9d33a2b6bc5f70dbd106ed0bf91110 | 982d3835bfda90cf5864fb11b82cc398fb271dce | /hlb-shequ/hlb-shequ-cms/src/main/java/com/haolinbang/modules/sys/dao/UserDao.java | d93ba9322356406fe857cca2b296ed40f5dfb017 | [] | no_license | chocoai/shequ-project | 9d79ad400c6630c0de564638715557ef744d814c | 03be9cdffbd02051dc5beab59254e04584077b3a | refs/heads/master | 2020-04-28T20:13:04.996428 | 2017-10-19T09:39:03 | 2017-10-19T09:39:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,585 | java | package com.haolinbang.modules.sys.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.haolinbang.common.persistence.CrudDao;
import com.haolinbang.common.persistence.annotation.DataSource;
import com.haolinbang.common.persistence.annotation.MyBatisDao;
import com.haolinbang.modules.sys.entity.User;
/**
* 用户DAO接口
*
*/
@MyBatisDao
@DataSource("ds1")
public interface UserDao extends CrudDao<User> {
/**
* 根据登录名称查询用户
*
* @param loginName
* @return
*/
public User getByLoginName(User user);
/**
* 通过OfficeId获取用户列表,仅返回用户id和name(树查询用户时用)
*
* @param user
* @return
*/
public List<User> findUserByOfficeId(User user);
/**
* 查询全部用户数目
*
* @return
*/
public long findAllCount(User user);
/**
* 更新用户密码
*
* @param user
* @return
*/
public int updatePasswordById(User user);
/**
* 更新登录信息,如:登录IP、登录时间
*
* @param user
* @return
*/
public int updateLoginInfo(User user);
/**
* 删除用户角色关联数据
*
* @param user
* @return
*/
public int deleteUserRole(User user);
/**
* 插入用户角色关联数据
*
* @param user
* @return
*/
public int insertUserRole(User user);
/**
* 更新用户信息
*
* @param user
* @return
*/
public int updateUserInfo(User user);
/**
* 通过员工id获取登录名
* @param staffId
* @return
*/
public String getUserByStaffid(@Param("staffId") int staffId);
}
| [
"[email protected]"
] | |
e0f290361e3356504ccb42c19db2d92b044364e2 | db525b75e993c8523cf1479c464c9b0070988a7c | /app/src/androidTest/java/com/example/rezervacije/ExampleInstrumentedTest.java | 2a472b6eab128c9d326facfeed9446e6514ecf64 | [] | no_license | isusnjara0/Rezervacije | 53ae23429ca2aa8e2cef74399be1dcdf7f4712b2 | c7a180c39d12d2c57f984b557e1d2e27c9f53178 | refs/heads/master | 2021-04-11T11:14:28.859387 | 2020-03-24T13:18:39 | 2020-03-24T13:18:39 | 249,009,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 762 | java | package com.example.rezervacije;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.rezervacije", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
490a40a1eedfb02df9e4e49d9d9f11fab48898a5 | d4627ad44a9ac9dfb444bd5d9631b25abe49c37e | /net/divinerpg/item/overworld/ItemSlimeSword.java | 4076ed6554247f94f8f1bc0b039f82229a66b769 | [] | no_license | Scrik/Divine-RPG | 0c357acf374f0ca7fab1f662b8f305ff0e587a2f | f546f1d60a2514947209b9eacdfda36a3990d994 | refs/heads/master | 2021-01-15T11:14:03.426172 | 2014-02-19T20:27:30 | 2014-02-19T20:27:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,114 | java | package net.divinerpg.item.overworld;
import net.divinerpg.helper.base.ItemDivineRPGSword;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class ItemSlimeSword extends ItemDivineRPGSword
{
private int weaponDamage;
private final EnumToolMaterial field_40439_b;
public ItemSlimeSword(int var1, EnumToolMaterial var2)
{
super(var1, var2);
this.field_40439_b = var2;
this.maxStackSize = 1;
this.setMaxDamage(1000);
this.weaponDamage = 11;
this.registerItemTexture("SlimeSword");
}
/**
* Returns the strength of the stack against a given block. 1.0F base, (Quality+1)*2 if correct blocktype, 1.5F if
* sword
*/
@Override
public float getStrVsBlock(ItemStack var1, Block var2)
{
return var2.blockID != Block.web.blockID ? 1.5F : 15.0F;
}
/**
* Current implementations of this method in child classes do not use the entry argument beside ev. They just raise
* the damage on the stack.
*/
public boolean hitEntity(ItemStack var1, EntityLiving var2, EntityLiving var3)
{
var1.damageItem(1, var3);
return true;
}
public boolean onBlockDestroyed(ItemStack var1, int var2, int var3, int var4, int var5, EntityLiving var6)
{
var1.damageItem(2, var6);
return true;
}
/**
* Returns the damage against a given entity.
*/
public int getDamageVsEntity(Entity var1)
{
return this.weaponDamage;
}
/**
* Returns True is the item is renderer in full 3D when hold.
*/
@Override
public boolean isFull3D()
{
return true;
}
/**
* returns the action that specifies what animation to play when the items is being used
*/
@Override
public EnumAction getItemUseAction(ItemStack var1)
{
return EnumAction.block;
}
/**
* How long it takes to use or consume an item
*/
@Override
public int getMaxItemUseDuration(ItemStack var1)
{
return 72000;
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
@Override
public ItemStack onItemRightClick(ItemStack var1, World var2, EntityPlayer var3)
{
var3.setItemInUse(var1, this.getMaxItemUseDuration(var1));
return var1;
}
/**
* Returns if the item (tool) can harvest results from the block type.
*/
@Override
public boolean canHarvestBlock(Block var1)
{
return var1.blockID == Block.web.blockID;
}
/**
* Return the enchantability factor of the item, most of the time is based on material.
*/
@Override
public int getItemEnchantability()
{
return this.field_40439_b.getEnchantability();
}
}
| [
"[email protected]"
] | |
7e2adce8f64bc5dd41bcfcf7c7f3af793b48000b | bc7d6a48c5e851af90b55da98e3bc300f5e617bd | /src/test/java/com/testdomain/aop_sample/AopSampleApplicationTests.java | 07954798b25f4e45229679f90227fefffa98c23e | [] | no_license | Nate-Southerland-EB/aop-sample | 608502dde6655c43bb42eed930f862f414144b83 | e28d7fd45ae4a09eee3de2957114f884d855fa68 | refs/heads/master | 2023-06-25T22:47:14.805628 | 2021-07-15T21:26:29 | 2021-07-15T21:26:29 | 386,427,806 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 229 | java | package com.testdomain.aop_sample;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AopSampleApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
fe60d789df246ab5a5cc934c3d44cff1fc3c47e1 | 3b84c0705b84d4d0ad34eaeb862ef53b05479843 | /Servidor-VEM/src/application/InicioVotoCtrl.java | 26c8bb0f17d868f96564fd764da44a200d8d8000 | [] | no_license | AntKevLazArt96/GADM-VE-v01 | ab9c70214c06cba75fddfe4151a1e4ab2e23b902 | dd6e5c140a0e7491ae78345c7cec4fee78992200 | refs/heads/master | 2021-09-07T12:08:20.285097 | 2018-02-22T15:29:07 | 2018-02-22T15:29:07 | 112,576,212 | 27 | 0 | null | 2017-12-21T03:51:26 | 2017-11-30T06:55:41 | Java | UTF-8 | Java | false | false | 4,437 | java | package application;
import java.io.IOException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ResourceBundle;
import org.json.simple.JSONObject;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextArea;
import clases.TramVoto;
import clases.puntoATratar;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
public class InicioVotoCtrl implements Initializable {
@FXML
public JFXButton btn_finVoto;
@FXML
public JFXButton btn_reVoto;
@FXML
public AnchorPane panelInicioVoto;
// imagenes
@FXML
public ImageView img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12;
// nombre de usuarios
@FXML
public Label user1, user2, user3, user4, user5, user6, user7, user8, user9, user10, user11, user12;
// Votacion de los usurios
@FXML
public Label status1, status2, status3, status4, status5, status6, status7, status8, status9, status10, status11,
estatus12;
// botones de reiniciar el voto individual
@FXML
public JFXButton btnRe1, btnRe2, btnRe3, btnRe4, btnRe5, btnRe6, btnRe7, btnRe8, btnRe9, btnRe10, btnRe11, btnRe12;
@FXML
public JFXTextArea label_titulo;
@FXML
public Label lbl_punto;
@FXML
public Label lbl_proponente;
@FXML
public Label lblAFavor;
@FXML
public Label lblEnContra;
@FXML
public Label lblBlanco;
@FXML
public Label lblSalvoVoto;
@FXML
public Label lblEspera;
@SuppressWarnings("unchecked")
@FXML
void finVoto(ActionEvent event) throws IOException {
try {
//guardamos los votos al finalizar
TramVoto t = new TramVoto();
t.guardarVotos(puntoATratar.id_ordendia);
try {
// String json = "{" + " 'name' : '" + data.name + "', 'message' : '" + msg +
// "'" + "}";
JSONObject js = new JSONObject();
js.put("name", "VOTO RESUMEN");
String json = js.toJSONString();
System.out.println("Se envio:" + json);
PantallaPrincipalCtrl.dos.writeUTF(json);
} catch (IOException E) {
E.printStackTrace();
}
FXMLLoader loader = new FXMLLoader(getClass().getResource("RegistrarVoto.fxml"));
AnchorPane quorum = (AnchorPane) loader.load();
panelInicioVoto.getChildren().setAll(quorum);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
label_titulo.setText(puntoATratar.tema);
lbl_punto.setText(puntoATratar.num_punto);
lbl_proponente.setText(puntoATratar.proponente);
btn_finVoto.setDisable(true);
btn_reVoto.setDisable(true);
try {
LoginController.servidor.limpiarVoto();
// Se inicio la votacion
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@FXML
void reiniciarVoto(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVotos();
}
@FXML
void re1(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto();
}
@FXML
void re2(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto2();
}
@FXML
void re3(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto3();
}
@FXML
void re4(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto4();
}
@FXML
void re5(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto5();
}
@FXML
void re6(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto6();
}
@FXML
void re7(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto7();
}
@FXML
void re8(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto8();
}
@FXML
void re9(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto9();
}
@FXML
void re10(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto10();
}
@FXML
void re11(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto11();
}
@FXML
void re12(ActionEvent event) throws IOException {
TramVoto t = new TramVoto();
t.reiniciarVoto12();
}
}
| [
"[email protected]"
] | |
c3dbcef7dd4e35764f078b900e08ebb0b9356917 | d5a6db9f56db1f404090aadb90acd7f95339dac3 | /leetcode_java/src/leetcode/editor/cn/P43MultiplyStrings.java | 19699b7a8c4e4813440e3059b159978a0faf602f | [] | no_license | luorixiangyang/Blog-code | da073b2958731a2fdb1247baf985190573076184 | 173f2aba7707953d4a6a9da4bd775830f7ceba50 | refs/heads/main | 2023-09-05T09:51:07.474344 | 2021-11-16T09:40:53 | 2021-11-16T09:40:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,423 | java | package leetcode.editor.cn;
public class P43MultiplyStrings {
public static void main(String[] args) {
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) return "0";
String res = "";
for (char c : num2.toCharArray()) {
res += '0';
int count = c - '0';
while (count-- > 0) res = add(res, num1);
}
return res;
}
private String add(String num1, String num2) {
// System.out.println("add: " + num1 + ", " + num2);
StringBuilder res = new StringBuilder();
char[] n1 = new StringBuilder(num1).reverse().toString().toCharArray();
char[] n2 = new StringBuilder(num2).reverse().toString().toCharArray();
int carry = 0;
for (int i = 0, endi = Math.max(n1.length, n2.length); i < endi; i++) {
if (i < n1.length) carry += n1[i] - '0';
if (i < n2.length) carry += n2[i] - '0';
res.append(Character.toChars(carry % 10 + '0'));
carry /= 10;
}
if (carry > 0) res.append('1');
return res.reverse().toString();
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | [
"[email protected]"
] | |
2fb1d02080cf78f468d9cc02dffc9cded20486fc | ea6bbe4659a7048f30dba5d4427060f5e8e116fa | /src/test/java/neusoft/sawyer/concurrency/example/immutable/ImmutableExample1.java | 01c37325ea175f17b2032b9216ad530e396ac28e | [] | no_license | SawyerSY/Concurrency | e047f7074e1b0c46d2592dfd0ad0df1dbcbc2e4f | ec0d1a7c9efcda9f6eb8db26683faca1e77cd579 | refs/heads/master | 2020-03-19T13:43:30.158148 | 2019-05-21T01:58:46 | 2019-05-21T01:58:46 | 136,592,376 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,058 | java | package neusoft.sawyer.concurrency.example.immutable;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import neusoft.sawyer.concurrency.annotation.ThreadSafe;
import java.util.Map;
/**
* Created by sawyer on 2018/7/17.
*/
@Slf4j
@ThreadSafe
public class ImmutableExample1 {
private static final Integer a = 1;
private static final String b = "2";
private static final Map<Integer, Integer> map = Maps.newHashMap();
static {
{
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
}
{
// map = Collections.unmodifiableMap(map);
}
}
public static void main(String[] args) {
// 不允许修改
{
// a = 2;
// b = "3";
// map = Maps.newHashMap();
}
// 允许修改值
{
map.put(1, 3);
}
// 打印
{
log.info("{}", map.get(1));
}
}
private void test(final int a) {
// a = 1;
}
}
| [
"aBc59731090"
] | aBc59731090 |
11dd07199ccfaf4b5b5c2500cfab57247389c82f | 21b59220b622384577ea28dccefb533c1d146c8b | /src/elections/Main.java | 7d76faf56528f3203670e7dd20c281cc6c27f87f | [] | no_license | EugenyB/elections | aa9ba6845f8e53a0fb3b19d4f3d2a986f7aed91e | bbcf56b98950cfb439a54a0a82abb0d27dfa4d8a | refs/heads/master | 2023-04-02T21:23:41.456390 | 2021-04-10T16:43:25 | 2021-04-10T16:43:25 | 354,894,864 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,312 | java | package elections;
import elections.entities.*;
import elections.exceptions.CitizenAlreadyIsAMemberOfPartyException;
import elections.exceptions.CitizenIsNotExistException;
import elections.exceptions.PassportNumberWrongException;
import java.time.LocalDate;
import java.util.Scanner;
public class Main {
Management management;
public static void main(String[] args) {
new Main().run();
}
public void run() {
management = new Management();
management.init();
init();
while (true) {
switch (menu()) {
case 1:
BallotBox newBallotBox = readBallotBoxFromKeyboard();
management.addBallotBox(newBallotBox);
break;
case 2:
try {
Citizen citizen = readCitizenFromKeyboard();
if (management.exists(citizen)) {
System.out.println("This citizen already exists");
} else {
BallotBox box = chooseBallotBox(citizen);
management.addCitizen(citizen, box);
System.out.println("Citizen was added!");
}
} catch (PassportNumberWrongException e) {
System.err.println(e.getMessage());
}
break;
case 3:
Party newParty = readPartyFromKeyboard();
management.addParty(newParty);
break;
case 4:
addPartyMembers();
break;
case 5:
showBoxes(management.showBallotBoxes());
break;
case 6:
printCitizens();
break;
case 7:
printParties();
break;
case 8:
executeBallots();
break;
case 9:
showResults();
break;
case 10: return;
}
}
}
private int readPartyNumberFromScanner(Scanner in, Party[] parties) {
for (int i = 0; i < parties.length; i++) {
System.out.println((i + 1) + ") " + parties[i].getName());
}
System.out.print("Which party? (enter number): ");
return in.nextInt() - 1;
}
private void addPartyMembers() {
System.out.println("Add Party Members");
Scanner in = new Scanner(System.in);
Party[] parties = management.showParties();
int p = readPartyNumberFromScanner(in, parties);
in.nextLine(); // clear buffer
System.out.print("Citizen passport: ");
String passport = in.nextLine();
Citizen citizen = management.findCitizen(passport);
try {
management.addMemberToParty(parties[p], passport);
} catch (CitizenIsNotExistException | CitizenAlreadyIsAMemberOfPartyException ex) {
System.out.println(ex.getMessage());
}
}
private void showResults() {
System.out.println("Votes for party from BallotBox:");
Scanner in = new Scanner(System.in);
Party[] parties = management.showParties();
BallotBox[] ballotBoxes = management.showBallotBoxes();
int p = readPartyNumberFromScanner(in, parties);
System.out.println("Do you want to view full result (1) or ballot box result (0) ? (enter number): ");
if (in.nextInt()==0) {
showResultByBallotBox(ballotBoxes, in, p);
} else {
showTotalResult(p);
}
}
private void showTotalResult(int p) {
int result = management.getResultByParty(p);
System.out.println("Total result is: " + result);
}
private void showResultByBallotBox(BallotBox[] ballotBoxes, Scanner in, int p) {
for (int i = 0; i < ballotBoxes.length; i++) {
System.out.println((i+1) + ") Ballot Box " + ballotBoxes[i].getNumber() + " at " + ballotBoxes[i].getAddress());
}
System.out.print("Which ballot box? (enter number): ");
int b = in.nextInt() - 1;
int votes = management.getVotes(p,b);
System.out.println("Result = " + votes);
}
private void executeBallots() {
Scanner in = new Scanner(System.in);
management.clearVotes();
Citizen[] citizens = management.showCitizens();
for (int i = 0; i < citizens.length; i++) {
System.out.println("Voting " + citizens[i]);
System.out.print("Want to vote? (1 - yes, 0 - no):");
if (in.nextInt() == 1) {
Party[] parties = management.showParties();
for (int p = 0; p < parties.length; p++) {
System.out.print(p+1 + ") ");
System.out.println(parties[p].getName());
}
System.out.print("Which party? Enter the number: ");
int p = in.nextInt() - 1;
management.acceptVoting(citizens[i], parties[p]);
} else {
System.out.println("It's pity - you're choosing to not voting");
}
}
}
private void printCitizens() {
Citizen[] citizens = management.showCitizens();
System.out.println("----- Citizens are: ------");
printArray(citizens);
System.out.println("-------------------------");
}
private void printArray(Object[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
private void printParties() {
Party[] parties = management.showParties();
System.out.println("----- Parties are: ------");
printArray(parties);
System.out.println("-------------------------");
}
private Party readPartyFromKeyboard() {
Scanner in = new Scanner(System.in);
System.out.println("Name of party:");
String name = in.nextLine();
System.out.println("Date of creation (y m d): ");
int year = in.nextInt();
int month = in.nextInt();
int day = in.nextInt();
LocalDate date = LocalDate.of(year, month, day);
System.out.println("Fraction 1 - Left, 2 - Center, 3 - Right");
int fraction;
do {
fraction = in.nextInt();
if (fraction < 1 || fraction >3) System.out.println("Incorrect fraction. Repeat.");
} while (fraction < 1 || fraction >3);
switch(fraction) {
case 1: return new Party(name, Fraction.LEFT, date);
case 2: return new Party(name, Fraction.CENTER, date);
case 3: return new Party(name, Fraction.RIGHT, date);
}
return null;
}
private BallotBox readBallotBoxFromKeyboard() {
Scanner in = new Scanner(System.in);
System.out.println("Address of BallotBox");
String address = in.nextLine();
System.out.println("1 - Normal, 2 - Carantine, 3 - Army");
int type;
do {
type = in.nextInt();
if (type < 1 || type >3) System.out.println("Incorrect type. Repeat.");
} while (type < 1 || type >3);
switch (type) {
case 1: return new NormalBallotBox(address, management);
case 2: return new CarantineBallotBox(address, management);
case 3: return new ArmyBallotBox(address, management);
default: return null;
}
}
private void init() {
// ввести дату (месяц и год выборов)
Scanner in = new Scanner(System.in);
System.out.println("Date of elections (month, year):");
int month = in.nextInt();
int year = in.nextInt();
management.setElectionDate(month, year);
management.addBallotBox(new NormalBallotBox("First Street, 1", management));
management.addBallotBox(new NormalBallotBox("First Street, 20", management));
management.addBallotBox(new ArmyBallotBox("Second Str, 2", management));
management.addBallotBox(new CarantineBallotBox("Another Str, 13", management));
try {
Citizen c1 = Citizen.of("Ian Iza", "123456789", 1995);
management.addCitizen(c1, management.getBallotBox(0));
Citizen c2 = Citizen.of("Bet Bets", "111111111", 1990);
management.addCitizen(c2, management.getBallotBox(0));
Citizen c3 = Citizen.of("Ben Yan", "987654321", 2000);
management.addCitizen(c3, management.getBallotBox(2));
Citizen c4 = Citizen.of("Bin Bolnoy", "123123123", 1998);
c4.setCarantine(true);
management.addCitizen(c4, management.getBallotBox(3));
Citizen c5 = Citizen.of("Ben Best", "212121212", 1990);
management.addCitizen(c5, management.getBallotBox(1));
Party p1 = new Party("Party 1", Fraction.LEFT, LocalDate.of(1990, 5, 1));
management.addParty(p1);
p1.addMember(c1);
p1.addMember(c2);
Party p2 = new Party("Party 2", Fraction.CENTER, LocalDate.of(1980, 1, 1));
management.addParty(p2);
p2.addMember(c3);
Party p3 = new Party("Party 3", Fraction.RIGHT, LocalDate.of(1984, 10, 10));
management.addParty(p3);
p3.addMember(c5);
} catch (Exception e) {}
}
private void showBoxes(BallotBox[] ballotBoxes) {
// for (int i = 0; i < ballotBoxes.length; i++) {
// BallotBox box = ballotBoxes[i];
// System.out.println(box);
// }
for (BallotBox box : ballotBoxes) {
System.out.println(box);
}
System.out.println("Choose BallotBox Number for full info:");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
Citizen[] citizens = management.findBallotBox(num).getCitizens();
printCitizens(citizens);
}
private void printCitizens(Citizen[] citizens) {
for (Citizen citizen : citizens) {
System.out.println(citizen);
}
}
private BallotBox chooseBallotBox(Citizen citizen) {
BallotBox[] appropriated = management.findAppropriateBallotBoxes(citizen);
System.out.println("----- Appropriated Ballot Boxes are: -----");
for (int i = 0; i < appropriated.length; i++) {
System.out.println(appropriated[i]);
}
Scanner in = new Scanner(System.in);
System.out.print("Choose one: ");
int num = in.nextInt();
for (BallotBox box : appropriated) {
if (box.getNumber() == num) return box;
}
return null;
}
private Citizen readCitizenFromKeyboard() throws PassportNumberWrongException {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine();
System.out.print("Passport: ");
String passport = in.nextLine();
System.out.print("Birth year: ");
int year = in.nextInt(); in.nextLine();
Citizen res = Citizen.of(name, passport, year);
System.out.print("Corona? (y/n):");
boolean corona = in.nextLine().startsWith("y");
res.setCarantine(corona);
return res;
}
private int menu() {
System.out.println(
"1. Добавление стойки\n" +
"2. Добавление гражданина \n" +
"3. Добавление партии\n" +
"4. Добавление гражданина , который кандидат от определенной партии\n" +
"5. Показать стойки\n" +
"6. Показать граждан\n" +
"7. Показать партии\n"+
"8. Выполнение выборов\n" +
"9. \n" +
"10. Exit");
return new Scanner(System.in).nextInt();
}
}
| [
"[email protected]"
] | |
73eb95f269588c53bf80602a0e4c1d1801d2c7e7 | ee95192a12c15996399b193e929550f7360f79d5 | /src/main/java/info/seleniumcucumber/methods/ScreenShotMethods.java | 6b01d4ba42b9f2c5a70936f0a4fdc973e2b61e2c | [] | no_license | vuongvvv/JavaSeleniumCucumber | 94dfd2d45eda7624f0e2ff9604c5372df89e8db1 | 1af99f082a1e94b534086f76784332881aaecf6d | refs/heads/master | 2021-07-09T13:18:53.904746 | 2019-08-24T13:44:00 | 2019-08-24T13:44:00 | 203,209,039 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,044 | java | package info.seleniumcucumber.methods;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import env.DriverUtil;
import org.openqa.selenium.WebDriver;
public class ScreenShotMethods implements BaseTest {
protected WebDriver driver = DriverUtil.getDefaultDriver();
/** Method to take screen shot and save in ./screenShots folder */
public void takeScreenShot() throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
DateFormat dateFormat = new SimpleDateFormat("MMMM-dd-yyyy-z-HH:mm:ss", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
//System.out.println(dateFormat.format(cal.getTime()));
FileUtils.copyFile(scrFile, new File("screenShots".concat(System.getProperty("file.separator")) + dateFormat.format(cal.getTime()) + ".png"));
}
}
| [
"[email protected]"
] | |
f8adbf1ca74c90e71379e793924a6bdd511ef9c1 | 9a3e66d89ba1b299bf809b6a4f645251fdbbb66d | /src/test/java/com/mycompany/myapp/security/SecurityUtilsTest.java | a04aabcfae8b19f064978862749480c587006b60 | [] | no_license | pvlastaridis/Neo4JHipster | 549e9e596fd15d688b2486bd597dd7dbaee04556 | bc13eaaa9542f3417713c27f5a9918bf8f7106b5 | refs/heads/master | 2021-06-05T02:41:06.265405 | 2020-12-24T17:35:43 | 2020-12-24T17:35:43 | 25,803,198 | 14 | 3 | null | 2021-04-26T17:41:54 | 2014-10-27T04:29:11 | Java | UTF-8 | Java | false | false | 2,092 | java | package com.mycompany.myapp.security;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the SecurityUtils utility class.
*
* @see SecurityUtils
*/
public class SecurityUtilsTest {
@Test
public void testgetCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
String login = SecurityUtils.getCurrentUserLogin();
assertThat(login).isEqualTo("admin");
}
@Test
public void testIsAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isTrue();
}
@Test
public void testAnonymousIsNotAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isFalse();
}
}
| [
"[email protected]"
] | |
c937edbf7c43dc0905a7a3204c9e9044c883f2ab | 67a1d45071d2ff3d3e3989dfca8d600a083b7ecd | /src/main/java/com/doctor/java/security/JavaCryptographyExtension_AES.java | 18e1af2fc7792f043ff39365cbfab2d0618e4e0f | [
"Apache-2.0"
] | permissive | sdcuike/openSourcLibrary-2015 | 2fdf6b7a39a15d6206af1e95f589261d6f00bb54 | 969bcae98d925b86017c04df72ebf50fad7fac3e | refs/heads/master | 2020-04-24T05:03:51.831869 | 2015-08-30T15:22:10 | 2015-08-30T15:22:10 | 32,978,037 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,139 | java | package com.doctor.java.security;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.google.common.base.Preconditions;
/**
*
* @author doctor
*
* @time 2015年3月27日
*/
public class JavaCryptographyExtension_AES {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
String key = AESUtil.generateKeyToBase64String();
SecretKey secretKey = AESUtil.getKeyFromBase64String(key);
String text = "hello ai doctor who";
String encryptToBase64String = AESUtil.EncryptToBase64String(text, secretKey);
System.out.println(encryptToBase64String);
String decryptFromBase64String = AESUtil.decryptFromBase64String(encryptToBase64String, secretKey);
Preconditions.checkState(text.equals(decryptFromBase64String));
}
private static final class AESUtil {
private static String keyAlgorithm = "AES";
private static String cipherAlgorithm = "AES/ECB/PKCS5Padding";
private static int keySize = 128;
public static String generateKeyToBase64String() throws NoSuchAlgorithmException {
byte[] encoded = generateKey();
return Base64.getEncoder().encodeToString(encoded);
}
public static byte[] generateKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(keyAlgorithm);
keyGenerator.init(keySize);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
public static SecretKey getKeyFromBase64String(String base64StringKey) {
byte[] key = Base64.getDecoder().decode(base64StringKey);
SecretKey secretKey = new SecretKeySpec(key, keyAlgorithm);
return secretKey;
}
public static String EncryptToBase64String(String plainText, SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] doFinal = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getUrlEncoder().encodeToString(doFinal);// UrlEncoder 内容,如果是cooki,这样的内容可以兼容cooki版本1
}
public static String decryptFromBase64String(String encryptedBase64String, SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decode = Base64.getUrlDecoder().decode(encryptedBase64String);
byte[] doFinal = cipher.doFinal(decode);
return new String(doFinal, StandardCharsets.UTF_8);
}
}
}
| [
"[email protected]"
] | |
309ab7366f6aab040ab95f7ea8fde78a9821a67c | 26884781a91f0961fcbea9934ed7dddabaeaa71c | /Textmining/src/org/wisslab/ss15/textmining/Scene.java | 462f30754289156afa3b4fd0c8df0b8e156230c1 | [] | no_license | kaiec/textmining-ss16 | 24a595186eb4a6c1235d06da3d96d77b83cf738d | 0c6a8001c2ef2a0a5b411a5ef42ad48289bf009a | refs/heads/master | 2021-01-21T13:53:19.486572 | 2016-05-12T10:29:52 | 2016-05-12T10:29:52 | 55,677,541 | 6 | 5 | null | 2016-04-21T14:16:43 | 2016-04-07T08:29:38 | Java | UTF-8 | Java | false | false | 687 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.wisslab.ss15.textmining;
/**
*
* @author kai
*/
public class Scene {
private int number;
private Act act;
public Scene(Act act, int number) {
this.number = number;
this.act = act;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Act getAct() {
return act;
}
public void setAct(Act act) {
this.act = act;
}
}
| [
"[email protected]"
] | |
9a4c046cf6696ef98a88fdc56575e35e336201fd | a636258c60406f8db850d695b064836eaf75338b | /src/org/openbravo/scheduling/ProcessMonitor.java | cd693ef14bb5bc69bf081db8a9842cb0d3b9b992 | [] | no_license | Afford-Solutions/openbravo-payroll | ed08af5a581fa41455f4e9b233cb182d787d5064 | 026fee4fe79b1f621959670fdd9ae6dec33d263e | refs/heads/master | 2022-03-10T20:43:13.162216 | 2019-11-07T18:31:05 | 2019-11-07T18:31:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,630 | java | /*
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.1 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2008-2013 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
************************************************************************
*/
package org.openbravo.scheduling;
import static org.openbravo.scheduling.Process.COMPLETE;
import static org.openbravo.scheduling.Process.ERROR;
import static org.openbravo.scheduling.Process.EXECUTION_ID;
import static org.openbravo.scheduling.Process.PROCESSING;
import static org.openbravo.scheduling.Process.SCHEDULED;
import static org.openbravo.scheduling.Process.SUCCESS;
import static org.openbravo.scheduling.Process.UNSCHEDULED;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import org.openbravo.base.ConfigParameters;
import org.openbravo.base.ConnectionProviderContextListener;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.database.SessionInfo;
import org.openbravo.erpCommon.utility.SequenceIdData;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.quartz.SchedulerListener;
import org.quartz.Trigger;
import org.quartz.TriggerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author awolski
*
*/
class ProcessMonitor implements SchedulerListener, JobListener, TriggerListener {
static final Logger log = LoggerFactory.getLogger(ProcessMonitor.class);
public static final String KEY = "org.openbravo.scheduling.ProcessMonitor.KEY";
private String name;
private SchedulerContext context;
public ProcessMonitor(String name, SchedulerContext context) {
this.name = name;
this.context = context;
}
public void jobScheduled(Trigger trigger) {
final ProcessBundle bundle = (ProcessBundle) trigger.getJobDataMap().get(ProcessBundle.KEY);
final ProcessContext ctx = bundle.getContext();
try {
ProcessRequestData.setContext(getConnection(), ctx.getUser(), ctx.getUser(), SCHEDULED,
bundle.getChannel().toString(), ctx.toString(), trigger.getName());
try {
log.debug("jobScheduled for process {}",
trigger.getJobDataMap().getString(Process.PROCESS_NAME));
} catch (Exception ignore) {
// ignore: exception while trying to log
}
} catch (final ServletException e) {
log.error(e.getMessage(), e);
} finally {
// return connection to pool and remove it from current thread
SessionInfo.init();
}
}
public void triggerFired(Trigger trigger, JobExecutionContext jec) {
final ProcessBundle bundle = (ProcessBundle) jec.getMergedJobDataMap().get(ProcessBundle.KEY);
final ProcessContext ctx = bundle.getContext();
try {
try {
log.debug("triggerFired for process {}. Next execution time: {}", jec.getTrigger()
.getJobDataMap().getString(Process.PROCESS_NAME), trigger.getNextFireTime());
} catch (Exception ignore) {
// ignore: exception while trying to log
}
ProcessRequestData.update(getConnection(), ctx.getUser(), ctx.getUser(), SCHEDULED, bundle
.getChannel().toString(), format(trigger.getPreviousFireTime()),
OBScheduler.sqlDateTimeFormat, format(trigger.getNextFireTime()), format(trigger
.getFinalFireTime()), ctx.toString(), trigger.getName());
} catch (final ServletException e) {
log.error(e.getMessage(), e);
}
// no need to return the connection because it will be done after the process is executed
}
public void jobToBeExecuted(JobExecutionContext jec) {
final ProcessBundle bundle = (ProcessBundle) jec.getMergedJobDataMap().get(ProcessBundle.KEY);
if (bundle == null) {
return;
}
try {
log.debug("jobToBeExecuted for process {}}",
jec.getTrigger().getJobDataMap().getString(Process.PROCESS_NAME));
} catch (Exception ignore) {
// ignore: exception while trying to log
}
final ProcessContext ctx = bundle.getContext();
final String executionId = SequenceIdData.getUUID();
try {
ProcessRunData.insert(getConnection(), ctx.getOrganization(), ctx.getClient(), ctx.getUser(),
ctx.getUser(), executionId, PROCESSING, null, null, jec.getJobDetail().getName());
jec.put(EXECUTION_ID, executionId);
jec.put(ProcessBundle.CONNECTION, getConnection());
jec.put(ProcessBundle.CONFIG_PARAMS, getConfigParameters());
} catch (final ServletException e) {
log.error(e.getMessage(), e);
}
// no need to return the connection because it will be done after the process is executed
}
public void jobWasExecuted(JobExecutionContext jec, JobExecutionException jee) {
final ProcessBundle bundle = (ProcessBundle) jec.getMergedJobDataMap().get(ProcessBundle.KEY);
if (bundle == null) {
return;
}
try {
log.debug("jobToBeExecuted for process {}}",
jec.getTrigger().getJobDataMap().getString(Process.PROCESS_NAME));
} catch (Exception ignore) {
// ignore: exception while trying to log
}
final ProcessContext ctx = bundle.getContext();
try {
final String executionId = (String) jec.get(EXECUTION_ID);
final String executionLog = bundle.getLog().length() >= 4000 ? bundle.getLog().substring(0,
3999) : bundle.getLog();
if (jee == null) {
ProcessRunData.update(getConnection(), ctx.getUser(), SUCCESS,
getDuration(jec.getJobRunTime()), executionLog, executionId);
} else {
ProcessRunData.update(getConnection(), ctx.getUser(), ERROR,
getDuration(jec.getJobRunTime()), executionLog, executionId);
}
} catch (final ServletException e) {
log.error(e.getMessage(), e);
} finally {
// return connection to pool and remove it from current thread
SessionInfo.init();
}
}
public void triggerFinalized(Trigger trigger) {
try {
ProcessRequestData.update(getConnection(), COMPLETE, trigger.getName());
} catch (final ServletException e) {
log.error(e.getMessage(), e);
} finally {
// return connection to pool and remove it from current thread
SessionInfo.init();
}
}
public void jobUnscheduled(String triggerName, String triggerGroup) {
try {
ProcessRequestData.update(getConnection(), UNSCHEDULED, null, null, null, triggerName);
} catch (final ServletException e) {
log.error(e.getMessage(), e);
} finally {
// return connection to pool and remove it from current thread
SessionInfo.init();
}
}
public void triggerMisfired(Trigger trigger) {
try {
log.debug("Misfired process {}, start time {}.",
trigger.getJobDataMap().getString(Process.PROCESS_NAME), trigger.getStartTime());
} catch (Exception e) {
// ignore: exception while trying to log
}
// Not implemented
}
public void jobsPaused(String jobName, String jobGroup) {
// Not implemented
}
public void jobsResumed(String jobName, String jobGroup) {
// Not implemented
}
public void schedulerError(String msg, SchedulerException e) {
// Not implemented
}
public void schedulerShutdown() {
// Not implemented
}
public void triggersPaused(String triggerName, String triggerGroup) {
// Not implemented
}
public void triggersResumed(String triggerName, String triggerGroup) {
// Not implemented
}
public void jobExecutionVetoed(JobExecutionContext jec) {
// Not implemented
}
public void triggerComplete(Trigger trigger, JobExecutionContext jec, int triggerInstructionCode) {
// Not implemented
}
@SuppressWarnings("unchecked")
public boolean vetoJobExecution(Trigger trigger, JobExecutionContext jec) {
JobDataMap jobData = trigger.getJobDataMap();
Boolean preventConcurrentExecutions = (Boolean) jobData
.get(Process.PREVENT_CONCURRENT_EXECUTIONS);
if (preventConcurrentExecutions == null || !preventConcurrentExecutions) {
return false;
}
List<JobExecutionContext> jobs;
String processName = jobData.getString(Process.PROCESS_NAME);
try {
jobs = jec.getScheduler().getCurrentlyExecutingJobs();
} catch (SchedulerException e) {
log.error("Error trying to determine if there are concurrent processes in execution for "
+ processName + ", executing it anyway", e);
return false;
}
// Checking if there is another instance in execution for this process
for (JobExecutionContext job : jobs) {
if (job.getTrigger().getJobDataMap().get(Process.PROCESS_ID)
.equals(trigger.getJobDataMap().get(Process.PROCESS_ID))
&& !job.getJobInstance().equals(jec.getJobInstance())) {
ProcessBundle jobAlreadyScheduled = (ProcessBundle) job.getTrigger().getJobDataMap()
.get("org.openbravo.scheduling.ProcessBundle.KEY");
ProcessBundle newJob = (ProcessBundle) trigger.getJobDataMap().get(
"org.openbravo.scheduling.ProcessBundle.KEY");
boolean isSameClient = isSameParam(jobAlreadyScheduled, newJob, "Client");
if (!isSameClient
|| (isSameClient && !isSameParam(jobAlreadyScheduled, newJob, "Organization"))) {
continue;
}
log.info("There's another instance running, so leaving" + processName);
try {
if (!trigger.mayFireAgain()) {
// This is last execution of this trigger, so set it as complete
ProcessRequestData.update(getConnection(), COMPLETE, trigger.getName());
}
// Create a process run as error
final ProcessBundle bundle = (ProcessBundle) jec.getMergedJobDataMap().get(
ProcessBundle.KEY);
if (bundle == null) {
return true;
}
final ProcessContext ctx = bundle.getContext();
final String executionId = SequenceIdData.getUUID();
ProcessRunData.insert(getConnection(), ctx.getOrganization(), ctx.getClient(),
ctx.getUser(), ctx.getUser(), executionId, PROCESSING, null, null, trigger.getName());
ProcessRunData.update(getConnection(), ctx.getUser(), ERROR, getDuration(0),
"Concurrent attempt to execute", executionId);
} catch (Exception e) {
log.error("Error updating conetext for non executed process due to concurrency "
+ processName, e);
} finally {
// return connection to pool and remove it from current thread only in case the process is
// not going to be executed because of concurrency, other case leave the connection to be
// closed after the process finishes
SessionInfo.init();
}
return true;
}
}
log.debug("No other instance");
return false;
}
private boolean isSameParam(ProcessBundle jobAlreadyScheduled, ProcessBundle newJob, String param) {
ProcessContext jobAlreadyScheduledContext = null;
String jobAlreadyScheduledParam = null;
ProcessContext newJobContext = null;
String newJobParam = null;
if (jobAlreadyScheduled != null) {
jobAlreadyScheduledContext = jobAlreadyScheduled.getContext();
if (jobAlreadyScheduledContext != null) {
if ("Client".equals(param)) {
jobAlreadyScheduledParam = jobAlreadyScheduledContext.getClient();
} else if ("Organization".equals(param)) {
jobAlreadyScheduledParam = jobAlreadyScheduledContext.getOrganization();
}
}
}
if (newJob != null) {
newJobContext = newJob.getContext();
if (newJobContext != null) {
if ("Client".equals(param)) {
newJobParam = newJobContext.getClient();
} else if ("Organization".equals(param)) {
newJobParam = newJobContext.getOrganization();
}
}
}
if (newJobParam != null && jobAlreadyScheduledParam != null
&& newJobParam.equals(jobAlreadyScheduledParam)) {
return true;
}
return false;
}
/**
* @return the database Connection Provider
*/
public ConnectionProvider getConnection() {
return (ConnectionProvider) context.get(ConnectionProviderContextListener.POOL_ATTRIBUTE);
}
/**
* @return the configuration parameters.
*/
public ConfigParameters getConfigParameters() {
return (ConfigParameters) context.get(ConfigParameters.CONFIG_ATTRIBUTE);
}
/**
* Formats a date according to the data time format.
*
* @param date
* @return a formatted date
*/
public final String format(Date date) {
final String dateTimeFormat = getConfigParameters().getJavaDateTimeFormat();
return date == null ? null : new SimpleDateFormat(dateTimeFormat).format(date);
}
/**
* Converts a duration in millis to a String
*
* @param duration
* the duration in millis
* @return a String representation of the duration
*/
public static String getDuration(long duration) {
final int milliseconds = (int) (duration % 1000);
final int seconds = (int) ((duration / 1000) % 60);
final int minutes = (int) ((duration / 60000) % 60);
final int hours = (int) ((duration / 3600000) % 24);
final String m = (milliseconds < 10 ? "00" : (milliseconds < 100 ? "0" : "")) + milliseconds;
final String sec = (seconds < 10 ? "0" : "") + seconds;
final String min = (minutes < 10 ? "0" : "") + minutes;
final String hr = (hours < 10 ? "0" : "") + hours;
return hr + ":" + min + ":" + sec + "." + m;
}
/*
* (non-Javadoc)
*
* @see org.quartz.JobListener#getName()
*/
public String getName() {
return name;
}
}
| [
"[email protected]"
] | |
94d5c5ca88570ad3245127aa2bbf0db9ff68503e | 79957f70c9d3aa84fbef65cf4bc5be9acfab3f61 | /zijianmall-product/src/main/java/com/zijianmall/product/dao/AttrAttrgroupRelationDao.java | 89b34bf06546b855ded07482bc5d26c1a67f70ec | [
"Apache-2.0"
] | permissive | xiaoxiaoll1/zijianmall | 0f3c075a1ea4444e821abcf0ea18a053294fcd4d | 8996354c12843091952ea705969078289d3cee93 | refs/heads/main | 2023-02-17T12:53:48.217420 | 2021-01-13T12:12:50 | 2021-01-13T12:12:50 | 322,787,590 | 0 | 0 | Apache-2.0 | 2020-12-31T09:46:50 | 2020-12-19T06:59:53 | JavaScript | UTF-8 | Java | false | false | 430 | java | package com.zijianmall.product.dao;
import com.zijianmall.product.entity.AttrAttrgroupRelationEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 属性&属性分组关联
*
* @author zijian
* @email [email protected]
* @date 2020-12-21 22:37:16
*/
@Mapper
public interface AttrAttrgroupRelationDao extends BaseMapper<AttrAttrgroupRelationEntity> {
}
| [
"[email protected]"
] | |
58edf8e7275776fc7e2c9f4be220ed32a2c177fd | b9a68c3d6c417bb20a9625e888137b824494aff8 | /Ride Share/obj/Debug/android/src/md5ec1e820de7c625f1eefa6266bce04596/TouchableWrapper.java | dd57d31a49ffd2710b4c2f59ceede62a55ca4af3 | [] | no_license | KhalidElKhamlichi/RideShare | d029703ccb2f7112abe8727aa701fba32a1290db | 709ad319141e32a484dd28eb770d78349b2f5bfe | refs/heads/master | 2021-09-02T13:03:57.623273 | 2018-01-02T21:41:16 | 2018-01-02T21:41:16 | 111,022,145 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,527 | java | package md5ec1e820de7c625f1eefa6266bce04596;
public class TouchableWrapper
extends android.widget.FrameLayout
implements
mono.android.IGCUserPeer
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_dispatchTouchEvent:(Landroid/view/MotionEvent;)Z:GetDispatchTouchEvent_Landroid_view_MotionEvent_Handler\n" +
"";
mono.android.Runtime.register ("Ride_Share.Fragments.TouchableWrapper, Ride Share, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", TouchableWrapper.class, __md_methods);
}
public TouchableWrapper (android.content.Context p0) throws java.lang.Throwable
{
super (p0);
if (getClass () == TouchableWrapper.class)
mono.android.TypeManager.Activate ("Ride_Share.Fragments.TouchableWrapper, Ride Share, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0 });
}
public TouchableWrapper (android.content.Context p0, android.util.AttributeSet p1) throws java.lang.Throwable
{
super (p0, p1);
if (getClass () == TouchableWrapper.class)
mono.android.TypeManager.Activate ("Ride_Share.Fragments.TouchableWrapper, Ride Share, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0, p1 });
}
public TouchableWrapper (android.content.Context p0, android.util.AttributeSet p1, int p2) throws java.lang.Throwable
{
super (p0, p1, p2);
if (getClass () == TouchableWrapper.class)
mono.android.TypeManager.Activate ("Ride_Share.Fragments.TouchableWrapper, Ride Share, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2 });
}
public TouchableWrapper (android.content.Context p0, android.util.AttributeSet p1, int p2, int p3) throws java.lang.Throwable
{
super (p0, p1, p2, p3);
if (getClass () == TouchableWrapper.class)
mono.android.TypeManager.Activate ("Ride_Share.Fragments.TouchableWrapper, Ride Share, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2, p3 });
}
public boolean dispatchTouchEvent (android.view.MotionEvent p0)
{
return n_dispatchTouchEvent (p0);
}
private native boolean n_dispatchTouchEvent (android.view.MotionEvent p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| [
"[email protected]"
] | |
03e48bbd6dcd3bccd3a28f34f80cfdb345e83f56 | a44c7af42d0a156410dc574a0166c79490feac61 | /app/src/main/java/nikonorov/net/signapp/di/AppModule.java | 0057be1a8b63fd4fc44036a09afd0a25ec9aba80 | [] | no_license | VitalyNikonorov/signapp | 30467d9c4c86cda54f4f9eaa6dd926ae71cb3ab6 | 11a56f8286811e92e1e093816da5b14c70d96932 | refs/heads/master | 2021-01-11T14:54:46.315581 | 2017-01-28T16:43:10 | 2017-01-28T16:43:10 | 80,248,605 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 492 | java | package nikonorov.net.signapp.di;
import android.content.Context;
import android.support.annotation.NonNull;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by vitaly on 27.01.17.
*/
@Module
public class AppModule {
private Context appContext;
public AppModule(@NonNull Context appContext) {
this.appContext = appContext;
}
@Provides
@Singleton
Context provideContext(){
return appContext;
}
}
| [
"[email protected]"
] | |
357ed3a9fc5dc48d1b9cdbbf18646af40faf1604 | 29f59c99fe387cdb6bca6dc8ca927ca67786429e | /src/main/java/model/jdbc/impl/JDBC.java | 4683bbbe27fb95c15930f5c3183ca7b4db79f55a | [] | no_license | grishasht/Ain.ua_Parser | 29a9fbfa24508fcc9e9b91533839404600672cb3 | 49cc90952a3df0b40bdf1e2dc8434d7cb9f90347 | refs/heads/master | 2022-09-30T19:53:18.264603 | 2020-02-20T21:44:30 | 2020-02-20T21:44:30 | 197,632,842 | 0 | 0 | null | 2022-09-08T01:06:29 | 2019-07-18T17:50:42 | Java | UTF-8 | Java | false | false | 176 | java | package model.jdbc.impl;
import java.sql.Connection;
class JDBC {
Connection connection;
JDBC(Connection connection) {
this.connection = connection;
}
}
| [
"[email protected]"
] | |
966c24593c42647c043228b3b1ee37e1d78315c7 | 43c212034087e8cf961075d783eb859e759b62e9 | /src/entity/Donation.java | 09e208d7ac57b25f830511b4718682e662e418f6 | [] | no_license | Nastasja-Z/lab1_Java | 4ac2c38512286207e9c9780ccde6e81856a75fde | b2dd1f093f2347cdb654291563e76a04234a2170 | refs/heads/main | 2023-03-16T08:57:35.115569 | 2021-03-17T17:30:29 | 2021-03-17T17:30:29 | 348,793,769 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,082 | java | package entity;
import entity.Needy;
import entity.Option;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class Donation {
private Integer id;
private Map<Needy, Option> donatMap;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id=id;
}
public Map<Needy, Option> getDonatMap() {
return donatMap;
}
public void setDonatMap(Map<Needy, Option> donatMap) {
this.donatMap=donatMap;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Donation donation = (Donation) o;
return Objects.equals(id, donation.id) && Objects.equals(donatMap, donation.donatMap);
}
@Override
public int hashCode() {
return Objects.hash(id, donatMap);
}
@Override
public String toString() {
return "Donation{" +
"id=" + id +
", donatMap=" + donatMap +
'}';
}
}
| [
"[email protected]"
] | |
d4d997d726508c06487eb17af6d8bc451f010495 | 421f0a75a6b62c5af62f89595be61f406328113b | /generated_tests/no_seeding/99_newzgrabber-Newzgrabber.NewsFile-1.0-3/Newzgrabber/NewsFile_ESTest_scaffolding.java | 1e2cccc91de3e242e03580868f81b1a68eb6b946 | [] | no_license | tigerqiu712/evosuite-model-seeding-empirical-evaluation | c78c4b775e5c074aaa5e6ca56bc394ec03c2c7c6 | 11a920b8213d9855082d3946233731c843baf7bc | refs/heads/master | 2020-12-23T21:04:12.152289 | 2019-10-30T08:02:29 | 2019-10-30T08:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Mon Oct 28 16:28:46 GMT 2019
*/
package Newzgrabber;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class NewsFile_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"[email protected]"
] | |
76dbac73063e379de091d7af4fb06cac340b9aec | 45e212d22087ddbe7baa5875943b888b4b5ba0a2 | /src/com/company/HasTail.java | c9c87f368129a6fdeec76f8ba2629841eafc0604 | [] | no_license | CoderBryGuy/OrderOfInitialization | f9ef5df7d70e72f6852c58fa451666e5f3498b05 | d9bcbb67ecb9f872f182915341f2e30ca7b8beca | refs/heads/master | 2020-11-29T03:04:54.922909 | 2019-12-24T21:08:15 | 2019-12-24T21:08:15 | 230,003,423 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 230 | java | package com.company;
public interface HasTail {
int DEFAULT_TAIL_LENGTH = 2;
// int getDefaultTailLength();
// public abstract int getDefaultTailLength();
int getDefaultTailLength();
int getWeight();
}
| [
"[email protected]"
] | |
b3b1775b865de7759c168dd084f010ab66a4f7e0 | e01c0a481a4241627011c3810a1dfe163eb29133 | /src/main/java/com/erp/pojo/ProductInfo.java | eb8fe056cd5c148658d92f06fe7ecf782fd2000e | [] | no_license | zhang771036282/Erp | acab9519c447e075070a2d0e2fa4254a579f5c46 | f4b1b66d2a577beaf08f1a99e51ebf2f35fb1883 | refs/heads/master | 2020-04-11T06:48:51.794277 | 2019-01-17T02:13:32 | 2019-01-17T02:13:49 | 161,583,501 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,025 | java | package com.erp.pojo;
public class ProductInfo {
private Integer id;
private Integer ddid;
private String orderCode;
private Float width;
private Float height;
private String board;
private String craft;
private String doorType;
private String edgeShape;
private String doorTypeParts;
private Integer doorTypePartsNum;
private String face;
private String parts;
private Integer partsNumber;
private String texture;
private Integer num;
private String productColor;
private String open;
private String remark;
private Float area;
private Float price;
private Float productSubtotal;
private Float v1;
private Float v2;
private Float v3;
private String doorTypeName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDdid() {
return ddid;
}
public void setDdid(Integer ddid) {
this.ddid = ddid;
}
public String getOrderCode() {
return orderCode;
}
public void setOrderCode(String orderCode) {
this.orderCode = orderCode == null ? null : orderCode.trim();
}
public Float getWidth() {
return width;
}
public void setWidth(Float width) {
this.width = width;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public String getBoard() {
return board;
}
public void setBoard(String board) {
this.board = board == null ? null : board.trim();
}
public String getCraft() {
return craft;
}
public void setCraft(String craft) {
this.craft = craft == null ? null : craft.trim();
}
public String getDoorType() {
return doorType;
}
public void setDoorType(String doorType) {
this.doorType = doorType == null ? null : doorType.trim();
}
public String getEdgeShape() {
return edgeShape;
}
public void setEdgeShape(String edgeShape) {
this.edgeShape = edgeShape == null ? null : edgeShape.trim();
}
public String getDoorTypeParts() {
return doorTypeParts;
}
public void setDoorTypeParts(String doorTypeParts) {
this.doorTypeParts = doorTypeParts == null ? null : doorTypeParts.trim();
}
public Integer getDoorTypePartsNum() {
return doorTypePartsNum;
}
public void setDoorTypePartsNum(Integer doorTypePartsNum) {
this.doorTypePartsNum = doorTypePartsNum;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face == null ? null : face.trim();
}
public String getParts() {
return parts;
}
public void setParts(String parts) {
this.parts = parts == null ? null : parts.trim();
}
public Integer getPartsNumber() {
return partsNumber;
}
public void setPartsNumber(Integer partsNumber) {
this.partsNumber = partsNumber;
}
public String getTexture() {
return texture;
}
public void setTexture(String texture) {
this.texture = texture == null ? null : texture.trim();
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getProductColor() {
return productColor;
}
public void setProductColor(String productColor) {
this.productColor = productColor == null ? null : productColor.trim();
}
public String getOpen() {
return open;
}
public void setOpen(String open) {
this.open = open == null ? null : open.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public Float getArea() {
return area;
}
public void setArea(Float area) {
this.area = area;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Float getProductSubtotal() {
return productSubtotal;
}
public void setProductSubtotal(Float productSubtotal) {
this.productSubtotal = productSubtotal;
}
public Float getV1() {
return v1;
}
public void setV1(Float v1) {
this.v1 = v1;
}
public Float getV2() {
return v2;
}
public void setV2(Float v2) {
this.v2 = v2;
}
public Float getV3() {
return v3;
}
public void setV3(Float v3) {
this.v3 = v3;
}
public String getDoorTypeName() {
return doorTypeName;
}
public void setDoorTypeName(String doorTypeName) {
this.doorTypeName = doorTypeName == null ? null : doorTypeName.trim();
}
} | [
"[email protected]"
] | |
536bfe1b73e189b2d4b2ea0ad53403f4ad6dcd59 | 3ff8443bb19fb0cf0dc0fc17051549881f91e9b6 | /app/src/main/java/com/arnela/rubiconapp/Ui/main/TvMovieListAdapter.java | fe0d0b415bd80046d71f14d43ff62a8b56237bf7 | [] | no_license | arn3la/mobileApp | 60530aa69a3e421138d376d7c3f3d55c6cff916b | 7e528b064aed88ad9a261eaabd2894bcdee15ee2 | refs/heads/master | 2020-03-21T00:34:22.265645 | 2018-06-19T23:33:18 | 2018-06-19T23:33:18 | 137,889,620 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,883 | java | package com.arnela.rubiconapp.Ui.main;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.arnela.rubiconapp.Data.DataModels.TvMovieVm;
import com.arnela.rubiconapp.Data.Helper.ItemClickListener;
import com.arnela.rubiconapp.Data.Helper.RoutesConstants;
import com.arnela.rubiconapp.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
public class TvMovieListAdapter extends RecyclerView.Adapter<TvMovieListAdapter.TvMovieViewHolder> {
private List<TvMovieVm> mMovieList;
private ItemClickListener mListener;
public TvMovieListAdapter(ItemClickListener listener) {
mMovieList = new ArrayList<>();
mListener = listener;
}
public void setSource(List<TvMovieVm> movies) {
mMovieList = movies;
}
public List<TvMovieVm> getSource() {
return mMovieList;
}
@NonNull
@Override
public TvMovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_movies, parent, false);
return new TvMovieViewHolder(itemView, mListener);
}
@Override
public void onBindViewHolder(final TvMovieViewHolder holder, int position) {
TvMovieVm movie = mMovieList.get(position);
holder.mTxtTitle.setText(movie.Title);
holder.mTxtGrade.setText(String.valueOf(movie.VoteAverage));
holder.MovieId = movie.Id;
Picasso.get().load(RoutesConstants.BASE_URL_IMG + movie.BackdropPath)
.placeholder(R.drawable.img_placeholder)
.transform(new CropCircleTransformation())
.into(holder.mImgMovie);
}
@Override
public int getItemCount() {
return mMovieList.size();
}
class TvMovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.txt_title_item)
TextView mTxtTitle;
@BindView(R.id.txt_grade)
TextView mTxtGrade;
@BindView(R.id.img_movie_pic)
ImageView mImgMovie;
private ItemClickListener mListener;
public int MovieId;
public TvMovieViewHolder(View itemView, ItemClickListener listener) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
mListener = listener;
}
@Override
public void onClick(View v) {
mListener.onItemClickListener(MovieId);
}
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.