blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
282137016f512928975d2b9902986af42e0f59d5
4e7ce544d5383a67279b3cff8194efb2d8296a57
/civcraft/src/com/avrgaming/civcraft/threading/tasks/TrommelAsyncTaskRegular.java
135c4c353687394933cb481fd5da445bed7f2fc7
[]
no_license
YourCoal/Project
658553333fa243c1e7cfb877654d630ce2a627e0
7c830b8f75692fbdcc380e959a77c019f3197bf9
refs/heads/master
2020-04-10T21:13:24.564032
2017-04-15T01:25:35
2017-04-15T01:25:35
50,268,051
0
1
null
null
null
null
UTF-8
Java
false
false
14,914
java
package com.avrgaming.civcraft.threading.tasks; import java.util.ArrayList; import java.util.HashSet; import java.util.Random; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.avrgaming.civcraft.exception.CivTaskAbortException; import com.avrgaming.civcraft.main.CivData; import com.avrgaming.civcraft.main.CivLog; import com.avrgaming.civcraft.main.CivMessage; import com.avrgaming.civcraft.object.StructureChest; import com.avrgaming.civcraft.object.TownChunk; import com.avrgaming.civcraft.structure.Structure; import com.avrgaming.civcraft.structure.Trommel; import com.avrgaming.civcraft.structure.Trommel.Mineral; import com.avrgaming.civcraft.threading.CivAsyncTask; import com.avrgaming.civcraft.threading.sync.request.UpdateInventoryRequest.Action; import com.avrgaming.civcraft.util.ItemManager; import com.avrgaming.civcraft.util.MultiInventory; public class TrommelAsyncTaskRegular extends CivAsyncTask { Trommel trommel; public static HashSet<String> debugTowns = new HashSet<String>(); public static void debug(Trommel trommel, String msg) { if (debugTowns.contains(trommel.getTown().getName())) { CivLog.warning("Trommel(Regular) Debug:"+trommel.getTown().getName()+":"+msg); } } public TrommelAsyncTaskRegular(Structure trommel) { this.trommel = (Trommel)trommel; } public void processTrommelUpdate() { if (!trommel.isActive()) { debug(trommel, "Trommel(Regular) inactive..."); return; } debug(trommel, "Processing Trommel(Regular) ..."); ArrayList<StructureChest> sources = trommel.getAllChestsById(1); ArrayList<StructureChest> destinations = trommel.getAllChestsById(2); if (sources.size() != 2 || destinations.size() != 2) { CivLog.error("Bad chests for Trommel(Regular) in town:"+trommel.getTown().getName()+" sources:"+sources.size()+" dests:"+destinations.size()); return; } MultiInventory source_inv = new MultiInventory(); MultiInventory dest_inv = new MultiInventory(); try { for (StructureChest src : sources) { this.syncLoadChunk(src.getCoord().getWorldname(), src.getCoord().getX(), src.getCoord().getZ()); Inventory tmp; try { tmp = this.getChestInventory(src.getCoord().getWorldname(), src.getCoord().getX(), src.getCoord().getY(), src.getCoord().getZ(), false); } catch (CivTaskAbortException e) { e.printStackTrace(); CivLog.warning("Trommel(Regular):"+e.getMessage()); return; } if (tmp == null) { trommel.skippedCounter++; return; } source_inv.addInventory(tmp); } boolean full = true; for (StructureChest dst : destinations) { this.syncLoadChunk(dst.getCoord().getWorldname(), dst.getCoord().getX(), dst.getCoord().getZ()); Inventory tmp; try { tmp = this.getChestInventory(dst.getCoord().getWorldname(), dst.getCoord().getX(), dst.getCoord().getY(), dst.getCoord().getZ(), false); } catch (CivTaskAbortException e) { e.printStackTrace(); CivLog.warning("Trommel(Regular):"+e.getMessage()); return; } if (tmp == null) { trommel.skippedCounter++; return; } dest_inv.addInventory(tmp); for (ItemStack stack : tmp.getContents()) { if (stack == null) { full = false; break; } } } if (full) { return; } } catch (InterruptedException e) { return; } debug(trommel, "Processing trommel:"+trommel.skippedCounter+1); ItemStack[] contents = source_inv.getContents(); for (int i = 0; i < trommel.skippedCounter+1; i++) { for(ItemStack stack : contents) { if (stack == null) { continue; } int mod = ((trommel.getTown().saved_trommel_level-1)/250)*4; if (ItemManager.getId(stack) == CivData.COBBLESTONE) { try { this.updateInventory(Action.REMOVE, source_inv, ItemManager.createItemStack(CivData.COBBLESTONE, 1)); } catch (InterruptedException e) { return; } Random rand = new Random(); int randMax = Trommel.COBBLE_MAX_RATE; int rand1 = rand.nextInt(randMax); ItemStack newItem; if (rand1 < ((int)((trommel.getGravelChance(Mineral.BLOCK)+mod)*randMax))) { ItemStack thatItem = ItemManager.createItemStack(CivData.COAL_BLOCK, 1); for (TownChunk tc : trommel.getTown().getTownChunks()) { if (tc.district.getID().equals(5)) { int tcChunkX = tc.getChunkCoord().getX(); int tcChunkZ = tc.getChunkCoord().getZ(); int sChunkX = trommel.getCorner().getLocation().getChunk().getX(); int sChunkZ = trommel.getCorner().getLocation().getChunk().getZ(); if (tcChunkX == sChunkX && tcChunkZ == sChunkZ) { CivMessage.global("Chunk SELECTED!!! :D"); int theOre = rand.nextInt(110); if (theOre <= 50) { thatItem = ItemManager.createItemStack(CivData.IRON_BLOCK, 1); } else if (theOre >= 51 && theOre <= 75) { thatItem = ItemManager.createItemStack(CivData.GOLD_BLOCK, 1); } else if (theOre >= 76 && theOre <= 95) { thatItem = ItemManager.createItemStack(CivData.REDSTONE_BLOCK, 1); } else if (theOre >= 96 && theOre <= 105) { thatItem = ItemManager.createItemStack(CivData.DIAMOND_BLOCK, 1); } else if (theOre >= 106) { thatItem = ItemManager.createItemStack(CivData.EMERALD_BLOCK, 1); } else { CivMessage.global("Trommel FAILED!? Test#ID: "+theOre); } } } } newItem = thatItem; } else if (rand1 < ((int)((trommel.getGravelChance(Mineral.EMERALD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.EMERALD, 1); } else if (rand1 < ((int)((trommel.getGravelChance(Mineral.DIAMOND)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.DIAMOND, 1); } else if (rand1 < ((int)((trommel.getGravelChance(Mineral.REDSTONE)+mod)*randMax))) { int red = rand.nextInt(4); if (red < 2) red = 2; newItem = ItemManager.createItemStack(CivData.REDSTONE_DUST, red); } else if (rand1 < ((int)((trommel.getGravelChance(Mineral.GOLD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.GOLD_INGOT, 1); } else if (rand1 < ((int)((trommel.getGravelChance(Mineral.IRON)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.IRON_INGOT, 1); } else { int factor = rand.nextInt(5); if (factor == 1) { newItem = ItemManager.createItemStack(CivData.DIRT, 1); } else if (factor == 2) { newItem = ItemManager.createItemStack(CivData.GRAVEL, 1); } else { newItem = ItemManager.createItemStack(CivData.AIR, 1); } } try { debug(trommel, "Updating inventory:"+newItem); this.updateInventory(Action.ADD, dest_inv, newItem); } catch (InterruptedException e) { return; } break; } if (ItemManager.getId(stack) == CivData.STONE) { if (ItemManager.getData(stack) == ItemManager.getData(ItemManager.getMaterialData(CivData.STONE, CivData.DATA_0))) { try { this.updateInventory(Action.REMOVE, source_inv, ItemManager.createItemStack(CivData.STONE, 1, (short) CivData.DATA_0)); } catch (InterruptedException e) { return; } Random rand = new Random(); int randMax = Trommel.STONE_MAX_RATE; int rand1 = rand.nextInt(randMax); ItemStack newItem; if (rand1 < ((int)((trommel.getStoneChance(Mineral.EMERALD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.EMERALD, 1); } else if (rand1 < ((int)((trommel.getStoneChance(Mineral.DIAMOND)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.DIAMOND, 1); } else if (rand1 < ((int)((trommel.getStoneChance(Mineral.REDSTONE)+mod)*randMax))) { int red = rand.nextInt(4); if (red < 2) red = 2; newItem = ItemManager.createItemStack(CivData.REDSTONE_DUST, red); } else if (rand1 < ((int)((trommel.getStoneChance(Mineral.GOLD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.GOLD_INGOT, 1); } else if (rand1 < ((int)((trommel.getStoneChance(Mineral.IRON)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.IRON_INGOT, 1); } else { int factor = rand.nextInt(5); if (factor == 1) { newItem = ItemManager.createItemStack(CivData.DIRT, 1); } else if (factor == 2) { newItem = ItemManager.createItemStack(CivData.GRAVEL, 1); } else { newItem = ItemManager.createItemStack(CivData.AIR, 1); } } try { debug(trommel, "Updating inventory:"+newItem); this.updateInventory(Action.ADD, dest_inv, newItem); } catch (InterruptedException e) { return; } break; } if (ItemManager.getData(stack) == ItemManager.getData(ItemManager.getMaterialData(CivData.STONE, CivData.GRANITE))) { try { this.updateInventory(Action.REMOVE, source_inv, ItemManager.createItemStack(CivData.STONE, 1, (short) CivData.GRANITE)); } catch (InterruptedException e) { return; } Random rand = new Random(); int randMax = Trommel.GRANITE_MAX_RATE; int rand1 = rand.nextInt(randMax); ItemStack newItem; if (rand1 < ((int)((trommel.getGraniteChance(Mineral.EMERALD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.EMERALD, 1); } else if (rand1 < ((int)((trommel.getGraniteChance(Mineral.DIAMOND)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.DIAMOND, 1); } else if (rand1 < ((int)((trommel.getGraniteChance(Mineral.REDSTONE)+mod)*randMax))) { int red = rand.nextInt(4); if (red < 2) red = 2; newItem = ItemManager.createItemStack(CivData.REDSTONE_DUST, red); } else if (rand1 < ((int)((trommel.getGraniteChance(Mineral.GOLD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.GOLD_INGOT, 1); } else if (rand1 < ((int)((trommel.getGraniteChance(Mineral.IRON)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.IRON_INGOT, 1); } else { int factor = rand.nextInt(5); if (factor == 1) { newItem = ItemManager.createItemStack(CivData.DIRT, 1); } else if (factor == 2) { newItem = ItemManager.createItemStack(CivData.GRAVEL, 1); } else { newItem = ItemManager.createItemStack(CivData.AIR, 1); } } try { debug(trommel, "Updating inventory:"+newItem); this.updateInventory(Action.ADD, dest_inv, newItem); } catch (InterruptedException e) { return; } break; } if (ItemManager.getData(stack) == ItemManager.getData(ItemManager.getMaterialData(CivData.STONE, CivData.DIORITE))) { try { this.updateInventory(Action.REMOVE, source_inv, ItemManager.createItemStack(CivData.STONE, 1, (short) CivData.DIORITE)); } catch (InterruptedException e) { return; } Random rand = new Random(); int randMax = Trommel.DIORITE_MAX_RATE; int rand1 = rand.nextInt(randMax); ItemStack newItem; if (rand1 < ((int)((trommel.getDioriteChance(Mineral.EMERALD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.EMERALD, 1); } else if (rand1 < ((int)((trommel.getDioriteChance(Mineral.DIAMOND)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.DIAMOND, 1); } else if (rand1 < ((int)((trommel.getDioriteChance(Mineral.REDSTONE)+mod)*randMax))) { int red = rand.nextInt(4); if (red < 2) red = 2; newItem = ItemManager.createItemStack(CivData.REDSTONE_DUST, red); } else if (rand1 < ((int)((trommel.getDioriteChance(Mineral.GOLD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.GOLD_INGOT, 1); } else if (rand1 < ((int)((trommel.getDioriteChance(Mineral.IRON)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.IRON_INGOT, 1); } else { int factor = rand.nextInt(5); if (factor == 1) { newItem = ItemManager.createItemStack(CivData.DIRT, 1); } else if (factor == 2) { newItem = ItemManager.createItemStack(CivData.GRAVEL, 1); } else { newItem = ItemManager.createItemStack(CivData.AIR, 1); } } try { debug(trommel, "Updating inventory:"+newItem); this.updateInventory(Action.ADD, dest_inv, newItem); } catch (InterruptedException e) { return; } break; } if (ItemManager.getData(stack) == ItemManager.getData(ItemManager.getMaterialData(CivData.STONE, CivData.ANDESITE))) { try { this.updateInventory(Action.REMOVE, source_inv, ItemManager.createItemStack(CivData.STONE, 1, (short) CivData.ANDESITE)); } catch (InterruptedException e) { return; } Random rand = new Random(); int randMax = Trommel.ANDESITE_MAX_RATE; int rand1 = rand.nextInt(randMax); ItemStack newItem; if (rand1 < ((int)((trommel.getAndesiteChance(Mineral.EMERALD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.EMERALD, 1); } else if (rand1 < ((int)((trommel.getAndesiteChance(Mineral.DIAMOND)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.DIAMOND, 1); } else if (rand1 < ((int)((trommel.getAndesiteChance(Mineral.REDSTONE)+mod)*randMax))) { int red = rand.nextInt(4); if (red < 2) red = 2; newItem = ItemManager.createItemStack(CivData.REDSTONE_DUST, red); } else if (rand1 < ((int)((trommel.getAndesiteChance(Mineral.GOLD)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.GOLD_INGOT, 1); } else if (rand1 < ((int)((trommel.getAndesiteChance(Mineral.IRON)+mod)*randMax))) { newItem = ItemManager.createItemStack(CivData.IRON_INGOT, 1); } else { int factor = rand.nextInt(5); if (factor == 1) { newItem = ItemManager.createItemStack(CivData.DIRT, 1); } else if (factor == 2) { newItem = ItemManager.createItemStack(CivData.GRAVEL, 1); } else { newItem = ItemManager.createItemStack(CivData.AIR, 1); } } try { debug(trommel, "Updating inventory:"+newItem); this.updateInventory(Action.ADD, dest_inv, newItem); } catch (InterruptedException e) { return; } break; } } } } trommel.skippedCounter = 0; } @Override public void run() { if (this.trommel.lock.tryLock()) { try { try { processTrommelUpdate(); } catch (Exception e) { e.printStackTrace(); } } finally { this.trommel.lock.unlock(); } } else { debug(this.trommel, "Failed to get lock while trying to start task, aborting."); } } }
[ "yourcoal5446@gmail.com" ]
yourcoal5446@gmail.com
02c83fb9a38ec6f73b238b2f83c761f815a30724
ce9f01ded30437569eb7b4c7694fb841fb4fe165
/copy/src/main/java/com/hopefully/domain/Pic.java
867399eac29ee8083475f63bc373fb2bb1a3f767
[]
no_license
SJFY/springProject2
fa1efdb68e2c72844fc11c115fd39daf38511bd7
aa7e6d111fdd64bf79db18649e4bdf569fd13b18
refs/heads/master
2021-08-19T17:24:41.487521
2017-11-27T02:40:52
2017-11-27T02:40:52
112,106,870
0
0
null
null
null
null
UTF-8
Java
false
false
2,590
java
package com.hopefully.domain; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Objects; /** * A Pic. */ @Entity @Table(name = "pic") @Document(indexName = "pic") public class Pic implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Lob @Column(name = "image", nullable = false) private byte[] image; @Column(name = "image_content_type", nullable = false) private String imageContentType; @ManyToOne(optional = false) @NotNull private Course coursepic; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public byte[] getImage() { return image; } public Pic image(byte[] image) { this.image = image; return this; } public void setImage(byte[] image) { this.image = image; } public String getImageContentType() { return imageContentType; } public Pic imageContentType(String imageContentType) { this.imageContentType = imageContentType; return this; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } public Course getCoursepic() { return coursepic; } public Pic coursepic(Course course) { this.coursepic = course; return this; } public void setCoursepic(Course course) { this.coursepic = course; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pic pic = (Pic) o; if (pic.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), pic.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Pic{" + "id=" + getId() + ", image='" + getImage() + "'" + ", imageContentType='" + imageContentType + "'" + "}"; } }
[ "jiefeis2@illinois.edu" ]
jiefeis2@illinois.edu
d49d6927a1daff6e0e00248d2f279926be77c1b3
aea4dce5215cf4a4bd6898102820dc177ab84248
/practice1.java
94ffca46d1ef6901e4ecb2cfcc2d1e865ccf1f6c
[]
no_license
Lbarte/java-training
84a17300b496f92fe3123469d730705dfc9cf9d4
18a6945f929bf216cac652704c0c3c2bd7cd8135
refs/heads/main
2023-06-02T16:00:12.062707
2021-06-24T18:26:14
2021-06-24T18:26:14
365,777,306
0
0
null
2021-05-12T20:47:10
2021-05-09T14:51:14
Java
UTF-8
Java
false
false
9,826
java
package com.practice; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; public class practice1 { //n numbers() BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); if (n > 0) { int max = Integer.parseInt(reader.readLine()); for(int i = 0; i < n-1; i++) { int nq = Integer.parseInt(reader.readLine()); max = nq > max ? nq : max; } System.out.println(max); } //old code, new requirements public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(reader.readLine()); int b = Integer.parseInt(reader.readLine()); int c = Integer.parseInt(reader.readLine()); int d = Integer.parseInt(reader.readLine()); int q = Integer.parseInt(reader.readLine()); int minimum = min(a,b,c,d,q); System.out.println("Minimum = " + minimum); } public static int min(int a, int b, int c, int d, int q) { int mq = a < b ? a : b; int mw = c < d ? c : d; int me = mq < mw ? mq : mw; return me < q ? me : q; } //sum() {} BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int sum = 0; String ns; while (true) { ns = reader.readLine(); if (ns.equals("sum")) { break; } else { sum += Integer.parseInt(ns); } } System.out.println(sum); //current date() //import java.util.* and java.text.* Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MM dd yyyy"); System.out.println(formatter.format(date)); //classes Dog, Cat and Mouse{} public static class Dog { public String name, address; public int age; public Dog(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } } public static class Cat { public String name, address; public int age; public Cat(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } } Dog d = new Dog("x",1,"x"); Cat c = new Cat("x",2,"x"); //classes Man and Woman {} public static class Man { public String name, address; public int age; public Man() { name = "x"; address = "x"; age = 1; } public Man(String name) { this.name = name; address = "x"; age = 1; } public Man(String name, int age) { this.name = name; this.age = age; address = "x"; } public Man (String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public String toString() { return name; } } public static class Woman { public String name, address; public int age; public Woman() { name = "x"; address = "x"; age = 1; } public Woman(String name) { this.name = name; address = "x"; age = 1; } public Woman(String name, int age) { this.name = name; this.age = age; address = "x"; } public Woman (String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public String toString() { return name; } } Man mq = new Man("x",21,"x"); Man mw = new Man("x",22,"x"); Woman wq = new Woman("c",21,"c"); Woman ww = new Woman("c",21,"c"); System.out.println(mq.name+" "+mq.age+" "+mq.address); System.out.println(mw.name+" "+mw.age+" "+mq.address); System.out.println(ww.name+" "+ww.age+" "+ww.address); System.out.println(wq.name+" "+wq.age+" "+wq.address); //class Duck {} super public static class Dog extends Duck { public String toString() { return "Dog"; } } public static class Cat extends Duck { public String toString() { return "Cat"; } } Dog dq = new Dog(); Dog dw = new Dog(); Cat cq = new Cat(); Cat cw = new Cat(); System.out.println(dq); System.out.println(dw); System.out.println(cq); System.out.println(cw); //class Circle() {} public int centerX, centerY, radius, width, color; public void initialize(int centerX, int centerY, int radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public void initialize(int centerX, int centerY, int radius, int width) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.width = width; } public void initialize(int centerX, int centerY, int radius, int width, int color) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.width = width; this.color = color; } //class Rectangle() {} public int left, top, width, height; public void initialize(int left, int top) { this.left = left; this.top = top; } public void initialize(int left, int top, int width, int height) { this.left = left; this.top = top; this.width = width; this.height = height; } public void initialize(int left, int top, int height) { this.left = left; this.top = top; this.height = height; } public void initialize(Rectangle r) { this.left = r.left; this.top = r.top; this.width = r.width; this.height = r.height; } //class Person() {} public String name; public int age; public void initialize(String name, int age) { this.name = name; this.age = age; } Person person = new Person(); person.initialize("pers", 21); //class Friend() {} public String name; public int age; public char sex; public Friend(String name) { this.name = name; } public Friend(String name, int age) { this.name = name; this.age = age; } public Friend(String name, int age, char sex) { this.name = name; this.age = age; this.sex = sex; } //class Cat() {} public String name, address, color; public int weight, age; public Cat(String name) { this.name = name; this.weight = 1; this.age = 1; this.color = ",,"; } public Cat(String name, int weight, int age) { this.name = name; this.weight = weight; this.age = age; this.color = ",,"; } public Cat(String name, int age) { this.name = name; this.age = age; this.weight = 1; this.color = ",,"; } public Cat(int weight, String color) { this.weight = weight; this.color = color; this.age = 1; } public Cat(int weight, String color, String address) { this.weight = weight; this.color = color; this.address = address; this.age = 1; } //class Dog() {} public String name, color; public int height; public Dog(String name) { this.name = name; } public Dog(String name, int height) { this.name = name; this.height = height; } public Dog(String name, int height, String color) { this.name = name; this.height = height; this.color = color; } //class Circle() {} public int centerX, centerY, radius, width, color; public Circle(int centerX, int centerY, int radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public Circle(int centerX, int centerY, int radius, int width) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.width = width; } public Circle(int centerX, int centerY, int radius, int width, int color) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.width = width; this.color = color; } //class Rectangle() {} public int left, top, width, height; public Rectangle(int left, int top) { this.left = left; this.top = top; } public Rectangle(int left, int top, int width, int height) { this.left = left; this.top = top; this.width = width; this.height = height; } public Rectangle(int left, int top, int height) { this.left = left; this.top = top; this.height = height; } public Rectangle(Rectangle r) { this.left = r.left; this.top = r.top; this.width = r.width; this.height = r.height; } //class Circle() {} public Circle (double x) { this.x = x; this.y = 5; this.radius = 10; } public Circle (double x, double y) { this.x = x; this.y = y; this.radius = 10; } public Circle (double x, double y, double radius) { this.x = x; this.y = y; this.radius = radius; } public Circle (Circle c) { this.x = c.x; this.y = c.y; this.radius = c.radius; } public Circle() { this.x = 5; this.y = 5; this.radius = 10; } }
[ "noreply@github.com" ]
noreply@github.com
f5caeb30d1ae11d2654586871903866a291c716c
9f4737ed4939c660f0668a2047e41810a1b01f7f
/src/com/basic/autowire/Test.java
dd56d2dc0f6f02f1e0b0a0fea45ac9980e449a1a
[]
no_license
svmgarg/SpringTutorial
33c2869b6b8b6ea7386fc69074f694c76ccf0e3a
971f18131c98cc21b2645a07db09f69031ff7247
refs/heads/master
2021-01-20T06:04:34.766525
2017-05-13T09:06:22
2017-05-13T09:06:22
89,838,991
0
0
null
null
null
null
UTF-8
Java
false
false
626
java
package com.basic.autowire; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Test { public static void main(String[] args) { // XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("AutowiringByType.xml")); // XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("AutowiringByName.xml")); XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("AutowiringByConstructor.xml")); Employee employee = (Employee)factory.getBean("employee"); System.out.println("Employee is ....\n"+ employee); } }
[ "svmgarg@gmail.com" ]
svmgarg@gmail.com
f78809bc35760619b3e7f58fc6a295f8521e3000
e770778e830e9a34b926c5a4df94b011a7e039b1
/ZDIM/src/zhwx/common/view/dialog/IBaseAdapter.java
5bc8d5191f3175529b71785d0db4c78b1ec7a74f
[]
no_license
lixinxiyou01/zdhx-im-yunxin-run
bc5290458dd0e8a4d37339da7ddb07a6d10ad317
3ad40223c15dac575e860136e24be690387405ad
refs/heads/master
2021-01-12T06:51:59.284750
2017-10-10T08:25:40
2017-10-10T08:25:40
83,505,395
3
4
null
null
null
null
UTF-8
Java
false
false
3,880
java
package zhwx.common.view.dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.BaseAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * com.zdhx.edu.im.common.dialog in ECDemo_Android * Created by 容联•云通讯 Modify By Li.Xin @ 中电和讯 on 2015/4/18. */ public abstract class IBaseAdapter<T> extends BaseAdapter { protected Context mContext; protected List<T> data; protected LayoutInflater mLayoutInflater; private boolean mNotifyOnChange = true; public IBaseAdapter(Context ctx) { mContext = ctx; mLayoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); data = new ArrayList<T>(); } public IBaseAdapter(Context ctx ,List<T> data) { this(ctx); this.data = data; } public View inflateView(int resource) { return mLayoutInflater.inflate(resource , null); } public List<T> getData() { return data; } public void replace(int position , T t) { data.remove(position); data.add(position , t); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void insert(int position , T t) { data.add(position, t); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void addAll(int position , Collection<T> t) { data.addAll(position, t); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void add(T t) { data.add(t); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void setData(Collection<T> t) { data.clear(); addData(t); } public void addData(T[] ts) { if(ts == null || ts.length == 0) { return ; } for(int i = 0 ; i < ts.length ; i++) { data.add(ts[i]); } if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void clear(boolean notify) { data.clear(); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void addData(Collection<T> t) { addData(t, this.mNotifyOnChange); } public void addData(Collection<T> t ,boolean notify) { data.addAll(t); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void reset() { clear(this.mNotifyOnChange); } public void remove(int position) { data.remove(position); if(!mNotifyOnChange) { return ; } notifyDataSetChanged(); } public void addOnly(T t) { data.add(t); } public T removeOnly(int position) { return data.remove(position); } public void removeOnly(T t) { data.remove(t); } public void unNofity() { this.mNotifyOnChange = false; } public boolean hasDataAndRemove(T t) { boolean remove = data.remove(t); if(mNotifyOnChange) { notifyDataSetChanged(); } return remove; } public Context getContext() { return mContext; } public int getPosition(T t) { return data.indexOf(t); } @Override public int getCount() { return data.size(); } @Override public long getItemId(int position) { return position; } @Override public Object getItem(int position) { return data.get(position); } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); this.mNotifyOnChange = true; } }
[ "lixin890403@163.com" ]
lixin890403@163.com
c2e7d9ce92fd3a369f88c56854be9bbd78d09a7f
b28c1d704e1880671dad31f7aea74e61ea8e8af5
/code/nm-framework-parent/test-rabbitmq-consumer/src/test/java/com/ningmeng/consumer/Consumer02.java
75c67c08296393580e1f94603447d32dca744244
[]
no_license
1704AClass/work_mjl
7f0f741fe58daf9c6a98dc907c4ed34ade5c7fda
50703c56af1ae7fa343ffade5c8c4f14c804d5ee
refs/heads/dev
2022-11-28T17:10:55.672029
2020-03-17T04:12:53
2020-03-17T04:12:53
240,469,526
0
0
null
2020-02-15T01:41:36
2020-02-14T09:14:17
Java
UTF-8
Java
false
false
1,688
java
package com.ningmeng.consumer; import com.rabbitmq.client.*; import java.io.IOException; public class Consumer02 { private static final String QUEUE_INFORM_EMAIL = "inform_queue_email"; private static final String EXCHANGE_FANOUT_INFORM="inform_exchange_fanout"; public static void main(String[] args) { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); factory.setPort(5672); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.FANOUT); channel.queueDeclare(QUEUE_INFORM_EMAIL, true, false, false, null); channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_FANOUT_INFORM,""); DefaultConsumer consumer=new DefaultConsumer(channel){ public void handleDelivery(String concumerTag, Envelope envelope,AMQP.BasicProperties properties, byte[] body)throws IOException{ String exchange = envelope.getExchange(); String routingKey = envelope.getRoutingKey(); long deliveryTag = envelope.getDeliveryTag(); String msg = new String(body, "utf-8"); System.out.println("message..."+msg); } }; channel.basicConsume(QUEUE_INFORM_EMAIL,true, consumer); }catch (Exception e){ e.printStackTrace(); } } }
[ "wuan_mjl@163.com" ]
wuan_mjl@163.com
7955cece2b15832281bb563a9055a04895944016
67f86bb3d09cbc86cac698b3f0abaf01457a966a
/master/java-ee-cdi-producer-methods-tutorial/com-byteslounge-cdi/src/main/java/com/byteslounge/bean/impl/EmailMessageSender.java
f9c014788950d8e689bd671a2f8557c118aa5e0b
[ "MIT" ]
permissive
tied/DevArtifacts
efba1ccea5f0d832d4227c9fe1a040cb93b9ad4f
931aabb8cbf27656151c54856eb2ea7d1153203a
refs/heads/master
2020-06-06T01:48:32.149972
2018-12-08T15:26:16
2018-12-08T15:26:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package com.byteslounge.bean.impl; import com.byteslounge.bean.MessageSender; public class EmailMessageSender implements MessageSender { @Override public void sendMessage() { System.out.println("Sending email message"); } }
[ "alexander.rogalsky@yandex.ru" ]
alexander.rogalsky@yandex.ru
264ac204e288eea2c86a4c20f5e8150aab18a3b6
f1b29b605de189fc906f678ced73bd71401deb30
/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
5a5a85116e5ad581afdfe1c4f081b946e468cb2f
[ "Apache-2.0" ]
permissive
pyl75/Spring-framework
39eafc2cac117ff1651d1875a6b1ac062b180c26
cc13b2a1f00f503ce3cf27abde7825b6b6d02285
refs/heads/master
2023-01-31T13:08:14.445794
2017-08-15T10:33:03
2017-08-15T10:33:03
null
0
0
null
null
null
null
GB18030
Java
false
false
67,146
java
/* * Copyright 2002-2017 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 org.springframework.beans.factory.support; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Provider; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.beans.factory.CannotLoadBeanClassException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartFactoryBean; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.NamedBeanHolder; import org.springframework.core.OrderComparator; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CompositeIterator; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Default implementation of the * {@link org.springframework.beans.factory.ListableBeanFactory} and * {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory * based on bean definition objects. * * <p>Typical usage is registering all bean definitions first (possibly read * from a bean definition file), before accessing beans. Bean definition lookup * is therefore an inexpensive operation in a local bean definition table, * operating on pre-built bean definition metadata objects. * * <p>Can be used as a standalone bean factory, or as a superclass for custom * bean factories. Note that readers for specific bean definition formats are * typically implemented separately rather than as bean factory subclasses: * see for example {@link PropertiesBeanDefinitionReader} and * {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. * * <p>For an alternative implementation of the * {@link org.springframework.beans.factory.ListableBeanFactory} interface, * have a look at {@link StaticListableBeanFactory}, which manages existing * bean instances rather than creating new ones based on bean definitions. * * @author Rod Johnson * @author Juergen Hoeller * @author Sam Brannen * @author Costin Leau * @author Chris Beams * @author Phillip Webb * @author Stephane Nicoll * @since 16 April 2001 * @see StaticListableBeanFactory * @see PropertiesBeanDefinitionReader * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader */ @SuppressWarnings("serial") public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable { @Nullable private static Class<?> javaxInjectProviderClass; static { try { javaxInjectProviderClass = ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader()); } catch (ClassNotFoundException ex) { // JSR-330 API not available - Provider interface simply not supported then. javaxInjectProviderClass = null; } } /** Map from serialized id to factory instance */ private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories = new ConcurrentHashMap<>(8); /** Optional id for this factory, for serialization purposes */ @Nullable private String serializationId; /** Whether to allow re-registration of a different definition with the same name */ private boolean allowBeanDefinitionOverriding = true; /** Whether to allow eager class loading even for lazy-init beans */ private boolean allowEagerClassLoading = true; /** Optional OrderComparator for dependency Lists and arrays */ @Nullable private Comparator<Object> dependencyComparator; /** Resolver to use for checking if a bean definition is an autowire candidate */ private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver(); /** Map from dependency type to corresponding autowired value */ private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16); /** Map of bean definition objects, keyed by bean name */ private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256); /** Map of singleton and non-singleton bean names, keyed by dependency type */ private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64); /** Map of singleton-only bean names, keyed by dependency type */ private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64); /** List of bean definition names, in registration order */ private volatile List<String> beanDefinitionNames = new ArrayList<>(256); /** List of names of manually registered singletons, in registration order */ private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16); /** Cached array of bean definition names in case of frozen configuration */ @Nullable private volatile String[] frozenBeanDefinitionNames; /** Whether bean definition metadata may be cached for all beans */ private volatile boolean configurationFrozen = false; /** * Create a new DefaultListableBeanFactory. */ public DefaultListableBeanFactory() { super(); } /** * Create a new DefaultListableBeanFactory with the given parent. * @param parentBeanFactory the parent BeanFactory */ public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) { super(parentBeanFactory); } /** * Specify an id for serialization purposes, allowing this BeanFactory to be * deserialized from this id back into the BeanFactory object, if needed. */ public void setSerializationId(@Nullable String serializationId) { if (serializationId != null) { serializableFactories.put(serializationId, new WeakReference<>(this)); } else if (this.serializationId != null) { serializableFactories.remove(this.serializationId); } this.serializationId = serializationId; } /** * Return an id for serialization purposes, if specified, allowing this BeanFactory * to be deserialized from this id back into the BeanFactory object, if needed. * @since 4.1.2 */ @Nullable public String getSerializationId() { return this.serializationId; } /** * Set whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * If not, an exception will be thrown. This also applies to overriding aliases. * <p>Default is "true". * @see #registerBeanDefinition */ public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } /** * Return whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * @since 4.1.2 */ public boolean isAllowBeanDefinitionOverriding() { return this.allowBeanDefinitionOverriding; } /** * Set whether the factory is allowed to eagerly load bean classes * even for bean definitions that are marked as "lazy-init". * <p>Default is "true". Turn this flag off to suppress class loading * for lazy-init beans unless such a bean is explicitly requested. * In particular, by-type lookups will then simply ignore bean definitions * without resolved class name, instead of loading the bean classes on * demand just to perform a type check. * @see AbstractBeanDefinition#setLazyInit */ public void setAllowEagerClassLoading(boolean allowEagerClassLoading) { this.allowEagerClassLoading = allowEagerClassLoading; } /** * Return whether the factory is allowed to eagerly load bean classes * even for bean definitions that are marked as "lazy-init". * @since 4.1.2 */ public boolean isAllowEagerClassLoading() { return this.allowEagerClassLoading; } /** * Set a {@link java.util.Comparator} for dependency Lists and arrays. * @since 4.0 * @see org.springframework.core.OrderComparator * @see org.springframework.core.annotation.AnnotationAwareOrderComparator */ public void setDependencyComparator(@Nullable Comparator<Object> dependencyComparator) { this.dependencyComparator = dependencyComparator; } /** * Return the dependency comparator for this BeanFactory (may be {@code null}. * @since 4.0 */ @Nullable public Comparator<Object> getDependencyComparator() { return this.dependencyComparator; } /** * Set a custom autowire candidate resolver for this BeanFactory to use * when deciding whether a bean definition should be considered as a * candidate for autowiring. */ public void setAutowireCandidateResolver(final AutowireCandidateResolver autowireCandidateResolver) { Assert.notNull(autowireCandidateResolver, "AutowireCandidateResolver must not be null"); if (autowireCandidateResolver instanceof BeanFactoryAware) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(DefaultListableBeanFactory.this); return null; }, getAccessControlContext()); } else { ((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(this); } } this.autowireCandidateResolver = autowireCandidateResolver; } /** * Return the autowire candidate resolver for this BeanFactory (never {@code null}). */ public AutowireCandidateResolver getAutowireCandidateResolver() { return this.autowireCandidateResolver; } @Override public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { super.copyConfigurationFrom(otherFactory); if (otherFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory; this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding; this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading; this.dependencyComparator = otherListableFactory.dependencyComparator; // A clone of the AutowireCandidateResolver since it is potentially BeanFactoryAware... setAutowireCandidateResolver(BeanUtils.instantiateClass(getAutowireCandidateResolver().getClass())); // Make resolvable dependencies (e.g. ResourceLoader) available here as well... this.resolvableDependencies.putAll(otherListableFactory.resolvableDependencies); } } //--------------------------------------------------------------------- // Implementation of remaining BeanFactory methods //--------------------------------------------------------------------- @Override public <T> T getBean(Class<T> requiredType) throws BeansException { return getBean(requiredType, (Object[]) null); } @Override public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException { NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args); if (namedBean != null) { return namedBean.getBeanInstance(); } BeanFactory parent = getParentBeanFactory(); if (parent != null) { return (args != null ? parent.getBean(requiredType, args) : parent.getBean(requiredType)); } throw new NoSuchBeanDefinitionException(requiredType); } //--------------------------------------------------------------------- // Implementation of ListableBeanFactory interface //--------------------------------------------------------------------- @Override public boolean containsBeanDefinition(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); return this.beanDefinitionMap.containsKey(beanName); } @Override public int getBeanDefinitionCount() { return this.beanDefinitionMap.size(); } @Override public String[] getBeanDefinitionNames() { String[] frozenNames = this.frozenBeanDefinitionNames; if (frozenNames != null) { return frozenNames.clone(); } else { return StringUtils.toStringArray(this.beanDefinitionNames); } } @Override public String[] getBeanNamesForType(ResolvableType type) { return doGetBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type) { return getBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); } Map<Class<?>, String[]> cache = (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType); String[] resolvedBeanNames = cache.get(type); if (resolvedBeanNames != null) { return resolvedBeanNames; } resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { cache.put(type, resolvedBeanNames); } return resolvedBeanNames; } private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List<String> result = new ArrayList<>(); // Check all bean definitions. for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name // is not defined as alias for some other bean. if (!isAlias(beanName)) { try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. if (!mbd.isAbstract() && (allowEagerInit || ((mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading())) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { // In case of FactoryBean, match object created by FactoryBean. boolean isFactoryBean = isFactoryBean(beanName, mbd); BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); boolean matchFound = (allowEagerInit || !isFactoryBean || (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) && (includeNonSingletons || (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) && isTypeMatch(beanName, type); if (!matchFound && isFactoryBean) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX + beanName; matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); } if (matchFound) { result.add(beanName); } } } catch (CannotLoadBeanClassException ex) { if (allowEagerInit) { throw ex; } // Probably contains a placeholder: let's ignore it for type matching purposes. if (this.logger.isDebugEnabled()) { this.logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex); } onSuppressedException(ex); } catch (BeanDefinitionStoreException ex) { if (allowEagerInit) { throw ex; } // Probably contains a placeholder: let's ignore it for type matching purposes. if (this.logger.isDebugEnabled()) { this.logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex); } onSuppressedException(ex); } } } // Check manually registered singletons too. for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean(beanName)) { if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { result.add(beanName); // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX + beanName; } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add(beanName); } } catch (NoSuchBeanDefinitionException ex) { // Shouldn't happen - probably a result of circular reference resolution... if (logger.isDebugEnabled()) { logger.debug("Failed to check manually registered singleton with name '" + beanName + "'", ex); } } } return StringUtils.toStringArray(result); } /** * Check whether the specified bean would need to be eagerly initialized * in order to determine its type. * @param factoryBeanName a factory-bean reference that the bean definition * defines a factory method for * @return whether eager initialization is necessary */ private boolean requiresEagerInitForType(@Nullable String factoryBeanName) { return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName)); } @Override public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException { return getBeansOfType(type, true, true); } @Override public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); Map<String, T> result = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { try { result.put(beanName, getBean(beanName, type)); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; String exBeanName = bce.getBeanName(); if (exBeanName != null && isCurrentlyInCreation(exBeanName)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Ignoring match to currently created bean '" + exBeanName + "': " + ex.getMessage()); } onSuppressedException(ex); // Ignore: indicates a circular reference when autowiring constructors. // We want to find matches other than the currently created bean itself. continue; } } throw ex; } } return result; } @Override public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) { List<String> results = new ArrayList<>(); for (String beanName : this.beanDefinitionNames) { BeanDefinition beanDefinition = getBeanDefinition(beanName); if (!beanDefinition.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) { results.add(beanName); } } for (String beanName : this.manualSingletonNames) { if (!results.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { results.add(beanName); } } return results.toArray(new String[results.size()]); } @Override public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) { String[] beanNames = getBeanNamesForAnnotation(annotationType); Map<String, Object> results = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { results.put(beanName, getBean(beanName)); } return results; } /** * Find a {@link Annotation} of {@code annotationType} on the specified * bean, traversing its interfaces and super classes if no annotation can be * found on the given class itself, as well as checking its raw bean class * if not found on the exposed bean reference (e.g. in case of a proxy). */ @Override public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException{ A ann = null; Class<?> beanType = getType(beanName); if (beanType != null) { ann = AnnotationUtils.findAnnotation(beanType, annotationType); } if (ann == null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; if (abd.hasBeanClass()) { ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType); } } } return ann; } //--------------------------------------------------------------------- // Implementation of ConfigurableListableBeanFactory interface //--------------------------------------------------------------------- @Override public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) { Assert.notNull(dependencyType, "Dependency type must not be null"); if (autowiredValue != null) { if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) { throw new IllegalArgumentException("Value [" + autowiredValue + "] does not implement specified dependency type [" + dependencyType.getName() + "]"); } this.resolvableDependencies.put(dependencyType, autowiredValue); } } @Override public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) throws NoSuchBeanDefinitionException { return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver()); } /** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) throws NoSuchBeanDefinitionException { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); if (containsBeanDefinition(beanDefinitionName)) { return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); } else if (containsSingleton(beanName)) { return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver); } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver); } else if (parent instanceof ConfigurableListableBeanFactory) { // If no DefaultListableBeanFactory, can't pass the resolver along. return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor); } else { return true; } } /** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param mbd the merged bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); resolveBeanClass(mbd, beanDefinitionName); if (mbd.isFactoryMethodUnique) { boolean resolve; synchronized (mbd.constructorArgumentLock) { resolve = (mbd.resolvedConstructorOrFactoryMethod == null); } if (resolve) { new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd); } } return resolver.isAutowireCandidate( new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor); } @Override public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } return bd; } @Override public Iterator<String> getBeanNamesIterator() { CompositeIterator<String> iterator = new CompositeIterator<>(); iterator.add(this.beanDefinitionNames.iterator()); iterator.add(this.manualSingletonNames.iterator()); return iterator; } @Override public void clearMetadataCache() { super.clearMetadataCache(); clearByTypeCache(); } @Override public void freezeConfiguration() { this.configurationFrozen = true; this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames); } @Override public boolean isConfigurationFrozen() { return this.configurationFrozen; } /** * Considers all beans as eligible for metadata caching * if the factory's configuration has been marked as frozen. * @see #freezeConfiguration() */ @Override protected boolean isBeanEligibleForMetadataCaching(String beanName) { return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName)); } @Override public void preInstantiateSingletons() throws BeansException { if (this.logger.isDebugEnabled()) { this.logger.debug("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> ((SmartFactoryBean<?>) factory).isEagerInit(), getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } else { getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } } //--------------------------------------------------------------------- // Implementation of BeanDefinitionRegistry interface //--------------------------------------------------------------------- @Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); if (beanDefinition instanceof AbstractBeanDefinition) { try { ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } BeanDefinition oldBeanDefinition; oldBeanDefinition = this.beanDefinitionMap.get(beanName); if (oldBeanDefinition != null) { if (!isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName + "': There is already [" + oldBeanDefinition + "] bound."); } else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) { // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (this.logger.isWarnEnabled()) { this.logger.warn("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); } } else if (!beanDefinition.equals(oldBeanDefinition)) { if (this.logger.isInfoEnabled()) { this.logger.info("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); } } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); } } this.beanDefinitionMap.put(beanName, beanDefinition); } else { if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { this.beanDefinitionMap.put(beanName, beanDefinition); List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (oldBeanDefinition != null || containsSingleton(beanName)) { resetBeanDefinition(beanName); } } @Override public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { Assert.hasText(beanName, "'beanName' must not be empty"); BeanDefinition bd = this.beanDefinitionMap.remove(beanName); if (bd == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames); updatedDefinitions.remove(beanName); this.beanDefinitionNames = updatedDefinitions; } } else { // Still in startup registration phase this.beanDefinitionNames.remove(beanName); } this.frozenBeanDefinitionNames = null; resetBeanDefinition(beanName); } /** * Reset all bean definition caches for the given bean, * including the caches of beans that are derived from it. * @param beanName the name of the bean to reset */ protected void resetBeanDefinition(String beanName) { // Remove the merged bean definition for the given bean, if already created. clearMergedBeanDefinition(beanName); // Remove corresponding bean from singleton cache, if any. Shouldn't usually // be necessary, rather just meant for overriding a context's default beans // (e.g. the default StaticMessageSource in a StaticApplicationContext). destroySingleton(beanName); // Reset all bean definitions that have the given bean as parent (recursively). for (String bdName : this.beanDefinitionNames) { if (!beanName.equals(bdName)) { BeanDefinition bd = this.beanDefinitionMap.get(bdName); if (beanName.equals(bd.getParentName())) { resetBeanDefinition(bdName); } } } } /** * Only allows alias overriding if bean definition overriding is allowed. */ @Override protected boolean allowAliasOverriding() { return isAllowBeanDefinitionOverriding(); } @Override public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { super.registerSingleton(beanName, singletonObject); if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { if (!this.beanDefinitionMap.containsKey(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1); updatedSingletons.addAll(this.manualSingletonNames); updatedSingletons.add(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase if (!this.beanDefinitionMap.containsKey(beanName)) { this.manualSingletonNames.add(beanName); } } clearByTypeCache(); } @Override public void destroySingleton(String beanName) { super.destroySingleton(beanName); this.manualSingletonNames.remove(beanName); clearByTypeCache(); } @Override public void destroySingletons() { super.destroySingletons(); this.manualSingletonNames.clear(); clearByTypeCache(); } /** * Remove any assumptions about by-type mappings. */ private void clearByTypeCache() { this.allBeanNamesByType.clear(); this.singletonBeanNamesByType.clear(); } //--------------------------------------------------------------------- // Dependency resolution functionality //--------------------------------------------------------------------- @Override public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException { NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, (Object[]) null); if (namedBean != null) { return namedBean; } BeanFactory parent = getParentBeanFactory(); if (parent instanceof AutowireCapableBeanFactory) { return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType); } throw new NoSuchBeanDefinitionException(requiredType); } @SuppressWarnings("unchecked") @Nullable private <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType, @Nullable Object... args) throws BeansException { Assert.notNull(requiredType, "Required type must not be null"); String[] candidateNames = getBeanNamesForType(requiredType); if (candidateNames.length > 1) { List<String> autowireCandidates = new ArrayList<>(candidateNames.length); for (String beanName : candidateNames) { if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) { autowireCandidates.add(beanName); } } if (!autowireCandidates.isEmpty()) { candidateNames = autowireCandidates.toArray(new String[autowireCandidates.size()]); } } if (candidateNames.length == 1) { String beanName = candidateNames[0]; return new NamedBeanHolder<>(beanName, getBean(beanName, requiredType, args)); } else if (candidateNames.length > 1) { Map<String, Object> candidates = new LinkedHashMap<>(candidateNames.length); for (String beanName : candidateNames) { if (containsSingleton(beanName)) { candidates.put(beanName, getBean(beanName, requiredType, args)); } else { candidates.put(beanName, getType(beanName)); } } String candidateName = determinePrimaryCandidate(candidates, requiredType); if (candidateName == null) { candidateName = determineHighestPriorityCandidate(candidates, requiredType); } if (candidateName != null) { Object beanInstance = candidates.get(candidateName); if (beanInstance instanceof Class) { beanInstance = getBean(candidateName, requiredType, args); } return new NamedBeanHolder<>(candidateName, (T) beanInstance); } throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet()); } return null; } @Override public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { //ObjectFactory类注入的reshuffle处理 return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { //javaxInjectProviderClass类注入的特殊处理 return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName); } else { //通用处理逻辑 Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } } @Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class<?> type = descriptor.getDependencyType(); //用于支持Spring中新增的注解@Value Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } //如果解析器没有成功解析,则需要考虑各种情况 Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(type, matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } //已经可以确定只有一个匹配项 if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } return (instanceCandidate instanceof Class ? descriptor.resolveCandidate(autowiredBeanName, type, this) : instanceCandidate); } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } } private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) { Class<?> type = descriptor.getDependencyType(); //属性是数组类型 if (type.isArray()) { Class<?> componentType = type.getComponentType(); ResolvableType resolvableType = descriptor.getResolvableType(); Class<?> resolvedArrayType = resolvableType.resolve(); if (resolvedArrayType != null && resolvedArrayType != type) { type = resolvedArrayType; componentType = resolvableType.getComponentType().resolve(); } if (componentType == null) { return null; } //根据属性类型找到beanFactory中所有类型的匹配bean //返回值的构成为:key=匹配的beanName,value=beanName //对应的实例化后的bean(通过getBean(beanName)返回) Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { //如果autowire的require属性为true而找到的匹配项却为空则只能抛出异常 return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } //通过类型转换器将bean的值转换为对应的type类型 TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof Object[]) { Arrays.sort((Object[]) result, adaptDependencyComparator(matchingBeans)); } return result; } //属性是Collection属性 else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric(); if (elementType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof List) { Collections.sort((List<?>) result, adaptDependencyComparator(matchingBeans)); } return result; } //属性是Map属性 else if (Map.class == type) { ResolvableType mapType = descriptor.getResolvableType().asMap(); Class<?> keyType = mapType.resolveGeneric(0); if (String.class != keyType) { return null; } Class<?> valueType = mapType.resolveGeneric(1); if (valueType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } else { return null; } } private boolean isRequired(DependencyDescriptor descriptor) { return getAutowireCandidateResolver().isRequired(descriptor); } private boolean indicatesMultipleBeans(Class<?> type) { return (type.isArray() || (type.isInterface() && (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)))); } @Nullable private Comparator<Object> adaptDependencyComparator(Map<String, Object> matchingBeans) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).withSourceProvider( createFactoryAwareOrderSourceProvider(matchingBeans)); } else { return comparator; } } private FactoryAwareOrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, Object> beans) { IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>(); beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName)); return new FactoryAwareOrderSourceProvider(instancesToBeanNames); } /** * Find bean instances that match the required type. * Called during autowiring for the specified bean. * @param beanName the name of the bean that is about to be wired * @param requiredType the actual type of bean to look for * (may be an array component type or collection element type) * @param descriptor the descriptor of the dependency to resolve * @return a Map of candidate names and candidate instances that match * the required type (never {@code null}) * @throws BeansException in case of errors * @see #autowireByType * @see #autowireConstructor */ protected Map<String, Object> findAutowireCandidates( @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); for (Class<?> autowiringType : this.resolvableDependencies.keySet()) { if (autowiringType.isAssignableFrom(requiredType)) { Object autowiringValue = this.resolvableDependencies.get(autowiringType); autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); if (requiredType.isInstance(autowiringValue)) { result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); break; } } } for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty() && !indicatesMultipleBeans(requiredType)) { // Consider fallback matches if the first pass failed to find anything... DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty()) { // Consider self references as a final pass... // but in the case of a dependency collection, not the very same bean itself. for (String candidate : candidateNames) { if (isSelfReference(beanName, candidate) && (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } } } return result; } /** * Add an entry to the candidate map: a bean instance if available or just the resolved * type, preventing early bean initialization ahead of primary candidate selection. */ private void addCandidateEntry(Map<String, Object> candidates, String candidateName, DependencyDescriptor descriptor, Class<?> requiredType) { if (descriptor instanceof MultiElementDescriptor || containsSingleton(candidateName)) { candidates.put(candidateName, descriptor.resolveCandidate(candidateName, requiredType, this)); } else { candidates.put(candidateName, getType(candidateName)); } } /** * Determine the autowire candidate in the given set of beans. * <p>Looks for {@code @Primary} and {@code @Priority} (in that order). * @param candidates a Map of candidate names and candidate instances * that match the required type, as returned by {@link #findAutowireCandidates} * @param descriptor the target dependency to match against * @return the name of the autowire candidate, or {@code null} if none found */ @Nullable protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) { Class<?> requiredType = descriptor.getDependencyType(); String primaryCandidate = determinePrimaryCandidate(candidates, requiredType); if (primaryCandidate != null) { return primaryCandidate; } String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType); if (priorityCandidate != null) { return priorityCandidate; } // Fallback for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateName = entry.getKey(); Object beanInstance = entry.getValue(); if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) || matchesBeanName(candidateName, descriptor.getDependencyName())) { return candidateName; } } return null; } /** * Determine the primary candidate in the given set of beans. * @param candidates a Map of candidate names and candidate instances * (or candidate classes if not created yet) that match the required type * @param requiredType the target dependency type to match against * @return the name of the primary candidate, or {@code null} if none found * @see #isPrimary(String, Object) */ @Nullable protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) { String primaryBeanName = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (isPrimary(candidateBeanName, beanInstance)) { if (primaryBeanName != null) { boolean candidateLocal = containsBeanDefinition(candidateBeanName); boolean primaryLocal = containsBeanDefinition(primaryBeanName); if (candidateLocal && primaryLocal) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "more than one 'primary' bean found among candidates: " + candidates.keySet()); } else if (candidateLocal) { primaryBeanName = candidateBeanName; } } else { primaryBeanName = candidateBeanName; } } } return primaryBeanName; } /** * Determine the candidate with the highest priority in the given set of beans. * <p>Based on {@code @javax.annotation.Priority}. As defined by the related * {@link org.springframework.core.Ordered} interface, the lowest value has * the highest priority. * @param candidates a Map of candidate names and candidate instances * (or candidate classes if not created yet) that match the required type * @param requiredType the target dependency type to match against * @return the name of the candidate with the highest priority, * or {@code null} if none found * @see #getPriority(Object) */ @Nullable protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) { String highestPriorityBeanName = null; Integer highestPriority = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); Integer candidatePriority = getPriority(beanInstance); if (candidatePriority != null) { if (highestPriorityBeanName != null) { if (candidatePriority.equals(highestPriority)) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "Multiple beans found with the same priority ('" + highestPriority + "') among candidates: " + candidates.keySet()); } else if (candidatePriority < highestPriority) { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } else { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } } return highestPriorityBeanName; } /** * Return whether the bean definition for the given bean name has been * marked as a primary bean. * @param beanName the name of the bean * @param beanInstance the corresponding bean instance (can be null) * @return whether the given bean qualifies as primary */ protected boolean isPrimary(String beanName, Object beanInstance) { if (containsBeanDefinition(beanName)) { return getMergedLocalBeanDefinition(beanName).isPrimary(); } BeanFactory parent = getParentBeanFactory(); return (parent instanceof DefaultListableBeanFactory && ((DefaultListableBeanFactory) parent).isPrimary(beanName, beanInstance)); } /** * Return the priority assigned for the given bean instance by * the {@code javax.annotation.Priority} annotation. * <p>The default implementation delegates to the specified * {@link #setDependencyComparator dependency comparator}, checking its * {@link OrderComparator#getPriority method} if it is an extension of * Spring's common {@link OrderComparator} - typically, an * {@link org.springframework.core.annotation.AnnotationAwareOrderComparator}. * If no such comparator is present, this implementation returns {@code null}. * @param beanInstance the bean instance to check (can be {@code null}) * @return the priority assigned to that bean or {@code null} if none is set */ @Nullable protected Integer getPriority(Object beanInstance) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).getPriority(beanInstance); } return null; } /** * Determine whether the given candidate name matches the bean name or the aliases * stored in this bean definition. */ protected boolean matchesBeanName(String beanName, @Nullable String candidateName) { return (candidateName != null && (candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName))); } /** * Determine whether the given beanName/candidateName pair indicates a self reference, * i.e. whether the candidate points back to the original bean or to a factory method * on the original bean. */ private boolean isSelfReference(@Nullable String beanName, @Nullable String candidateName) { return (beanName != null && candidateName != null && (beanName.equals(candidateName) || (containsBeanDefinition(candidateName) && beanName.equals(getMergedLocalBeanDefinition(candidateName).getFactoryBeanName())))); } /** * Raise a NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException * for an unresolvable dependency. */ private void raiseNoMatchingBeanFound( Class<?> type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException { checkBeanNotOfRequiredType(type, descriptor); throw new NoSuchBeanDefinitionException(resolvableType, "expected at least 1 bean which qualifies as autowire candidate. " + "Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations())); } /** * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable, * i.e. if the target type of the bean would match but an exposed proxy doesn't. */ private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) { for (String beanName : this.beanDefinitionNames) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> targetType = mbd.getTargetType(); if (targetType != null && type.isAssignableFrom(targetType) && isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) { // Probably a proxy interfering with target type match -> throw meaningful exception. Object beanInstance = getSingleton(beanName, false); Class<?> beanType = (beanInstance != null ? beanInstance.getClass() : predictBeanType(beanName, mbd)); if (beanType != null && !type.isAssignableFrom(beanType)) { throw new BeanNotOfRequiredTypeException(beanName, type, beanType); } } } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor); } } /** * Create an {@link Optional} wrapper for the specified dependency. */ private Optional<?> createOptionalDependency( DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) { DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) { @Override public boolean isRequired() { return false; } @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, requiredType, args) : super.resolveCandidate(beanName, requiredType, beanFactory)); } }; return Optional.ofNullable(doResolveDependency(descriptorToUse, beanName, null, null)); } @Override public String toString() { StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this)); sb.append(": defining beans ["); sb.append(StringUtils.collectionToCommaDelimitedString(this.beanDefinitionNames)); sb.append("]; "); BeanFactory parent = getParentBeanFactory(); if (parent == null) { sb.append("root of factory hierarchy"); } else { sb.append("parent: ").append(ObjectUtils.identityToString(parent)); } return sb.toString(); } //--------------------------------------------------------------------- // Serialization support //--------------------------------------------------------------------- private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { throw new NotSerializableException("DefaultListableBeanFactory itself is not deserializable - " + "just a SerializedBeanFactoryReference is"); } protected Object writeReplace() throws ObjectStreamException { if (this.serializationId != null) { return new SerializedBeanFactoryReference(this.serializationId); } else { throw new NotSerializableException("DefaultListableBeanFactory has no serialization id"); } } /** * Minimal id reference to the factory. * Resolved to the actual factory instance on deserialization. */ private static class SerializedBeanFactoryReference implements Serializable { private final String id; public SerializedBeanFactoryReference(String id) { this.id = id; } private Object readResolve() { Reference<?> ref = serializableFactories.get(this.id); if (ref != null) { Object result = ref.get(); if (result != null) { return result; } } // Lenient fallback: dummy factory in case of original factory not found... return new DefaultListableBeanFactory(); } } /** * Serializable ObjectFactory/ObjectProvider for lazy resolution of a dependency. */ private class DependencyObjectProvider implements ObjectProvider<Object>, Serializable { private final DependencyDescriptor descriptor; private final boolean optional; @Nullable private final String beanName; public DependencyObjectProvider(DependencyDescriptor descriptor, @Nullable String beanName) { this.descriptor = new NestedDependencyDescriptor(descriptor); this.optional = (this.descriptor.getDependencyType() == Optional.class); this.beanName = beanName; } @Override public Object getObject() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { return doResolveDependency(this.descriptor, this.beanName, null, null); } } @Override public Object getObject(final Object... args) throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName, args); } else { DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) { @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return ((AbstractBeanFactory) beanFactory).getBean(beanName, requiredType, args); } }; return doResolveDependency(descriptorToUse, this.beanName, null, null); } } @Override public Object getIfAvailable() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) { @Override public boolean isRequired() { return false; } }; return doResolveDependency(descriptorToUse, this.beanName, null, null); } } @Override public Object getIfUnique() throws BeansException { DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) { @Override public boolean isRequired() { return false; } @Override public Object resolveNotUnique(Class<?> type, Map<String, Object> matchingBeans) { return null; } }; if (this.optional) { return createOptionalDependency(descriptorToUse, this.beanName); } else { return doResolveDependency(descriptorToUse, this.beanName, null, null); } } } /** * Serializable ObjectFactory for lazy resolution of a dependency. */ private class Jsr330DependencyProvider extends DependencyObjectProvider implements Provider<Object> { public Jsr330DependencyProvider(DependencyDescriptor descriptor, @Nullable String beanName) { super(descriptor, beanName); } @Override @Nullable public Object get() throws BeansException { return getObject(); } } /** * Separate inner class for avoiding a hard dependency on the {@code javax.inject} API. */ private class Jsr330ProviderFactory { public Object createDependencyProvider(DependencyDescriptor descriptor, @Nullable String beanName) { return new Jsr330DependencyProvider(descriptor, beanName); } } /** * An {@link org.springframework.core.OrderComparator.OrderSourceProvider} implementation * that is aware of the bean metadata of the instances to sort. * <p>Lookup for the method factory of an instance to sort, if any, and let the * comparator retrieve the {@link org.springframework.core.annotation.Order} * value defined on it. This essentially allows for the following construct: */ private class FactoryAwareOrderSourceProvider implements OrderComparator.OrderSourceProvider { private final Map<Object, String> instancesToBeanNames; public FactoryAwareOrderSourceProvider(Map<Object, String> instancesToBeanNames) { this.instancesToBeanNames = instancesToBeanNames; } @Override public Object getOrderSource(Object obj) { RootBeanDefinition beanDefinition = getRootBeanDefinition(this.instancesToBeanNames.get(obj)); if (beanDefinition == null) { return null; } List<Object> sources = new ArrayList<>(2); Method factoryMethod = beanDefinition.getResolvedFactoryMethod(); if (factoryMethod != null) { sources.add(factoryMethod); } Class<?> targetType = beanDefinition.getTargetType(); if (targetType != null && targetType != obj.getClass()) { sources.add(targetType); } return sources.toArray(new Object[sources.size()]); } @Nullable private RootBeanDefinition getRootBeanDefinition(@Nullable String beanName) { if (beanName != null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof RootBeanDefinition) { return (RootBeanDefinition) bd; } } return null; } } private static class NestedDependencyDescriptor extends DependencyDescriptor { public NestedDependencyDescriptor(DependencyDescriptor original) { super(original); increaseNestingLevel(); } } private static class MultiElementDescriptor extends NestedDependencyDescriptor { public MultiElementDescriptor(DependencyDescriptor original) { super(original); } } }
[ "penglong0705@126.com" ]
penglong0705@126.com
5b5fc139ed3263c094c81c5ddc4786d609b88e93
8dd6bf4f167e1f981854a3c849128500353d88c7
/andengine/src/org/anddev/andengine/util/modifier/BaseSingleValueChangeModifier.java
7aba59667a783b7c4c792fabebf032bd1df759f4
[ "MIT" ]
permissive
embedlabs/candybot
52e61a2e6b7eda1bd35b177844a345881f7966aa
594a5cbdb79fc143aa5211bce4025e9e9b88113b
refs/heads/master
2020-03-25T12:59:50.306869
2015-01-14T02:24:55
2015-01-14T02:24:55
18,902,672
2
0
null
null
null
null
UTF-8
Java
false
false
2,409
java
package org.anddev.andengine.util.modifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:49:51 - 03.09.2010 * @param <T> */ public abstract class BaseSingleValueChangeModifier<T> extends BaseDurationModifier<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mValueChangePerSecond; // =========================================================== // Constructors // =========================================================== public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange) { this(pDuration, pValueChange, null); } public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange, final IModifierListener<T> pModifierListener) { super(pDuration, pModifierListener); this.mValueChangePerSecond = pValueChange / pDuration; } protected BaseSingleValueChangeModifier(final BaseSingleValueChangeModifier<T> pBaseSingleValueChangeModifier) { super(pBaseSingleValueChangeModifier); this.mValueChangePerSecond = pBaseSingleValueChangeModifier.mValueChangePerSecond; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValue); @Override protected void onManagedInitialize(final T pItem) { } @Override protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) { this.onChangeValue(pSecondsElapsed, pItem, this.mValueChangePerSecond * pSecondsElapsed); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
[ "shravvmehtaa@gmail.com" ]
shravvmehtaa@gmail.com
0f7c3467b2a1a1418e196647031d679935ca5c95
a2cdf730f57276f12769bf442e4e2ff64ec363ee
/src/com/orange/songcrawler/service/CrawlPolicy.java
2f400ab29b0901a9c3480b4bba12654957357bb0
[]
no_license
gckjdev/SongCrawler
66f3ca58e6cd53157ef280a3b3ea0d937713a586
256c17a7eb08165cafe71b32085dc53f6bf6e494
refs/heads/master
2016-09-06T07:24:31.533077
2013-07-25T07:09:47
2013-07-25T07:09:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,845
java
package com.orange.songcrawler.service; /** * 用于爬虫策略,如 *   对于OneShot爬虫,由于百度的IP访问限制,每个实例进程只抓取部分字母范围  */ public class CrawlPolicy { public enum NameCapital { A("A"), B("B"), C("C"), D("D"), E("E"), F("F"), G("G"), H("H"), I("I"), J("J"), K("K"), L("L"), M("M"), N("N"), O("O"), P("P"), Q("Q"), R("R"), S("S"), T("T"), U("U"), V("V"), W("W"), X("X"), Y("Y"), Z("Z"); private final String capital; NameCapital(String capital) { this.capital = capital; } public static NameCapital valueOf(int ord) { for (NameCapital nc: NameCapital.values()) { if (nc.ordinal() == ord) return nc; } return null; } public String getCapital() { return capital; } } public static NameCapital[] dispatchNameCapitalRange(String startCapital, String endCapital) throws Exception { // 检查有无提供字母范围,无则终止程序! if (startCapital == null || endCapital == null) { throw new Exception("You must provide start capital and end capital !!!"); } // 检查是否合格的字母,否则终止程序! if (! Character.isUpperCase(startCapital.charAt(0)) || ! Character.isUpperCase(endCapital.charAt(0)) ) { throw new Exception("You must provide a valid capital range"); } // 检查start是否小于等于end, 否则终止程序! if (NameCapital.valueOf(startCapital).ordinal() > NameCapital.valueOf(endCapital).ordinal() ) { throw new Exception("You must provide a valid capital range"); } // 抓singersRange[0]至singersRange[1]的所有歌曲 NameCapital[] nameCapitalRange = new NameCapital[2]; nameCapitalRange[0] = NameCapital.valueOf(startCapital); nameCapitalRange[1] = NameCapital.valueOf(endCapital); return nameCapitalRange; } }
[ "nasa4836@gmail.com" ]
nasa4836@gmail.com
ac34e0de31df88da47a70bfff531848741d2f2b4
269578c14ef6444f5fc07483d65b80fd520bcdec
/InterviewPrep/src/C16June29/SortedRowColumnWiseSortedMatrix.java
67b166206c0e27a503278fb146eb09d9947bf5ac
[]
no_license
akashantil/Problem-Solving
e03e86361d4c7ea1d8b7ad4d24e1706c2c595e07
13a7a7ed68845951a79935daf50bda6463594659
refs/heads/master
2020-03-19T20:09:31.145864
2018-08-01T06:20:40
2018-08-01T06:20:40
136,882,935
0
0
null
null
null
null
UTF-8
Java
false
false
1,094
java
package C15June28; import java.util.PriorityQueue; import java.util.Scanner; public class SortedRowColumnWiseSortedMatrix { public static class Pair implements Comparable<Pair>{ int data; int li; int di; Pair(int data, int li, int di) { this.data = data; this.li = li; this.di = di; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.data-o.data; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int row = sc.nextInt(); int col = sc.nextInt(); int[][] arr = new int[row][col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) arr[i][j] = sc.nextInt(); PriorityQueue<Pair> pq = new PriorityQueue<>(); for (int i = 0; i < arr.length; i++) { Pair x = new Pair(arr[i][0], i, 0); pq.add(x); } while(!pq.isEmpty()){ Pair x = pq.remove(); System.out.print(x.data+" "); if(x.di +1 <arr[0].length){ int d=x.di; x.di=d+1; x.data=arr[x.li][x.di]; pq.add(x); } } } }
[ "antil.akash91@gmail.com" ]
antil.akash91@gmail.com
2069605fa3e791ef31d93ad7445c47cbe1cb8183
a8630229207852b3ad903ca09621d7d473617381
/src/main/java/com/br/guilherme/utils/DateService.java
a2dbb7528389c64740b41877be78c7c7b669c274
[]
no_license
guichico/TestesUnitarios
6309419c513e392fe3d0b7b3bdd58ddd8a1027ee
a689f9ac15ac57d50c29b6dbff06d24a66214f4c
refs/heads/master
2021-07-07T15:17:17.449280
2019-07-23T20:40:39
2019-07-23T20:40:39
196,290,229
0
0
null
2020-10-13T14:32:42
2019-07-11T00:00:58
Java
UTF-8
Java
false
false
136
java
package com.br.guilherme.utils; import java.util.Date; public interface DateService { Date getDate(); Date getDate(int days); }
[ "guilherme.chiconato@gmail.com" ]
guilherme.chiconato@gmail.com
9de4f3c803916c580122b402d3a50fe9d5e6ebfb
481862667cc07b84fc6030cda1d98df7eb7c95ce
/src/main/java/com/cloudacademy/data/Main.java
17d293f269be8e9ebd362ac9941f6b6673d53cd8
[]
no_license
cloudacademy/redis-java-app
14cfb56e8d22949f054082aa2d549231e00ea7c0
ad58fc44c4d9ea4478ec0cf2c61c70dfc25e45fc
refs/heads/master
2023-01-14T13:40:42.853446
2020-11-23T04:28:07
2020-11-23T04:28:07
296,191,005
0
0
null
null
null
null
UTF-8
Java
false
false
1,103
java
package com.cloudacademy.data; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Set; public class Main { //address of redis server private static final String redisHost = "localhost"; private static final Integer redisPort = 6379; //jedis connection pool private static JedisPool pool = null; public Main() { //configure jedis pool connection pool = new JedisPool(redisHost, redisPort); } public void demoSets() { //get a jedis connection jedis connection pool Jedis jedis = pool.getResource(); //cache set data System.out.println("writing..."); String key = "languages"; jedis.sadd(key, "Python", "Java", "C#", "Ruby", "NodeJS"); //retrieve set data System.out.println("reading..."); Set<String> members = jedis.smembers(key); for (String member : members) { System.out.println(member); } } public static void main(String[] args){ Main main = new Main(); main.demoSets(); } }
[ "jeremycook123@gmail.com" ]
jeremycook123@gmail.com
a104eae9d238a36b4dbd593987e83a72d8cf7db4
ef14f0ec90e369a95148c56b0127821ca22a9e69
/ChongQing_ipanelforhw/src-portal/com/ipanel/join/chongqing/portal/MailData.java
a25d7af7afb173cdfdb9cb33112354df80583884
[]
no_license
piaoxue85/workspace
e8ab8ee7368ebf1338dd3c2de541820d513bef14
0c37d881df09893073c2baa2a0dbed78a34571e1
refs/heads/master
2020-07-04T04:03:54.824284
2018-10-10T17:09:50
2018-10-10T17:09:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
964
java
package com.ipanel.join.chongqing.portal; import java.io.Serializable; public class MailData implements Serializable { private String emergencyMailTheme; private String emergencyMailContent; private String emergencyMailId; private String notReadNum; public String getEmergencyMailTheme() { return emergencyMailTheme; } public void setEmergencyMailTheme(String emergencyMailTheme) { this.emergencyMailTheme = emergencyMailTheme; } public String getEmergencyMailContent() { return emergencyMailContent; } public void setEmergencyMailContent(String emergencyMailContent) { this.emergencyMailContent = emergencyMailContent; } public String getEmergencyMailId() { return emergencyMailId; } public void setEmergencyMailId(String emergencyMailId) { this.emergencyMailId = emergencyMailId; } public String getNotReadNum() { return notReadNum; } public void setNotReadNum(String notReadNum) { this.notReadNum = notReadNum; } }
[ "583570220@qq.com" ]
583570220@qq.com
b7c771db5bf9fb4421af36f6337d86911017f053
6fea2f2f5741c8921b49040d94501c5b41373906
/something-learned/Algorithms and Data-Structures/leetcode/java/medium/RemoveDuplicatesFromSortedArrayII.java
96c23c86eddf583e573b6313641b196b73faf67a
[ "MIT" ]
permissive
agarrharr/code-rush-101
675f19d68206b38af022b60d16c83974dd504f16
dd27b767cdc0c667655ab8e32e020ed4248bd112
refs/heads/master
2021-04-27T01:36:58.705613
2017-12-21T23:24:32
2017-12-21T23:24:32
122,677,807
4
0
MIT
2018-02-23T22:08:28
2018-02-23T22:08:28
null
UTF-8
Java
false
false
1,203
java
package leetcode.medium; import org.junit.Test; import junit.framework.TestCase; /** * Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ * * @author shivam.maharshi */ public class RemoveDuplicatesFromSortedArrayII extends TestCase { @Test public static void test() { assertEquals(0, removeDuplicates(new int[] {})); assertEquals(2, removeDuplicates(new int[] { 1, 1 })); assertEquals(2, removeDuplicates(new int[] { 1, 2 })); assertEquals(2, removeDuplicates(new int[] { 1, 1, 1, 1, 1, 1, 1, 1 })); assertEquals(7, removeDuplicates(new int[] { 1, 2, 3, 4, 5, 6, 7 })); assertEquals(6, removeDuplicates(new int[] { 1, 1, 2, 2, 3, 3 })); assertEquals(5, removeDuplicates(new int[] { 1, 1, 1, 2, 2, 3 })); } public static int removeDuplicates(int[] nums) { if (nums == null) return 0; if (nums.length == 0 || nums.length == 1) return nums.length; int r = 2; for (int i = 2; i < nums.length; i++) { if (nums[r - 1] != nums[i] || (nums[r - 1] == nums[i] && nums[r - 2] != nums[i])) { nums[r] = nums[i]; r++; } } return r; } }
[ "noreply@github.com" ]
noreply@github.com
035007bc2e273f1b249d022c3d138685c9a82609
b06acf556b750ac1fa5b28523db7188c05ead122
/IfcModel/src/ifc2x3tc1/IfcRelAssociatesConstraint.java
a0c27252a64f22c2dfcf9db6b060b22c62ecd44d
[]
no_license
christianharrington/MDD
3500afbe5e1b1d1a6f680254095bb8d5f63678ba
64beecdaed65ac22b0047276c616c269913afd7f
refs/heads/master
2021-01-10T21:42:53.686724
2012-12-17T03:27:05
2012-12-17T03:27:05
6,157,471
1
0
null
null
null
null
UTF-8
Java
false
false
2,382
java
/** */ package ifc2x3tc1; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Rel Associates Constraint</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link ifc2x3tc1.IfcRelAssociatesConstraint#getIntent <em>Intent</em>}</li> * <li>{@link ifc2x3tc1.IfcRelAssociatesConstraint#getRelatingConstraint <em>Relating Constraint</em>}</li> * </ul> * </p> * * @see ifc2x3tc1.Ifc2x3tc1Package#getIfcRelAssociatesConstraint() * @model * @generated */ public interface IfcRelAssociatesConstraint extends IfcRelAssociates { /** * Returns the value of the '<em><b>Intent</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Intent</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Intent</em>' attribute. * @see #setIntent(String) * @see ifc2x3tc1.Ifc2x3tc1Package#getIfcRelAssociatesConstraint_Intent() * @model * @generated */ String getIntent(); /** * Sets the value of the '{@link ifc2x3tc1.IfcRelAssociatesConstraint#getIntent <em>Intent</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Intent</em>' attribute. * @see #getIntent() * @generated */ void setIntent(String value); /** * Returns the value of the '<em><b>Relating Constraint</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Relating Constraint</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Relating Constraint</em>' reference. * @see #setRelatingConstraint(IfcConstraint) * @see ifc2x3tc1.Ifc2x3tc1Package#getIfcRelAssociatesConstraint_RelatingConstraint() * @model * @generated */ IfcConstraint getRelatingConstraint(); /** * Sets the value of the '{@link ifc2x3tc1.IfcRelAssociatesConstraint#getRelatingConstraint <em>Relating Constraint</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Relating Constraint</em>' reference. * @see #getRelatingConstraint() * @generated */ void setRelatingConstraint(IfcConstraint value); } // IfcRelAssociatesConstraint
[ "t.didriksen@gmail.com" ]
t.didriksen@gmail.com
a4ad90d7c3db19d238a71e2222b97a54b943a0c9
7c542f85f7fa9cbf772704dc2a3a81924e531ffb
/JavaCommExtractor/JavaCommExtractor/src/enoir/graphvizapi/Node.java
08272ce1417e7a51550635aa945f6dbb582b737d
[]
no_license
PqES/JavaCommExtractor
121f83db9982fe5b3ddba92de9a031c565c97df0
439a6fd8cada5595bf00b5a04a83118acfd743bf
refs/heads/master
2020-05-17T10:40:53.839983
2019-04-26T16:52:08
2019-04-26T16:52:08
183,664,313
0
0
null
null
null
null
UTF-8
Java
false
false
477
java
package enoir.graphvizapi; /** * The Node class like Graphviz's node. * Created by frank on 2014/11/17. */ public class Node extends BaseGraphObject { /** * Constructor. * @param id */ public Node(String id) { super(id); } @Override public String genDotString() { StringBuilder dotString = new StringBuilder(); dotString.append("["+this.genAttributeDotString()+"]"); return dotString.toString(); } }
[ "elenaaugusta94@gmail.com" ]
elenaaugusta94@gmail.com
187aa36b91118cb9fd24d1b77662db7c4c256c11
720f05005df2b67390acb46001f7536be27f6286
/api/couchmovies/src/main/java/com/cb/demo/entities/Country.java
c5d3e91e9261f30b32b1ba40cc16bd6e4710018a
[]
no_license
thejcfactor/docker-couchmovies
598dd4d3426dcf2015b51eaa5ed24a636d1fce4b
e8811a870d4815a6991e7939d5e4b5708ed72bfa
refs/heads/master
2022-05-06T14:52:18.527003
2019-11-14T00:16:01
2019-11-14T00:16:01
221,576,046
0
0
null
2022-03-31T18:57:30
2019-11-14T00:15:04
JavaScript
UTF-8
Java
false
false
330
java
package com.cb.demo.entities; import com.couchbase.client.java.repository.annotation.Field; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Country { @Field("iso_3166_1") private String IsoCode; private String name; }
[ "jaredcasey@Admins-MacBook-Pro-4.local" ]
jaredcasey@Admins-MacBook-Pro-4.local
6df7c0425b0f987ee81c8956bcbc702463b7e375
5c0f28a7f19de155a13fb8372d060a7305d5d7e6
/src/main/java/com/github/rest/ResumeBuilderResouce.java
d5dab39162606aa59aefa60162cdf661f8d739e9
[]
no_license
mahersafadi/github_resume
90afbe78a0719d9c93ce082dbcbebc58cba78f83
07d5e1195d0a763c8e119eeef7341201b10a725c
refs/heads/master
2021-01-20T19:29:58.724038
2016-05-30T21:48:38
2016-05-30T21:48:38
60,040,719
0
0
null
null
null
null
UTF-8
Java
false
false
1,639
java
package com.github.rest; import java.io.IOException; /** * @author maher * This class is responsible for receive the rest request * from client and produces the profile or error if there is a problem raised */ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; 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; import com.github.service.GithubService; import com.github.transferobjects.Error; import com.github.transferobjects.TransferObject; @ComponentScan @RestController public class ResumeBuilderResouce extends AbstractResource{ @Autowired private GithubService githubService; /** * this method get the request(GET) contains the guthub username and produces the profile for the user * @param name the github user coming from client * @return the profile or an error if there is which the are implement TransferObject interface */ @ResponseBody @RequestMapping(value="/resume/{name}", produces = "application/json;charset=UTF-8") public TransferObject getProfile(@PathVariable("name") String name) { try { return githubService.getProfile(name); } catch (IOException ex) { ex.printStackTrace(); Error e = new Error(); e.setErrMsg("An error accured during get data from github, Please check the github username if correct, detailed message:"+ex.getMessage()); return e; } } }
[ "maher.safadi@gmail.com" ]
maher.safadi@gmail.com
86a0776604729fa746967b4ea83b3f94e1701a7c
dbfb73c985d4dfea6b1aa8a98bd018d378369ddf
/wtu-tbdata-dal/src/main/java/com/wtu/tbdata/dal/mapper/impl/BaseMapper.java
6cfe9cc45af02517c4d4ddf41fa9bf1cd1297014
[]
no_license
zuodeng091/wtu
cd76c4dbc64a5e7580e5052d30d4706e8ce40083
0ede7ae5ada4afb7b3f3bec306d9bc11a15fe158
refs/heads/master
2021-01-10T22:01:39.547366
2015-07-21T07:02:18
2015-07-21T07:02:18
34,492,255
0
0
null
null
null
null
UTF-8
Java
false
false
1,176
java
package com.wtu.tbdata.dal.mapper.impl; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * 定义sqlsession * @author zuodeng 作者 */ @Component public class BaseMapper { /** * 加入日志 */ private static Logger logger = LoggerFactory.getLogger(BaseMapper.class); /** * sqlSession */ @Resource(name = "sqlSessionFactory") private SqlSessionFactory sqlSessionFactory; private SqlSession sqlSession; /** * 加载类的时候初始化sqlSession */ public BaseMapper(){ if(sqlSessionFactory == null){ logger.info("spring加载sqlSessionFactory失败"); }else{ sqlSession = sqlSessionFactory.openSession(); if(sqlSession != null){ logger.info("spring成功加载sqlSession"); } } } /** * 获取sqlSession * @return 返回 */ public SqlSession getSqlSession(){ return sqlSession; } }
[ "1125280065@qq.com" ]
1125280065@qq.com
e05b9455f3f73e69a6195ca2d65ce25487ee3aaa
8976e0c8fad2ee8071d164feaec12a5c64a71aea
/src/jminusminus/JUnlessStatement.java
6b41c2b309c2d2bf1fb634f1985a5e0f82f51854
[]
no_license
Grantapher/TCSS421-j--
65727be686b88011fdeb3593feb792b055fc65a9
281bfcfb6b2c72008362025a0e698b63fcca0797
refs/heads/master
2020-05-23T06:26:51.014074
2016-06-02T01:03:48
2016-06-02T01:03:48
54,934,655
0
0
null
null
null
null
UTF-8
Java
false
false
3,317
java
// Copyright 2013 Bill Campbell, Swami Iyer and Bahar Akbal-Delibas package jminusminus; import static jminusminus.CLConstants.GOTO; /** * The AST node for an if-statement. */ class JUnlessStatement extends JStatement { /** * Test expression. */ private JExpression condition; /** * Then clause. */ private JStatement thenPart; /** * Else clause. */ private JStatement elsePart; /** * Construct an AST node for an unless-statement given its line number, the test * expression, the consequent, and the alternate. * * @param line line in which the unless-statement occurs in the source file. * @param condition test expression. * @param thenPart then clause. * @param elsePart else clause. */ public JUnlessStatement(int line, JExpression condition, JStatement thenPart, JStatement elsePart) { super(line); this.condition = condition; this.thenPart = thenPart; this.elsePart = elsePart; } /** * Analyzing the unless-statement means analyzing its components and checking * that the test is boolean. * * @param context context in which names are resolved. * @return the analyzed (and possibly rewritten) AST subtree. */ public JStatement analyze(Context context) { condition = (JExpression) condition.analyze(context); condition.type().mustMatchExpected(line(), Type.BOOLEAN); thenPart = (JStatement) thenPart.analyze(context); if (elsePart != null) { elsePart = (JStatement) elsePart.analyze(context); } return this; } /** * Code generation for an unless-statement. We generate code to branch over the * consequent if test; the consequent is followed by an unconditonal branch * over (any) alternate. * * @param output the code emitter (basically an abstraction for producing the * .class file). */ public void codegen(CLEmitter output) { String elseLabel = output.createLabel(); String endLabel = output.createLabel(); condition.codegen(output, elseLabel, true); thenPart.codegen(output); if (elsePart != null) { output.addBranchInstruction(GOTO, endLabel); } output.addLabel(elseLabel); if (elsePart != null) { elsePart.codegen(output); output.addLabel(endLabel); } } /** * @inheritDoc */ public void writeToStdOut(PrettyPrinter p) { p.printf("<JUnlessStatement line=\"%d\">\n", line()); p.indentRight(); p.printf("<TestExpression>\n"); p.indentRight(); condition.writeToStdOut(p); p.indentLeft(); p.printf("</TestExpression>\n"); p.printf("<ThenClause>\n"); p.indentRight(); thenPart.writeToStdOut(p); p.indentLeft(); p.printf("</ThenClause>\n"); if (elsePart != null) { p.printf("<ElseClause>\n"); p.indentRight(); elsePart.writeToStdOut(p); p.indentLeft(); p.printf("</ElseClause>\n"); } p.indentLeft(); p.printf("</JUnlessStatement>\n"); } }
[ "granttpfr@gmail.com" ]
granttpfr@gmail.com
59a6e40218d9ae7f8355ad251cc4a0760dfe2321
32da6d3e417ae150970a2c5a6f6e9cab7e013de1
/ServletWorkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/sprmvc/org/apache/jsp/WEB_002dINF/views/searchForm_jsp.java
1b55b3399589cede873083bc49977896c3015761
[]
no_license
sumedha-sen/GitPractice
3f6319bf365914422b1d0ae645cafff0e97099d5
20692dafc8f16f89d8b8b0744ad3e04d572e5a0e
refs/heads/master
2023-05-26T18:46:19.467279
2021-06-06T19:05:35
2021-06-06T19:05:35
374,428,982
0
0
null
null
null
null
UTF-8
Java
false
false
7,902
java
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/9.0.1 * Generated at: 2021-04-21 09:40:29 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.views; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import com.te.sprmvc.beans.EmployeeBean; public final class searchForm_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1); _jspx_dependants.put("/WEB-INF/views/header.jsp", Long.valueOf(1618946079083L)); } private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = new java.util.HashSet<>(); _jspx_imports_classes.add("com.te.sprmvc.beans.EmployeeBean"); } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final java.lang.String _jspx_method = request.getMethod(); if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD"); return; } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=ISO-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta charset=\"ISO-8859-1\">\r\n"); out.write("<title>Header</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\t<table border=\"1\" style= width:100%\">\r\n"); out.write("\t\t<tr>\r\n"); out.write("\t\t\t<th style=\"font-size:20px\"><a href=\"./searchForm\">Search Employee</a></th>\r\n"); out.write("\r\n"); out.write("\t\t\t<th style=\"font-size:20px\"><a href=\"./update\">Update Employee</a></th>\r\n"); out.write("\t\t\t<th style=\"font-size:20px\"><a href=\"./showdelete\">Delete Employee</a></th>\r\n"); out.write("\t\t\t<th style=\"font-size:20px\"><a href=\"./add\">Add all employees</a></th>\r\n"); out.write("\t\t\t<th style=\"font-size:20px\"><a href=\"./alldata\">Get all employees</a></th>\r\n"); out.write("\t\t\t<th style=\"font-size:20px\"><a href=\"./logout\">LogOut</a></th>\r\n"); out.write("\t\t</tr>\r\n"); out.write("\t</table>\r\n"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>"); out.write('\r'); out.write('\n'); String msg = (String) request.getAttribute("msg"); EmployeeBean bean=(EmployeeBean)request.getAttribute("data"); out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta charset=\"ISO-8859-1\">\r\n"); out.write("<title>Search Form</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\t"); if (bean!=null) { out.write("\r\n"); out.write("\t<h2 User id:>"); out.print(bean.getId()); out.write("</h2>\r\n"); out.write("\t<h2 Name:>"); out.print(bean.getName()); out.write("</h2>\r\n"); out.write("\t<h2 Dob:>"); out.print(bean.getDob()); out.write("</h2>\r\n"); out.write("\t"); } out.write("\r\n"); out.write("\r\n"); out.write("\t<h1>\r\n"); out.write("\t\t<fieldset>\r\n"); out.write("\t\t\t<legend>Login</legend>\r\n"); out.write("\t\t\t<form action=\"./search\" method=\"\">\r\n"); out.write("\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t<td>Search</td>\r\n"); out.write("\t\t\t\t\t<td>:</td>\r\n"); out.write("\t\t\t\t\t<td><input type=\"text\" name=\"id\"></td>\r\n"); out.write("\t\t\t\t</tr>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\t\t\t\t<tr>\r\n"); out.write("\r\n"); out.write("\t\t\t\t\t<td><input type=\"submit\" value=\"search\"></td>\r\n"); out.write("\t\t\t\t</tr>\r\n"); out.write("\t\t\t</form>\r\n"); out.write("\r\n"); out.write("\t\t</fieldset>\r\n"); out.write("\t</h1>\r\n"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
[ "sumedha.s@testyantra.in" ]
sumedha.s@testyantra.in
fb940daa4880f1f20ccc29fa303fd208ea563eb1
d6ac1789994729933323fadb3510e142fef6ab20
/src/main/java/com/daumsoft/taSolutionManager/restFullApi/controller/BatchRestController.java
f7b838f881441aa863f080328f3fe5f3b2f98a18
[]
no_license
muna0208/TA_Solution_Manager
31b821abe6e0553b61169e2e4e0e26d010cfaf30
1f9eea3a4a4c1f745843a170ae937f37eecbbae3
refs/heads/main
2023-09-04T08:55:16.038527
2021-10-27T07:19:10
2021-10-27T07:19:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,742
java
package com.daumsoft.taSolutionManager.restFullApi.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.daumsoft.taSolutionManager.common.service.RestFullExceptionService; import com.daumsoft.taSolutionManager.common.utils.MakeUtil; import com.daumsoft.taSolutionManager.restFullApi.domain.BatchService; import com.daumsoft.taSolutionManager.restFullApi.service.BatchRestService; @RestController public class BatchRestController { @Autowired private BatchRestService batchRestService; @Autowired private RestFullExceptionService restFullExceptionService; /** * 배치 조회 * @return */ @GetMapping(value="/getBatchList") public ResponseEntity<Object> getBatchList(HttpSession session) { try { return new ResponseEntity<Object>(batchRestService.getBatchList(session),HttpStatus.OK); } catch (Exception e) { return restFullExceptionService.exceptionFailed(MakeUtil.printErrorLogger(e, "getBatchList")); } } /** * 배치 상세조회 * @param id * @return */ @GetMapping(value="/getBatch/{batchServiceSeq}") public ResponseEntity<Object> getBatch(@PathVariable Integer batchServiceSeq){ try { return new ResponseEntity<Object>(batchRestService.getBatch(batchServiceSeq),HttpStatus.OK); } catch (Exception e) { return restFullExceptionService.exceptionFailed(MakeUtil.printErrorLogger(e, "getBatch")); } } /** * 배치 등록 * @param userInfo * @param session * @return */ @PostMapping(value="/insertBatch") public ResponseEntity<Object> insertBatch(@RequestBody BatchService batch){ try { return new ResponseEntity<Object>(batchRestService.insertBatch(batch),HttpStatus.CREATED); } catch (Exception e) { return restFullExceptionService.exceptionFailed(MakeUtil.printErrorLogger(e, "insertBatch")); } } /** * 배치 수정 * @param userInfo * @param session * @return */ @PatchMapping(value="/updateBatch") public ResponseEntity<Object> updateBatch(@RequestBody BatchService batch){ try { return new ResponseEntity<Object>(batchRestService.updateBatch(batch),HttpStatus.OK); } catch (Exception e) { return restFullExceptionService.exceptionFailed(MakeUtil.printErrorLogger(e, "updateBatch")); } } /** * 배치 삭제 * @param batchServiceSeq * @return */ @DeleteMapping(value="/deleteBatch/{batchServiceSeq}") public ResponseEntity<Object> deleteBatch(@PathVariable Integer batchServiceSeq){ try { return new ResponseEntity<Object>(batchRestService.deleteBatch(batchServiceSeq),HttpStatus.OK); } catch (Exception e) { return restFullExceptionService.exceptionFailed(MakeUtil.printErrorLogger(e, "deleteBatch")); } } /** * 배치 시작/중지 * @param batch * @return */ @PatchMapping(value="/commandBatch") public ResponseEntity<Object> commandBatch(@RequestBody BatchService batch){ try { return new ResponseEntity<Object>(batchRestService.commandBatch(batch),HttpStatus.OK); } catch (Exception e) { return restFullExceptionService.exceptionFailed(MakeUtil.printErrorLogger(e, "commandBatch")); } } }
[ "muna2020@daumsoft.com" ]
muna2020@daumsoft.com
c5b3ee46eced1cea4daeaea51416c16273882c68
cad6d656107c5b08c2a089585dd1dd689855e663
/eafall/src/main/java/com/yaroslavlancelot/eafall/game/campaign/missions/FourthMissionActivity.java
33e15564813f7d4445db17ae4831bf63f36de44e
[ "Apache-2.0" ]
permissive
YaroslavHavrylovych/eafall
57b046d1a0427a2692ef6fb9041a5a5b2d393b05
188d71dd9f5e7da5923627397c77e2a29b7c642e
refs/heads/develop
2021-01-22T08:19:41.303734
2019-11-22T08:30:23
2019-11-22T08:30:23
92,613,651
3
0
NOASSERTION
2019-10-15T16:56:22
2017-05-27T17:27:32
Java
UTF-8
Java
false
false
4,162
java
package com.yaroslavlancelot.eafall.game.campaign.missions; import android.widget.Toast; import com.yaroslavlancelot.eafall.R; import com.yaroslavlancelot.eafall.game.BaseTutorialActivity; import com.yaroslavlancelot.eafall.game.constant.SizeConstants; import com.yaroslavlancelot.eafall.game.constant.StringConstants; import com.yaroslavlancelot.eafall.game.entity.gameobject.unit.offence.OffenceUnit; import com.yaroslavlancelot.eafall.game.entity.gameobject.unit.offence.path.IUnitPath; import com.yaroslavlancelot.eafall.game.entity.gameobject.unit.offence.path.implementation.SingleWayThoughCenterUnitPath; import com.yaroslavlancelot.eafall.game.events.SharedEvents; import com.yaroslavlancelot.eafall.game.events.periodic.time.GameTime; import com.yaroslavlancelot.eafall.game.player.IPlayer; import com.yaroslavlancelot.eafall.game.player.PlayersHolder; import com.yaroslavlancelot.eafall.game.scene.scenes.EaFallScene; import java.util.ArrayList; import java.util.List; import java.util.Random; /** Fifth mission include waves user need to leave */ public class FourthMissionActivity extends BaseTutorialActivity { @Override protected void onPopulateWorkingScene(final EaFallScene scene) { super.onPopulateWorkingScene(scene); String callbackKey = GameTime.GAME_TIMER_TICK_KEY; SharedEvents.addCallback(new SharedEvents.DataChangedCallback(callbackKey) { @Override public void callback(final String key, final Object value) { Integer intVal = (Integer) value; switch (intVal) { case 180: { showInfoToast(R.string.ninth_mission_pre_support); break; } case 170: { wave(3); break; } case 30: { wave(5); break; } } } }); } private void wave(int amountOfUnitPerPath) { IPlayer player = getBotPlayer(); List<Integer> unitsIds = new ArrayList<>(player.getAlliance().getMovableUnitsIds()); unitsIds.remove(unitsIds.size() - 1);// removing defence unit Random random = new Random(); //top support for (int i = 0; i < amountOfUnitPerPath; i++) { int id = unitsIds.get(random.nextInt(unitsIds.size())); int y = SizeConstants.GAME_FIELD_HEIGHT * 9 / 10 + i / 10 * SizeConstants.UNIT_SIZE; int x = SizeConstants.GAME_FIELD_WIDTH / 2 + (((i % 10) - 2) * SizeConstants.UNIT_SIZE + 5); OffenceUnit unit = createMovableUnit(player, id, x, y, new SingleWayThoughCenterUnitPath(false)); IUnitPath path = unit.getUnitPath(); path.setCurrentPathPoint(path.getTotalPathPoints() / 2); } //bottom support for (int i = 0; i < amountOfUnitPerPath; i++) { int id = unitsIds.get(random.nextInt(unitsIds.size())); int x = SizeConstants.GAME_FIELD_WIDTH / 2 + (((i % 10) - 2) * SizeConstants.UNIT_SIZE + 5); int y = SizeConstants.GAME_FIELD_HEIGHT / 10 + i / 10 * SizeConstants.UNIT_SIZE; OffenceUnit unit = createMovableUnit(player, id, x, y, new SingleWayThoughCenterUnitPath(false)); IUnitPath path = unit.getUnitPath(); path.setCurrentPathPoint(path.getTotalPathPoints() / 2); } showInfoToast(R.string.ninth_mission_support); } private IPlayer getBotPlayer() { IPlayer player = PlayersHolder.getPlayer(StringConstants.FIRST_PLAYER_CONTROL_BEHAVIOUR_TYPE); if (player.getControlType().user()) { player = player.getEnemyPlayer(); } return player; } private void showInfoToast(final int strId) { runOnUiThread(() -> Toast.makeText(FourthMissionActivity.this, strId, Toast.LENGTH_SHORT).show()); } @Override protected String getScreenName() { return "Mission 5 Screen"; } }
[ "yaroslavlancelot@gmail.com" ]
yaroslavlancelot@gmail.com
d003b162e6b93f513809dfb97294c91a12dd1d35
c08d0e70339df3748f8b7e53dacdcb0631d423ff
/src/main/java/homework/homework_4/pageObjects/HomePage.java
7e955c03516a9ea82dee9f9d28a5aaaa3e1b91de
[]
no_license
NataliaLebedeva/TestAutoWinter2018
70a599b839c73f54558b610a53d6dfd77086a23f
d00f644e3bc30c4747636998980a9b6925680dda
refs/heads/master
2021-05-12T19:42:26.762352
2018-02-03T20:53:41
2018-02-03T20:53:41
117,100,482
0
0
null
null
null
null
UTF-8
Java
false
false
2,750
java
package homework.homework_4.pageObjects; import com.codeborne.selenide.Condition; import com.codeborne.selenide.ElementsCollection; import com.codeborne.selenide.SelenideElement; import homework.homework_4.enums.BenefitsTextEnum; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.testng.Assert; import ru.yandex.qatools.allure.annotations.Step; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import static com.codeborne.selenide.CollectionCondition.size; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Condition.visible; import static com.codeborne.selenide.Selenide.title; import static homework.homework_4.enums.MainTextEnum.*; public class HomePage { @FindBy(css = ".benefit-icon") private ElementsCollection benefitIcon; @FindBy(css = ".benefit-txt") private ElementsCollection benefitTxt; @FindBy(css = ".main-txt") private SelenideElement mainText; @FindBy(css = ".main-title") private SelenideElement mainTitle; @Step public void checkPageTitle() { Assert.assertTrue(title().equals(PAGE_TITLE.getText())); } @Step public void checkBenefitsIcon() { benefitIcon.shouldHave(size(4)); for (SelenideElement icon : benefitIcon) { icon.shouldBe(visible); } } public void checkBenefitsTextsSelenide() { BenefitsTextEnum[] values = BenefitsTextEnum.values(); benefitTxt.shouldHave(size(values.length)); for (int i = 0; i < values.length; i++) { String s = values[i].getText(); // should be replaced by simple assert, just 4 example benefitTxt.get(i).should(new Condition("testIgnore\\n") { @Override public boolean apply(WebElement element) { return element.getText().replaceAll("\n", " ").equals(s); } }); } } @Step public void checkBenefitsTextsByStream() { Function<String, String> replace = (s) -> s.replaceAll("\n", " ").toLowerCase().trim(); List<String> expected = Arrays.stream(BenefitsTextEnum.values()) .map(BenefitsTextEnum::getText) .map(replace).collect(Collectors.toList()); List<String> actual = benefitTxt.stream() .map(SelenideElement::getText) .map(replace).collect(Collectors.toList()); Assert.assertEquals(actual, expected); } @Step public void checkMainText() { mainTitle.shouldHave(text(MAIN_TITLE.getText())); mainText.shouldHave(text(MAIN_TEXT.getText())); } }
[ "natalia.bunyak@gmail.com" ]
natalia.bunyak@gmail.com
dcdc86e7a905efb8593ed2b2a5e4c6b0f15407eb
c3d17aa91f6b7290f9a1de53f5069be5b9e5821e
/arquitetura-jsf/src/main/java/br/com/codetisolutions/arquitetura/jsf/apresentacao/ControllerBaseJSF.java
d72a10d0cb5b9a75dc9f158c090e9b562f70dbf6
[]
no_license
marcosbuganeme/arquitetura-modular-javaee
d12d3331a1261aab99acecfc84185a42a735f760
57603cbca8533d3ff14a214495b208faf649c4cd
refs/heads/master
2021-03-27T11:47:18.737691
2019-03-24T22:55:34
2019-03-24T22:55:34
22,484,381
1
0
null
null
null
null
UTF-8
Java
false
false
4,252
java
package br.com.codetisolutions.arquitetura.jsf.apresentacao; import java.io.Serializable; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <p> * <b>Organização:</b> 4code TI Solutions * </p> * * <p> * <b>Título:</b> ControllerBaseJSF.java * </p> * * <p> * <b>Descrição:</b> Classe delegada de <code>ControllerJSF</code>. * </p> * * Data de criação: 04/08/2014 * * @author marcosbuganeme * * @version 1.0.0 */ public class ControllerBaseJSF implements Serializable { /** Constante serialVersionUID. */ private static final long serialVersionUID = -735243567000463544L; /** Atributo controllerJSF. */ private ControllerJSF controllerJSF; /** * Método responsável por iniciar os dados de um controlador. * * @author marcosbuganeme * */ public void iniciarDados() { return; } /** * Método responsável por abrir a página inicial de um caso de uso. * * @author marcosbuganeme * * @return <i>página inicial</i>. */ public String abreIniciar() { return this.getControllerJSF().abreIniciar(); } /** * Método responsável por apontar a rota de navegação da página inicial de um caso de uso. * * @author marcosbuganeme * * @return <i>nome da classe + /inicial == rota do arquivo JSF</i>. */ public String getNavigationAbreIniciar() { return this.getControllerJSF().getNavigationAbreIniciar(); } /** * Método responsável por voltar para a página inicial de um caso de uso. * * @author marcosbuganeme * * @return <i>volta para a página inicial</i>. */ public String voltarInicio() { return this.getControllerJSF().voltarInicio(); } /** * Método responsável por exibir uma mensagem na tela. * * @author marcosbuganeme * * @param mensagens * - mensagens que serão exibidas na tela. */ public void exibirMensagemNaTela(final String... mensagens) { this.getControllerJSF().exibirMensagemNaTela(mensagens); } /** * Método responsável por adicionar uma mensagem de sucesso na tela. * * @author marcosbuganeme * * @param mensagemSucesso * - mensagem de sucesso. */ public void adicionarMensagemSucesso(final String mensagemSucesso) { this.getControllerJSF().adicionarMensagemSucesso(mensagemSucesso); } /** * Método responsável por adicionar uma mensagem de alerta na tela. * * @author marcosbuganeme * * @param mensagemALerta * - mensagem de alerta. */ public void adicionarMensagemAlerta(final String mensagemAlerta) { this.getControllerJSF().adicionarMensagemAlerta(mensagemAlerta); } /** * Método responsável por adicionar uma mensagem de erro na tela. * * @author marcosbuganeme * * @param mensagemErro * - mensagem de erro. */ public void adicionarMensagemErro(final String mensagemErro) { this.getControllerJSF().adicionarMensagemErro(mensagemErro); } /** * Método responsável por verificar se existe mensagens configuradas. * * @author marcosbuganeme * * @return <i>{ TRUE, se existir mensagem configurada }<br> * { FALSE, se <b>não</b> existir mensagem configurada }</i>. */ public boolean hasMessage() { return this.getControllerJSF().hasMessage(); } /** * Retorna o valor do atributo <code>httpServletRequest</code>. * * @return <code>HttpServletRequest</code>. */ public HttpServletRequest getRequest() { return this.getControllerJSF().getRequest(); } /** * Retorna o valor do atributo <code>httpServletResponse</code>. * * @return <code>HttpServletResponse</code>. */ public HttpServletResponse getResponse() { return this.getControllerJSF().getResponse(); } /** * Retorna o valor do atributo <code>facesContext</code>. * * @return <code>FacesContext</code>. */ public FacesContext getFacesContext() { return this.getControllerJSF().getFacesContext(); } /** * Retorna o valor do atributo <code>controllerJSF</code> * * @return <code>ControllerJSF</code> */ public ControllerJSF getControllerJSF() { if (this.controllerJSF == null) { this.controllerJSF = new ControllerJSF(); } return this.controllerJSF; } }
[ "marcos.after@gmail.com" ]
marcos.after@gmail.com
9f9efc04f795db5283eda3f9d0d4d103f52ad272
fb38aef83a5da55183789b2a362d29609a2c6254
/str_api/src/main/java/net/streets/api/StrAPIApp.java
1e8751c3a8a09e3ac161111c5878ef304e27531b
[]
no_license
tkaviya/jstreets
121b591cf0a7878248c616f36ceb372f0b662330
26fb7fb8fd5f974c2bd003e6d7c564f39e665e98
refs/heads/master
2020-07-30T00:43:08.593883
2019-09-25T18:44:06
2019-09-25T18:44:06
210,022,607
0
0
null
null
null
null
UTF-8
Java
false
false
1,607
java
package net.streets.api; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.context.annotation.Configuration; import javax.ws.rs.ext.ContextResolver; /*************************************************************************** * * * Created: 16 / 01 / 2017 * * Author: Tsungai Kaviya * * Contact: tsungai.kaviya@gmail.com * * * ***************************************************************************/ @Configuration public class StrAPIApp extends ResourceConfig { public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { private final ObjectMapper mapper; ObjectMapperContextResolver() { mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Override public ObjectMapper getContext(Class<?> type) { return mapper; } } public StrAPIApp() { register(new ObjectMapperContextResolver()); register(MultiPartFeature.class); // register(StrRestExceptionHandler.class); // register(MobileXMLRestController.class); // register(MobileJSONRestController.class); // register(StrXMLRestController.class); // register(StrJSONRestController.class); } }
[ "tsungai.kaviya@gmail.com" ]
tsungai.kaviya@gmail.com
92aece76d0380220fcf1d30e0393082e5d7b88dd
a28162c4b04cdb9450882607804de52b5a63fa50
/src/main/java/Overall/JSONDecoder.java
4014841e139faa877aa881e7acc4919ef40ad22b
[]
no_license
NguyenMinhChien20020369/BTL1TuDienOop
da6bccd0c9aa2621d8f0ad6bd0f73392473bf72c
36dc2158d9e8547c889348f1bd773cde2a1ced15
refs/heads/main
2023-08-22T23:38:55.182688
2021-10-29T04:50:54
2021-10-29T04:50:54
410,587,443
0
0
null
null
null
null
UTF-8
Java
false
false
2,208
java
package Overall; import Overall.Description; import Overall.Word; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.sql.SQLOutput; import java.util.ArrayList; public class JSONDecoder { void addMeaningByType(Word word, JSONObject jo1){ JSONArray noun = (JSONArray) jo1.get("definitions"); //System.out.println(checkType); String type = (String) jo1.get("partOfSpeech"); ArrayList<Description> meaning = new ArrayList<>(); for (int i = 0; i < noun.size(); i++) { Description des = new Description(); JSONObject def = (JSONObject) noun.get(i); des.setDefinition(def.get("definition").toString()); //TODO : MAKE EXAMPLE AS ARRAY if (def.get("examples") != null) { JSONArray examples = (JSONArray) def.get("examples"); for (Object ex :examples) { des.setExample(ex.toString()); } } meaning.add(des); } word.addMeaning(type, meaning); } public ArrayList<Word> Decoder(String data){ ArrayList<Word> words = new ArrayList<>(); try { //Get word from Json string Object obj = JSONValue.parse(data); JSONArray ja = (JSONArray) obj; for (int i = 0; i < ja.size(); i++) { Word word = new Word(); JSONObject jo = (JSONObject) ja.get(i); word.setWord_target((String) jo.get("word")); word.setPhonetic((String)jo.get("phonetic")); //Get the meaning source JSONArray JsonMeaning = (JSONArray) jo.get("meanings"); for (int k = 0; k < JsonMeaning.size(); k++) { JSONObject jo1 = (JSONObject) JsonMeaning.get(k); // System.out.println(jo1); // System.out.println(type); addMeaningByType(word, jo1); } words.add(word); } }catch(Exception e){ System.out.println(e.getMessage()); } return words; } }
[ "lehuyhaianh0808@gmail.com" ]
lehuyhaianh0808@gmail.com
46f1c0bbe776c337679044312583464a6dbf58ba
47a67da71b6f3eb0c8bdadbeeea8493c7e87dd33
/graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraph.java
e8f02a93b97c6bc88ceff56b0544b26aacdb213a
[ "Apache-2.0", "BSD-3-Clause", "WTFPL", "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jnhagelberg/incubator-atlas
9c44a49d2001d2800dd8a281a246684c2248af31
90a44167466921d726add4318ae9b83ea4e3f9ab
refs/heads/master
2020-12-31T03:17:26.200002
2016-06-28T21:24:04
2016-07-01T19:06:25
54,225,426
0
1
null
2016-03-18T19:08:38
2016-03-18T19:08:38
null
UTF-8
Java
false
false
8,654
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 org.apache.atlas.repository.graphdb; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Set; import javax.script.ScriptException; import org.apache.atlas.typesystem.types.IDataType; /** * Represents a graph * * @param <V> vertex implementation class * @param <E> edge implementation class */ public interface AtlasGraph<V,E> { /** * Adds an edge to the graph * * @param outVertex * @param inVertex * @param label * @return */ AtlasEdge<V,E> addEdge(AtlasVertex<V,E> outVertex, AtlasVertex<V,E> inVertex, String label); /** * Adds a vertex to the graph * * @return */ AtlasVertex<V,E> addVertex(); /** * Removes the specified edge from the graph * * @param edge */ void removeEdge(AtlasEdge<V,E> edge); /** * Removes the specified vertex from the graph. * * @param vertex */ void removeVertex(AtlasVertex<V,E> vertex); /** * Retrieves the edge with the specified id. As an optimization, a non-null Edge may be * returned by some implementations if the Edge does not exist. In that case, * you can call {@link AtlasElement#exists()} to determine whether the vertex * exists. This allows the retrieval of the Edge information to be deferred * or in come cases avoided altogether in implementations where that might * be an expensive operation. * * @param edgeId * @return */ AtlasEdge<V,E> getEdge(String edgeId); /** * Gets all the edges in the graph. * @return */ Iterable<AtlasEdge<V,E>> getEdges(); /** * Gets all the vertices in the graph. * @return */ Iterable<AtlasVertex<V,E>> getVertices(); /** * Gets the vertex with the specified id. As an optimization, a non-null vertex may be * returned by some implementations if the Vertex does not exist. In that case, * you can call {@link AtlasElement#exists()} to determine whether the vertex * exists. This allows the retrieval of the Vertex information to be deferred * or in come cases avoided altogether in implementations where that might * be an expensive operation. * * @param vertexId * @return */ AtlasVertex<V, E> getVertex(String vertexId); /** * Gets the names of the indexes on edges * type. * * @param type * @return */ Set<String> getEdgeIndexKeys(); /** * Gets the names of the indexes on vertices. * type. * * @param type * @return */ Set<String> getVertexIndexKeys(); /** * Finds the vertices where the given property key * has the specified value. For multi-valued properties, * finds the vertices where the value list contains * the specified value. * * @param key * @param value * @return */ Iterable<AtlasVertex<V,E>> getVertices(String key, Object value); /** * Creates a graph query * @return */ AtlasGraphQuery<V,E> query(); /** * Creates an index query * * @param indexName index name * @param queryString the query * * @see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html">Elastic Search Reference</a> for query syntax */ AtlasIndexQuery<V,E> indexQuery(String indexName, String queryString); /** * Gets the management object associated with this graph and opens a transaction * for changes that are made. * @return */ AtlasGraphManagement getManagementSystem(); /** * Commits changes made to the graph in the current transaction. */ void commit(); /** * Rolls back changes made to the graph in the current transaction. */ void rollback(); /** * Unloads and releases any resources associated with the graph. */ void shutdown(); /** * deletes everything in the graph. For testing only */ void clear(); /** * Converts the graph to gson and writes it to the specified stream * * @param os * @throws IOException */ void exportToGson(OutputStream os) throws IOException; //the following methods insulate Atlas from the details //of the interaction with Gremlin /** * * When we construct Gremlin select queries, the information we request * is grouped by the vertex the information is coming from. Each vertex * is assigned a column name which uniquely identifies it. The queries * are specially formatted so that the value associated with each of * these column names is an array with the various things we need * about that particular vertex. The query evaluator creates a mapping * that knows what index each bit of information is stored at within * this array. * <p/> * When we execute a Gremlin query, the exact java objects we get * back vary depending on whether Gremlin 2 or Gremlin 3 is being used. * This method takes as input a raw row result that was obtained by * executing a Gremlin query and extracts the value that was found * at the given index in the array for the given column name. * <p/> * If the value found is a vertex or edge, it is automatically converted * to an AtlasVertex/AtlasEdge. * * @param rowValue the raw row value that was returned by Gremin * @param colName the column name to use * @param idx the index of the value within the column to retrieve. * */ Object getGremlinColumnValue(Object rowValue, String colName, int idx); /** * When Gremlin queries are executed, they return * Vertex and Edge objects that are specific to the underlying * graph database. This method provides a way to convert these * objects back into the AtlasVertex/AtlasEdge objects that * Atlas requires. * * @param rawValue the value that was obtained from Gremlin * @return either an AtlasEdge, an AtlasVertex, or the original * value depending on whether the rawValue represents an edge, * vertex, or something else. * */ Object convertGremlinValue(Object rawValue); /** * Gremlin 2 and Gremlin 3 represent the results of "path" * queries differently. This method takes as input the * path from Gremlin and returns the list of objects in the path. * * @param rawValue * @return */ List<Object> convertPathQueryResultToList(Object rawValue); /** * This method is used in the generation of queries. It is used to * convert property values from the value that is stored in the graph * to the value/type that the user expects to get back. * * @param expr - gremlin expr that represents the persistent property value * @param type * @return */ String generatePersisentToLogicalConversionExpression(String valueExpr, IDataType<?> type); boolean isPropertyValueConversionNeeded(IDataType<?> type); /** * Gets the version of Gremlin that this graph uses. * * @return */ GremlinVersion getSupportedGremlinVersion(); /** * Whether or not an initial predicate needs to be added to gremlin queries * in order for them to run successfully. This is needed for some graph database where * graph scans are disabled. * @return */ boolean requiresInitialIndexedPredicate(); String getInitialIndexedPredicate(); /** * Executes a gremlin query, returns an object with the raw * result. * * @param gremlinQuery * @return */ Object executeGremlinScript(String gremlinQuery) throws ScriptException; }
[ "jnhagelberg@us.ibm.com" ]
jnhagelberg@us.ibm.com
0973487c9d1267a241575899ffd3fd9927bd5a55
1419e9b72ece837b9719066af93499be521205be
/1-2/src/sample1/HelloApp.java
894dc73ce0291450aaf13b99fd43c4f9e867969d
[]
no_license
mobssiie/Srping
bcf2669d1ba2626143a34dfe5c23e4ab8929962d
9e1d5dfc3a6bde9ef1c01df354ba91762a25539d
refs/heads/master
2020-05-20T01:19:22.069743
2014-03-07T04:48:53
2014-03-07T04:48:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
428
java
package sample1; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; public class HelloApp { public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml")); MessageBean bean = (MessageBean)factory.getBean("messageBean"); bean.sayHello(); } }
[ "mobssiie@tistory.com" ]
mobssiie@tistory.com
bdfbdae9ac14b81a156bcc750437ebbb79a10c96
fb83241bce8d6e500ae6b58363d0cae77529d973
/src/com/reason/psi/ReasonMLFunBody.java
31882c16c418c193f30bbce713fa133119dd608c
[ "MIT" ]
permissive
okonet/reasonml-idea-plugin
37b93f2c8d57116851ca401608fdec9ad8252e20
dc95e0051e31df68b7837b85726cbd61aede713e
refs/heads/master
2023-08-25T18:53:48.989038
2017-09-14T07:14:30
2017-09-14T07:14:30
103,940,022
0
0
null
2017-09-18T13:04:31
2017-09-18T13:04:31
null
UTF-8
Java
false
false
248
java
package com.reason.psi; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; public class ReasonMLFunBody extends ASTWrapperPsiElement { public ReasonMLFunBody(ASTNode node) { super(node); } }
[ "giraud.contact@yahoo.fr" ]
giraud.contact@yahoo.fr
4a0aee8d1186dac3c9dc90ba98ca3a1081951a77
4941c24dd7b82aa773e3b4cc2ab9f22fd026844f
/ssm-demo/src/main/java/com/ljz/test/FilesBlocTest.java
5fa676035e9350f5991c2ad884b40001baf2a69b
[]
no_license
WuYunWangYue/ssm-ljz
fea9efd629ed0b0e0b09c927a9157c4843b91dfa
d669bf8145695bf0926be14907064d10a04b48e5
refs/heads/master
2021-09-14T13:25:50.750604
2018-05-14T10:13:29
2018-05-14T10:13:29
125,993,813
1
0
null
null
null
null
UTF-8
Java
false
false
365
java
package com.ljz.test; public class FilesBlocTest { private static A a = new A(); static { System.out.println("A类的静态代码块"); } public static void main(String[] args) { System.out.println("main方法"); } // 非静态字段 // 初始代码块 // A类构造器 // A类的静态代码块 // main方法 }
[ "1120573031@qq.com" ]
1120573031@qq.com
49b36e71adf41744b89520f1ad90e11fd8f6c41e
35113b2441bd923c7768d6ef823ca2e0cc509c13
/travel.java
ee32fdccac69535805a825820d357f03ed7c36a0
[]
no_license
AbdoGamal/Problem_Solved
85b157fd60cb144513296bfaa5723d929d1bc6a8
6b224633201b74d7e2349352233ee24fe6d499d0
refs/heads/master
2016-09-15T23:11:33.188849
2015-03-13T21:46:40
2015-03-13T21:46:40
31,720,117
0
0
null
null
null
null
UTF-8
Java
false
false
468
java
import java.util.*; public class travel { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); if(a * m <= b) { System.out.println(n * a); } else { int result = Math.min((n / m) * b + a * (n % m), ((n/m) + 1) * b); System.out.println(result); } } }
[ "abdo.gamal.coder@gmail.com" ]
abdo.gamal.coder@gmail.com
d976d9106212fb29d207cef0816cad1db136c6fc
a371a863bdb5ba079561a4e7c602b1efe12898df
/src/fr/definity/api/API.java
5fa32aadcf0c263b3f55cc9dcafab30534432a4f
[]
no_license
Dinnerwolph/dc_api
b301f074810bed50d78a562ef2d5d02f6fd96ca7
4d34533eb8807b58ec32dc48f0ea5516ffed6881
refs/heads/master
2021-01-20T03:14:40.403668
2017-04-26T18:54:50
2017-04-26T18:54:50
89,515,237
0
0
null
null
null
null
UTF-8
Java
false
false
2,157
java
package fr.definity.api; import fr.definity.api.commands.CommandLag; import fr.definity.api.commands.Nick; import fr.definity.api.database.ConnectionDriver; import fr.definity.api.database.tables.Group; import fr.definity.api.groups.Groups; import fr.definity.api.listeners.ListenerManager; import fr.definity.api.player.DefinityPlayer; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class API extends JavaPlugin { private static API instance; private static Map<UUID, DefinityPlayer> definityPlayer = new HashMap(); private Map<Integer, Groups> groups = new HashMap(); public void onEnable() { instance = this; new ListenerManager(); getCommand("lag").setExecutor(new CommandLag()); getCommand("nick").setExecutor(new Nick()); ConnectionDriver.openConnection(); new Group().getAllGroups(); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); } public void onDisable() { ConnectionDriver.closeConnection(); } public static API getInstance() { return instance; } public static DefinityPlayer getDefinityPlayer(Player player) { return definityPlayer.get(player.getUniqueId()); } public static DefinityPlayer getDefinityPlayer(UUID uuid) { return definityPlayer.get(uuid); } public void addDefinityPlayer(DefinityPlayer definityPlayer) { API.definityPlayer.put(definityPlayer.uuid, definityPlayer); } public void removeDefinityPlayer(DefinityPlayer definityPlayer) { API.definityPlayer.remove(definityPlayer.uuid); } public void removeDefinityPlayer(Player player) { API.definityPlayer.remove(player.getUniqueId()); } public void removeDefinityPlayer(UUID uuid) { API.definityPlayer.remove(uuid); } public void addGroups(Groups groups) { this.groups.put(groups.getLadder(), groups); } public Groups getGroups(int groupId) { return groups.get(groupId); } }
[ "samu.loubiat@gmail.com" ]
samu.loubiat@gmail.com
8fba4283ffbe84f615ecd8ef163ce78b10c6c290
51d0e0e0a10fcb078eb928e2c3d22b8ee9cacd3e
/src/br/com/etechoracio/sihas/biblioteca/model/Autor.java
81be77037d7ed1a0fe5aa60811e682e47b1d497e
[]
no_license
Andrecrivellari/exercicio3
807a3cfc5f1bd388380e075a93c79ecd5a2c9bb0
d1d869a6ed518e763202c3513898fc6a7a08682f
refs/heads/master
2020-04-24T17:43:47.231753
2019-02-23T01:38:21
2019-02-23T01:38:21
172,157,132
0
0
null
null
null
null
UTF-8
Java
false
false
1,206
java
package br.com.etechoracio.sihas.biblioteca.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity @Table(name="TBL_AUTOR") public class Autor { @Id @GeneratedValue @Column(name="ID_AUTOR") private Long id; @Column(name="TX_NOME") private String nome; @Column(name="DT_INICIO_VIGENCIA") private Date dataInicio; @Column(name="DT_fim_VIGENCIA") private Date dataFim; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Date getDataInicio() { return dataInicio; } public void setDataInicio(Date dataInicio) { this.dataInicio = dataInicio; } public Date getDataFim() { return dataFim; } public void setDataFim(Date dataFim) { this.dataFim = dataFim; } @PrePersist private void preencherDataInicio() { if(dataInicio == null) { dataInicio= new Date(); } } }
[ "Andre" ]
Andre
1e13e54a17fa65b336c8fcb3525cc7a179f9d1a3
a71f01bbc7d5aa308a1eda2d65b5839fbc954a29
/src/main/java/com/dave/invertedindex/parse/Parser.java
e3bfefa1626d09bf5e59232bcb10bf3ddfec35db
[]
no_license
jiuzixue09/InvertedIndex
8429528a7538a5906d091a701fe4bb8051d1af24
dc0adf74fdaccad9dbcc70eef1fb4507c9769876
refs/heads/master
2020-05-29T20:36:23.842200
2019-08-14T10:11:46
2019-08-14T10:11:46
188,366,391
0
0
null
null
null
null
UTF-8
Java
false
false
2,321
java
package com.dave.invertedindex.parse; import com.dave.invertedindex.conf.FileConfigured; import java.util.HashMap; /** * A Parser defines DataStreams, which are used to parse and clean the field data (text,..) before it's indexed * Actually, this class define a set of rules to extract the terms from the source text. Each of these is applied by * a component, subclass of DataStream. This rules are defined in createStreamChain. Classes implementing a * Parser must override createStreamChain with their custom rules ie components. * * To improve efficiency, components are created only once, and streamChainPerFields holds then the reference to * the StreamChain defined for every field */ public abstract class Parser extends FileConfigured { public static HashMap<String, StreamChain> streamChainPerField = new HashMap<>(); public abstract StreamChain createStreamChain(final String fieldName); public final DataStream dataStream(String fieldName, String text) { StreamChain stream = streamChainPerField.computeIfAbsent(fieldName, k -> createStreamChain(fieldName)); stream.setData(text); return stream.getDataStream(); } /** * This class encapsulates the outer components of a DataStream. It provides * access to the source ({@link Tokenizer}) and the outer end, an * instance of {@link DataStream} which is the object returned by DataParser.dataStream */ public static class StreamChain { /** * source of the tokens, has to be {@link Tokenizer} or subclass of it */ protected final Tokenizer sourceStream; /** * this is the outer component decorating the chain. * if there are no filters defined, it will be the same as the source */ protected final DataStream endStream; public StreamChain(final Tokenizer source, final DataStream end) { this.sourceStream = source; this.endStream = end; } public void setData(final String input) { sourceStream.setData(input); } /** * the last component in the chain * @return the last component {@link DataStream} */ public DataStream getDataStream() { return endStream; } } }
[ "DAVEhall4857" ]
DAVEhall4857
5a6a69220c9075dd6ed8f231bbb9f3f6ccbf73e4
1c53d5257ea7be9450919e6b9e0491944a93ba80
/merge-scenarios/elasticsearch/5707bc7f5de-server-src-test-java-org-elasticsearch-snapshots-SnapshotResiliencyTests/expected.java
b7e6874eb96d2998c398974d992cffc131a27625
[]
no_license
anonyFVer/mastery-material
89062928807a1f859e9e8b9a113b2d2d123dc3f1
db76ee571b84be5db2d245f3b593b29ebfaaf458
refs/heads/master
2023-03-16T13:13:49.798374
2021-02-26T04:19:19
2021-02-26T04:19:19
342,556,129
0
0
null
null
null
null
UTF-8
Java
false
false
54,050
java
package org.elasticsearch.snapshots; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionType; import org.elasticsearch.action.RequestValidators; import org.elasticsearch.action.StepListener; import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryAction; import org.elasticsearch.action.admin.cluster.repositories.put.TransportPutRepositoryAction; import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteAction; import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteRequest; import org.elasticsearch.action.admin.cluster.reroute.TransportClusterRerouteAction; import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotAction; import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse; import org.elasticsearch.action.admin.cluster.snapshots.create.TransportCreateSnapshotAction; import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotAction; import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest; import org.elasticsearch.action.admin.cluster.snapshots.delete.TransportDeleteSnapshotAction; import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotAction; import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest; import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse; import org.elasticsearch.action.admin.cluster.snapshots.restore.TransportRestoreSnapshotAction; import org.elasticsearch.action.admin.cluster.state.ClusterStateAction; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.cluster.state.TransportClusterStateAction; import org.elasticsearch.action.admin.indices.create.CreateIndexAction; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.create.TransportCreateIndexAction; import org.elasticsearch.action.admin.indices.delete.DeleteIndexAction; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.TransportDeleteIndexAction; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingAction; import org.elasticsearch.action.admin.indices.mapping.put.TransportPutMappingAction; import org.elasticsearch.action.admin.indices.shards.IndicesShardStoresAction; import org.elasticsearch.action.admin.indices.shards.TransportIndicesShardStoresAction; import org.elasticsearch.action.bulk.BulkAction; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.bulk.TransportBulkAction; import org.elasticsearch.action.bulk.TransportShardBulkAction; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.resync.TransportResyncReplicationAction; import org.elasticsearch.action.search.SearchAction; import org.elasticsearch.action.search.SearchExecutionStatsCollector; import org.elasticsearch.action.search.SearchPhaseController; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchTransportService; import org.elasticsearch.action.search.TransportSearchAction; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.AutoCreateIndex; import org.elasticsearch.action.support.DestructiveOperations; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateHelper; import org.elasticsearch.client.AdminClient; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ESAllocationTestCase; import org.elasticsearch.cluster.NodeConnectionsService; import org.elasticsearch.cluster.SnapshotsInProgress; import org.elasticsearch.cluster.action.index.MappingUpdatedAction; import org.elasticsearch.cluster.action.index.NodeMappingRefreshAction; import org.elasticsearch.cluster.action.shard.ShardStateAction; import org.elasticsearch.cluster.coordination.ClusterBootstrapService; import org.elasticsearch.cluster.coordination.CoordinationMetaData.VotingConfiguration; import org.elasticsearch.cluster.coordination.CoordinationState; import org.elasticsearch.cluster.coordination.Coordinator; import org.elasticsearch.cluster.coordination.CoordinatorTests; import org.elasticsearch.cluster.coordination.DeterministicTaskQueue; import org.elasticsearch.cluster.coordination.ElectionStrategy; import org.elasticsearch.cluster.coordination.InMemoryPersistedState; import org.elasticsearch.cluster.coordination.MockSinglePrioritizingExecutor; import org.elasticsearch.cluster.metadata.AliasValidator; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.MetaDataCreateIndexService; import org.elasticsearch.cluster.metadata.MetaDataDeleteIndexService; import org.elasticsearch.cluster.metadata.MetaDataIndexUpgradeService; import org.elasticsearch.cluster.metadata.MetaDataMappingService; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.BatchedRerouteService; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.cluster.routing.allocation.AllocationService; import org.elasticsearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand; import org.elasticsearch.cluster.service.ClusterApplierService; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.cluster.service.FakeThreadPoolMasterService; import org.elasticsearch.cluster.service.MasterService; import org.elasticsearch.common.CheckedConsumer; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.IndexScopedSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.PageCacheRecycler; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.env.Environment; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.gateway.MetaStateService; import org.elasticsearch.gateway.TransportNodesListGatewayStartedShards; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.index.seqno.GlobalCheckpointSyncAction; import org.elasticsearch.index.seqno.RetentionLeaseBackgroundSyncAction; import org.elasticsearch.index.seqno.RetentionLeaseSyncAction; import org.elasticsearch.index.shard.PrimaryReplicaSyncer; import org.elasticsearch.indices.IndicesModule; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.analysis.AnalysisModule; import org.elasticsearch.indices.breaker.NoneCircuitBreakerService; import org.elasticsearch.indices.cluster.IndicesClusterStateService; import org.elasticsearch.indices.flush.SyncedFlushService; import org.elasticsearch.indices.mapper.MapperRegistry; import org.elasticsearch.indices.recovery.PeerRecoverySourceService; import org.elasticsearch.indices.recovery.PeerRecoveryTargetService; import org.elasticsearch.indices.recovery.RecoverySettings; import org.elasticsearch.ingest.IngestService; import org.elasticsearch.node.ResponseCollectorService; import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.repositories.Repository; import org.elasticsearch.repositories.blobstore.BlobStoreRepository; import org.elasticsearch.repositories.blobstore.BlobStoreTestUtil; import org.elasticsearch.repositories.fs.FsRepository; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchService; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.FetchPhase; import org.elasticsearch.snapshots.mockstore.MockEventuallyConsistentRepository; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.disruption.DisruptableMockTransport; import org.elasticsearch.test.disruption.NetworkDisruption; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportInterceptor; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportRequestHandler; import org.elasticsearch.transport.TransportService; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static org.elasticsearch.env.Environment.PATH_HOME_SETTING; import static org.elasticsearch.node.Node.NODE_NAME_SETTING; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.mockito.Mockito.mock; public class SnapshotResiliencyTests extends ESTestCase { private DeterministicTaskQueue deterministicTaskQueue; private TestClusterNodes testClusterNodes; private Path tempDir; @Nullable private MockEventuallyConsistentRepository.Context blobStoreContext; @Before public void createServices() { tempDir = createTempDir(); if (randomBoolean()) { blobStoreContext = new MockEventuallyConsistentRepository.Context(); } deterministicTaskQueue = new DeterministicTaskQueue(Settings.builder().put(NODE_NAME_SETTING.getKey(), "shared").build(), random()); } @After public void verifyReposThenStopServices() { try { if (blobStoreContext != null) { blobStoreContext.forceConsistent(); } BlobStoreTestUtil.assertConsistency((BlobStoreRepository) testClusterNodes.randomMasterNodeSafe().repositoriesService.repository("repo"), Runnable::run); } finally { testClusterNodes.nodes.values().forEach(TestClusterNode::stop); } } public void testSuccessfulSnapshotAndRestore() { setupTestCluster(randomFrom(1, 3, 5), randomIntBetween(2, 10)); String repoName = "repo"; String snapshotName = "snapshot"; final String index = "test"; final int shards = randomIntBetween(1, 10); final int documents = randomIntBetween(0, 100); final TestClusterNode masterNode = testClusterNodes.currentMaster(testClusterNodes.nodes.values().iterator().next().clusterService.state()); final StepListener<CreateSnapshotResponse> createSnapshotResponseListener = new StepListener<>(); continueOrDie(createRepoAndIndex(masterNode, repoName, index, shards), createIndexResponse -> { final Runnable afterIndexing = () -> masterNode.client.admin().cluster().prepareCreateSnapshot(repoName, snapshotName).setWaitForCompletion(true).execute(createSnapshotResponseListener); if (documents == 0) { afterIndexing.run(); } else { final BulkRequest bulkRequest = new BulkRequest().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < documents; ++i) { bulkRequest.add(new IndexRequest(index).source(Collections.singletonMap("foo", "bar" + i))); } final StepListener<BulkResponse> bulkResponseStepListener = new StepListener<>(); masterNode.client.bulk(bulkRequest, bulkResponseStepListener); continueOrDie(bulkResponseStepListener, bulkResponse -> { assertFalse("Failures in bulk response: " + bulkResponse.buildFailureMessage(), bulkResponse.hasFailures()); assertEquals(documents, bulkResponse.getItems().length); afterIndexing.run(); }); } }); final StepListener<AcknowledgedResponse> deleteIndexListener = new StepListener<>(); continueOrDie(createSnapshotResponseListener, createSnapshotResponse -> masterNode.client.admin().indices().delete(new DeleteIndexRequest(index), deleteIndexListener)); final StepListener<RestoreSnapshotResponse> restoreSnapshotResponseListener = new StepListener<>(); continueOrDie(deleteIndexListener, ignored -> masterNode.client.admin().cluster().restoreSnapshot(new RestoreSnapshotRequest(repoName, snapshotName).waitForCompletion(true), restoreSnapshotResponseListener)); final StepListener<SearchResponse> searchResponseListener = new StepListener<>(); continueOrDie(restoreSnapshotResponseListener, restoreSnapshotResponse -> { assertEquals(shards, restoreSnapshotResponse.getRestoreInfo().totalShards()); masterNode.client.search(new SearchRequest(index).source(new SearchSourceBuilder().size(0).trackTotalHits(true)), searchResponseListener); }); final AtomicBoolean documentCountVerified = new AtomicBoolean(); continueOrDie(searchResponseListener, r -> { assertEquals(documents, Objects.requireNonNull(r.getHits().getTotalHits()).value); documentCountVerified.set(true); }); runUntil(documentCountVerified::get, TimeUnit.MINUTES.toMillis(5L)); assertNotNull(createSnapshotResponseListener.result()); assertNotNull(restoreSnapshotResponseListener.result()); assertTrue(documentCountVerified.get()); SnapshotsInProgress finalSnapshotsInProgress = masterNode.clusterService.state().custom(SnapshotsInProgress.TYPE); assertFalse(finalSnapshotsInProgress.entries().stream().anyMatch(entry -> entry.state().completed() == false)); final Repository repository = masterNode.repositoriesService.repository(repoName); Collection<SnapshotId> snapshotIds = repository.getRepositoryData().getSnapshotIds(); assertThat(snapshotIds, hasSize(1)); final SnapshotInfo snapshotInfo = repository.getSnapshotInfo(snapshotIds.iterator().next()); assertEquals(SnapshotState.SUCCESS, snapshotInfo.state()); assertThat(snapshotInfo.indices(), containsInAnyOrder(index)); assertEquals(shards, snapshotInfo.successfulShards()); assertEquals(0, snapshotInfo.failedShards()); } public void testSnapshotWithNodeDisconnects() { final int dataNodes = randomIntBetween(2, 10); setupTestCluster(randomFrom(1, 3, 5), dataNodes); String repoName = "repo"; String snapshotName = "snapshot"; final String index = "test"; final int shards = randomIntBetween(1, 10); TestClusterNode masterNode = testClusterNodes.currentMaster(testClusterNodes.nodes.values().iterator().next().clusterService.state()); final StepListener<CreateSnapshotResponse> createSnapshotResponseStepListener = new StepListener<>(); continueOrDie(createRepoAndIndex(masterNode, repoName, index, shards), createIndexResponse -> { for (int i = 0; i < randomIntBetween(0, dataNodes); ++i) { scheduleNow(this::disconnectRandomDataNode); } if (randomBoolean()) { scheduleNow(() -> testClusterNodes.clearNetworkDisruptions()); } masterNode.client.admin().cluster().prepareCreateSnapshot(repoName, snapshotName).execute(createSnapshotResponseStepListener); }); continueOrDie(createSnapshotResponseStepListener, createSnapshotResponse -> { for (int i = 0; i < randomIntBetween(0, dataNodes); ++i) { scheduleNow(this::disconnectOrRestartDataNode); } final boolean disconnectedMaster = randomBoolean(); if (disconnectedMaster) { scheduleNow(this::disconnectOrRestartMasterNode); } if (disconnectedMaster || randomBoolean()) { scheduleSoon(() -> testClusterNodes.clearNetworkDisruptions()); } else if (randomBoolean()) { scheduleNow(() -> testClusterNodes.clearNetworkDisruptions()); } }); runUntil(() -> testClusterNodes.randomMasterNode().map(master -> { final SnapshotsInProgress snapshotsInProgress = master.clusterService.state().custom(SnapshotsInProgress.TYPE); return snapshotsInProgress != null && snapshotsInProgress.entries().isEmpty(); }).orElse(false), TimeUnit.MINUTES.toMillis(1L)); clearDisruptionsAndAwaitSync(); final TestClusterNode randomMaster = testClusterNodes.randomMasterNode().orElseThrow(() -> new AssertionError("expected to find at least one active master node")); SnapshotsInProgress finalSnapshotsInProgress = randomMaster.clusterService.state().custom(SnapshotsInProgress.TYPE); assertThat(finalSnapshotsInProgress.entries(), empty()); final Repository repository = randomMaster.repositoriesService.repository(repoName); Collection<SnapshotId> snapshotIds = repository.getRepositoryData().getSnapshotIds(); assertThat(snapshotIds, hasSize(1)); } public void testConcurrentSnapshotCreateAndDelete() { setupTestCluster(randomFrom(1, 3, 5), randomIntBetween(2, 10)); String repoName = "repo"; String snapshotName = "snapshot"; final String index = "test"; final int shards = randomIntBetween(1, 10); TestClusterNode masterNode = testClusterNodes.currentMaster(testClusterNodes.nodes.values().iterator().next().clusterService.state()); final StepListener<CreateSnapshotResponse> createSnapshotResponseStepListener = new StepListener<>(); continueOrDie(createRepoAndIndex(masterNode, repoName, index, shards), createIndexResponse -> masterNode.client.admin().cluster().prepareCreateSnapshot(repoName, snapshotName).execute(createSnapshotResponseStepListener)); final StepListener<AcknowledgedResponse> deleteSnapshotStepListener = new StepListener<>(); continueOrDie(createSnapshotResponseStepListener, createSnapshotResponse -> masterNode.client.admin().cluster().deleteSnapshot(new DeleteSnapshotRequest(repoName, snapshotName), deleteSnapshotStepListener)); final StepListener<CreateSnapshotResponse> createAnotherSnapshotResponseStepListener = new StepListener<>(); continueOrDie(deleteSnapshotStepListener, acknowledgedResponse -> masterNode.client.admin().cluster().prepareCreateSnapshot(repoName, snapshotName).execute(createAnotherSnapshotResponseStepListener)); continueOrDie(createAnotherSnapshotResponseStepListener, createSnapshotResponse -> assertEquals(createSnapshotResponse.getSnapshotInfo().state(), SnapshotState.SUCCESS)); deterministicTaskQueue.runAllRunnableTasks(); assertNotNull(createAnotherSnapshotResponseStepListener.result()); SnapshotsInProgress finalSnapshotsInProgress = masterNode.clusterService.state().custom(SnapshotsInProgress.TYPE); assertFalse(finalSnapshotsInProgress.entries().stream().anyMatch(entry -> entry.state().completed() == false)); final Repository repository = masterNode.repositoriesService.repository(repoName); Collection<SnapshotId> snapshotIds = repository.getRepositoryData().getSnapshotIds(); assertThat(snapshotIds, hasSize(1)); final SnapshotInfo snapshotInfo = repository.getSnapshotInfo(snapshotIds.iterator().next()); assertEquals(SnapshotState.SUCCESS, snapshotInfo.state()); assertThat(snapshotInfo.indices(), containsInAnyOrder(index)); assertEquals(shards, snapshotInfo.successfulShards()); assertEquals(0, snapshotInfo.failedShards()); } public void testSnapshotPrimaryRelocations() { final int masterNodeCount = randomFrom(1, 3, 5); setupTestCluster(masterNodeCount, randomIntBetween(2, 10)); String repoName = "repo"; String snapshotName = "snapshot"; final String index = "test"; final int shards = randomIntBetween(1, 10); final TestClusterNode masterNode = testClusterNodes.currentMaster(testClusterNodes.nodes.values().iterator().next().clusterService.state()); final AtomicBoolean createdSnapshot = new AtomicBoolean(); final AdminClient masterAdminClient = masterNode.client.admin(); final StepListener<ClusterStateResponse> clusterStateResponseStepListener = new StepListener<>(); continueOrDie(createRepoAndIndex(masterNode, repoName, index, shards), createIndexResponse -> masterAdminClient.cluster().state(new ClusterStateRequest(), clusterStateResponseStepListener)); continueOrDie(clusterStateResponseStepListener, clusterStateResponse -> { final ShardRouting shardToRelocate = clusterStateResponse.getState().routingTable().allShards(index).get(0); final TestClusterNode currentPrimaryNode = testClusterNodes.nodeById(shardToRelocate.currentNodeId()); final TestClusterNode otherNode = testClusterNodes.randomDataNodeSafe(currentPrimaryNode.node.getName()); scheduleNow(() -> testClusterNodes.stopNode(currentPrimaryNode)); scheduleNow(new Runnable() { @Override public void run() { final StepListener<ClusterStateResponse> updatedClusterStateResponseStepListener = new StepListener<>(); masterAdminClient.cluster().state(new ClusterStateRequest(), updatedClusterStateResponseStepListener); continueOrDie(updatedClusterStateResponseStepListener, updatedClusterState -> { final ShardRouting shardRouting = updatedClusterState.getState().routingTable().shardRoutingTable(shardToRelocate.shardId()).primaryShard(); if (shardRouting.unassigned() && shardRouting.unassignedInfo().getReason() == UnassignedInfo.Reason.NODE_LEFT) { if (masterNodeCount > 1) { scheduleNow(() -> testClusterNodes.stopNode(masterNode)); } testClusterNodes.randomDataNodeSafe().client.admin().cluster().prepareCreateSnapshot(repoName, snapshotName).execute(ActionListener.wrap(() -> { createdSnapshot.set(true); testClusterNodes.randomDataNodeSafe().client.admin().cluster().deleteSnapshot(new DeleteSnapshotRequest(repoName, snapshotName), noopListener()); })); scheduleNow(() -> testClusterNodes.randomMasterNodeSafe().client.admin().cluster().reroute(new ClusterRerouteRequest().add(new AllocateEmptyPrimaryAllocationCommand(index, shardRouting.shardId().id(), otherNode.node.getName(), true)), noopListener())); } else { scheduleSoon(this); } }); } }); }); runUntil(() -> testClusterNodes.randomMasterNode().map(master -> { if (createdSnapshot.get() == false) { return false; } final SnapshotsInProgress snapshotsInProgress = master.clusterService.state().custom(SnapshotsInProgress.TYPE); return snapshotsInProgress == null || snapshotsInProgress.entries().isEmpty(); }).orElse(false), TimeUnit.MINUTES.toMillis(1L)); clearDisruptionsAndAwaitSync(); assertTrue(createdSnapshot.get()); final SnapshotsInProgress finalSnapshotsInProgress = testClusterNodes.randomDataNodeSafe().clusterService.state().custom(SnapshotsInProgress.TYPE); assertThat(finalSnapshotsInProgress.entries(), empty()); final Repository repository = masterNode.repositoriesService.repository(repoName); Collection<SnapshotId> snapshotIds = repository.getRepositoryData().getSnapshotIds(); assertThat(snapshotIds, either(hasSize(1)).or(hasSize(0))); } private StepListener<CreateIndexResponse> createRepoAndIndex(TestClusterNode masterNode, String repoName, String index, int shards) { final AdminClient adminClient = masterNode.client.admin(); final StepListener<AcknowledgedResponse> createRepositoryListener = new StepListener<>(); adminClient.cluster().preparePutRepository(repoName).setType(FsRepository.TYPE).setSettings(Settings.builder().put("location", randomAlphaOfLength(10))).execute(createRepositoryListener); final StepListener<CreateIndexResponse> createIndexResponseStepListener = new StepListener<>(); continueOrDie(createRepositoryListener, acknowledgedResponse -> adminClient.indices().create(new CreateIndexRequest(index).waitForActiveShards(ActiveShardCount.ALL).settings(defaultIndexSettings(shards)), createIndexResponseStepListener)); return createIndexResponseStepListener; } private void clearDisruptionsAndAwaitSync() { testClusterNodes.clearNetworkDisruptions(); runUntil(() -> { final List<Long> versions = testClusterNodes.nodes.values().stream().map(n -> n.clusterService.state().version()).distinct().collect(Collectors.toList()); return versions.size() == 1L; }, TimeUnit.MINUTES.toMillis(1L)); } private void disconnectOrRestartDataNode() { if (randomBoolean()) { disconnectRandomDataNode(); } else { testClusterNodes.randomDataNode().ifPresent(TestClusterNode::restart); } } private void disconnectOrRestartMasterNode() { testClusterNodes.randomMasterNode().ifPresent(masterNode -> { if (randomBoolean()) { testClusterNodes.disconnectNode(masterNode); } else { masterNode.restart(); } }); } private void disconnectRandomDataNode() { testClusterNodes.randomDataNode().ifPresent(n -> testClusterNodes.disconnectNode(n)); } private void startCluster() { final ClusterState initialClusterState = new ClusterState.Builder(ClusterName.DEFAULT).nodes(testClusterNodes.discoveryNodes()).build(); testClusterNodes.nodes.values().forEach(testClusterNode -> testClusterNode.start(initialClusterState)); deterministicTaskQueue.advanceTime(); deterministicTaskQueue.runAllRunnableTasks(); final VotingConfiguration votingConfiguration = new VotingConfiguration(testClusterNodes.nodes.values().stream().map(n -> n.node).filter(DiscoveryNode::isMasterNode).map(DiscoveryNode::getId).collect(Collectors.toSet())); testClusterNodes.nodes.values().stream().filter(n -> n.node.isMasterNode()).forEach(testClusterNode -> testClusterNode.coordinator.setInitialConfiguration(votingConfiguration)); runUntil(() -> { List<String> masterNodeIds = testClusterNodes.nodes.values().stream().map(node -> node.clusterService.state().nodes().getMasterNodeId()).distinct().collect(Collectors.toList()); return masterNodeIds.size() == 1 && masterNodeIds.contains(null) == false; }, TimeUnit.SECONDS.toMillis(30L)); } private void runUntil(Supplier<Boolean> fulfilled, long timeout) { final long start = deterministicTaskQueue.getCurrentTimeMillis(); while (timeout > deterministicTaskQueue.getCurrentTimeMillis() - start) { if (fulfilled.get()) { return; } deterministicTaskQueue.runAllRunnableTasks(); deterministicTaskQueue.advanceTime(); } fail("Condition wasn't fulfilled."); } private void setupTestCluster(int masterNodes, int dataNodes) { testClusterNodes = new TestClusterNodes(masterNodes, dataNodes); startCluster(); } private void scheduleSoon(Runnable runnable) { deterministicTaskQueue.scheduleAt(deterministicTaskQueue.getCurrentTimeMillis() + randomLongBetween(0, 100L), runnable); } private void scheduleNow(Runnable runnable) { deterministicTaskQueue.scheduleNow(runnable); } private static Settings defaultIndexSettings(int shards) { return Settings.builder().put(IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), shards).put(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0).build(); } private static <T> void continueOrDie(StepListener<T> listener, CheckedConsumer<T, Exception> onResponse) { listener.whenComplete(onResponse, e -> { throw new AssertionError(e); }); } private static <T> ActionListener<T> noopListener() { return ActionListener.wrap(() -> { }); } private Environment createEnvironment(String nodeName) { return TestEnvironment.newEnvironment(Settings.builder().put(NODE_NAME_SETTING.getKey(), nodeName).put(PATH_HOME_SETTING.getKey(), tempDir.resolve(nodeName).toAbsolutePath()).put(Environment.PATH_REPO_SETTING.getKey(), tempDir.resolve("repo").toAbsolutePath()).putList(ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING.getKey(), ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING.get(Settings.EMPTY)).build()); } private static ClusterState stateForNode(ClusterState state, DiscoveryNode node) { return ClusterState.builder(state).nodes(DiscoveryNodes.builder(state.nodes()).remove(node.getId()).add(node).localNodeId(node.getId())).build(); } private final class TestClusterNodes { private final Map<String, TestClusterNode> nodes = new LinkedHashMap<>(); private final DisconnectedNodes disruptedLinks = new DisconnectedNodes(); TestClusterNodes(int masterNodes, int dataNodes) { for (int i = 0; i < masterNodes; ++i) { nodes.computeIfAbsent("node" + i, nodeName -> { try { return newMasterNode(nodeName); } catch (IOException e) { throw new AssertionError(e); } }); } for (int i = 0; i < dataNodes; ++i) { nodes.computeIfAbsent("data-node" + i, nodeName -> { try { return newDataNode(nodeName); } catch (IOException e) { throw new AssertionError(e); } }); } } public TestClusterNode nodeById(final String nodeId) { return nodes.values().stream().filter(n -> n.node.getId().equals(nodeId)).findFirst().orElseThrow(() -> new AssertionError("Could not find node by id [" + nodeId + ']')); } private TestClusterNode newMasterNode(String nodeName) throws IOException { return newNode(nodeName, DiscoveryNodeRole.MASTER_ROLE); } private TestClusterNode newDataNode(String nodeName) throws IOException { return newNode(nodeName, DiscoveryNodeRole.DATA_ROLE); } private TestClusterNode newNode(String nodeName, DiscoveryNodeRole role) throws IOException { return new TestClusterNode(new DiscoveryNode(nodeName, randomAlphaOfLength(10), buildNewFakeTransportAddress(), emptyMap(), Collections.singleton(role), Version.CURRENT), this::getDisruption); } public TestClusterNode randomMasterNodeSafe() { return randomMasterNode().orElseThrow(() -> new AssertionError("Expected to find at least one connected master node")); } public Optional<TestClusterNode> randomMasterNode() { final List<TestClusterNode> masterNodes = testClusterNodes.nodes.values().stream().filter(n -> n.node.isMasterNode()).sorted(Comparator.comparing(n -> n.node.getName())).collect(Collectors.toList()); return masterNodes.isEmpty() ? Optional.empty() : Optional.of(randomFrom(masterNodes)); } public void stopNode(TestClusterNode node) { node.stop(); nodes.remove(node.node.getName()); } public TestClusterNode randomDataNodeSafe(String... excludedNames) { return randomDataNode(excludedNames).orElseThrow(() -> new AssertionError("Could not find another data node.")); } public Optional<TestClusterNode> randomDataNode(String... excludedNames) { final List<TestClusterNode> dataNodes = testClusterNodes.nodes.values().stream().filter(n -> n.node.isDataNode()).filter(n -> { for (final String nodeName : excludedNames) { if (n.node.getName().equals(nodeName)) { return false; } } return true; }).sorted(Comparator.comparing(n -> n.node.getName())).collect(Collectors.toList()); return dataNodes.isEmpty() ? Optional.empty() : Optional.ofNullable(randomFrom(dataNodes)); } public void disconnectNode(TestClusterNode node) { if (disruptedLinks.disconnected.contains(node.node.getName())) { return; } testClusterNodes.nodes.values().forEach(n -> n.transportService.getConnectionManager().disconnectFromNode(node.node)); disruptedLinks.disconnect(node.node.getName()); } public void clearNetworkDisruptions() { final Set<String> disconnectedNodes = new HashSet<>(disruptedLinks.disconnected); disruptedLinks.clear(); disconnectedNodes.forEach(nodeName -> { if (testClusterNodes.nodes.containsKey(nodeName)) { final DiscoveryNode node = testClusterNodes.nodes.get(nodeName).node; testClusterNodes.nodes.values().forEach(n -> n.transportService.openConnection(node, null)); } }); } private NetworkDisruption.DisruptedLinks getDisruption() { return disruptedLinks; } public DiscoveryNodes discoveryNodes() { DiscoveryNodes.Builder builder = DiscoveryNodes.builder(); nodes.values().forEach(node -> builder.add(node.node)); return builder.build(); } public TestClusterNode currentMaster(ClusterState state) { TestClusterNode master = nodes.get(state.nodes().getMasterNode().getName()); assertNotNull(master); assertTrue(master.node.isMasterNode()); return master; } } private final class TestClusterNode { private final Logger logger = LogManager.getLogger(TestClusterNode.class); private final NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(Stream.concat(ClusterModule.getNamedWriteables().stream(), NetworkModule.getNamedWriteables().stream()).collect(Collectors.toList())); private final TransportService transportService; private final ClusterService clusterService; private final RepositoriesService repositoriesService; private final SnapshotsService snapshotsService; private final SnapshotShardsService snapshotShardsService; private final IndicesService indicesService; private final IndicesClusterStateService indicesClusterStateService; private final DiscoveryNode node; private final MasterService masterService; private final AllocationService allocationService; private final NodeClient client; private final NodeEnvironment nodeEnv; private final DisruptableMockTransport mockTransport; private final ThreadPool threadPool; private final Supplier<NetworkDisruption.DisruptedLinks> disruption; private Coordinator coordinator; TestClusterNode(DiscoveryNode node, Supplier<NetworkDisruption.DisruptedLinks> disruption) throws IOException { this.disruption = disruption; this.node = node; final Environment environment = createEnvironment(node.getName()); masterService = new FakeThreadPoolMasterService(node.getName(), "test", deterministicTaskQueue::scheduleNow); final Settings settings = environment.settings(); final ClusterSettings clusterSettings = new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); threadPool = deterministicTaskQueue.getThreadPool(); clusterService = new ClusterService(settings, clusterSettings, masterService, new ClusterApplierService(node.getName(), settings, clusterSettings, threadPool) { @Override protected PrioritizedEsThreadPoolExecutor createThreadPoolExecutor() { return new MockSinglePrioritizingExecutor(node.getName(), deterministicTaskQueue); } @Override protected void connectToNodesAndWait(ClusterState newClusterState) { } }); mockTransport = new DisruptableMockTransport(node, logger) { @Override protected ConnectionStatus getConnectionStatus(DiscoveryNode destination) { return disruption.get().disrupt(node.getName(), destination.getName()) ? ConnectionStatus.DISCONNECTED : ConnectionStatus.CONNECTED; } @Override protected Optional<DisruptableMockTransport> getDisruptableMockTransport(TransportAddress address) { return testClusterNodes.nodes.values().stream().map(cn -> cn.mockTransport).filter(transport -> transport.getLocalNode().getAddress().equals(address)).findAny(); } @Override protected void execute(Runnable runnable) { scheduleNow(CoordinatorTests.onNodeLog(getLocalNode(), runnable)); } @Override protected NamedWriteableRegistry writeableRegistry() { return namedWriteableRegistry; } }; transportService = mockTransport.createTransportService(settings, deterministicTaskQueue.getThreadPool(runnable -> CoordinatorTests.onNodeLog(node, runnable)), new TransportInterceptor() { @Override public <T extends TransportRequest> TransportRequestHandler<T> interceptHandler(String action, String executor, boolean forceExecution, TransportRequestHandler<T> actualHandler) { if (action.startsWith("internal:index/shard/recovery")) { return (request, channel, task) -> scheduleSoon(new AbstractRunnable() { @Override protected void doRun() throws Exception { channel.sendResponse(new TransportException(new IOException("failed to recover shard"))); } @Override public void onFailure(final Exception e) { throw new AssertionError(e); } }); } else { return actualHandler; } } }, a -> node, null, emptySet()); final IndexNameExpressionResolver indexNameExpressionResolver = new IndexNameExpressionResolver(); repositoriesService = new RepositoriesService(settings, clusterService, transportService, Collections.singletonMap(FsRepository.TYPE, getRepoFactory(environment)), emptyMap(), threadPool); snapshotsService = new SnapshotsService(settings, clusterService, indexNameExpressionResolver, repositoriesService, threadPool); nodeEnv = new NodeEnvironment(settings, environment); final NamedXContentRegistry namedXContentRegistry = new NamedXContentRegistry(Collections.emptyList()); final ScriptService scriptService = new ScriptService(settings, emptyMap(), emptyMap()); client = new NodeClient(settings, threadPool); allocationService = ESAllocationTestCase.createAllocationService(settings); final IndexScopedSettings indexScopedSettings = new IndexScopedSettings(settings, IndexScopedSettings.BUILT_IN_INDEX_SETTINGS); final BigArrays bigArrays = new BigArrays(new PageCacheRecycler(settings), null, "test"); final MapperRegistry mapperRegistry = new IndicesModule(Collections.emptyList()).getMapperRegistry(); indicesService = new IndicesService(settings, mock(PluginsService.class), nodeEnv, namedXContentRegistry, new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap()), indexNameExpressionResolver, mapperRegistry, namedWriteableRegistry, threadPool, indexScopedSettings, new NoneCircuitBreakerService(), bigArrays, scriptService, client, new MetaStateService(nodeEnv, namedXContentRegistry), Collections.emptyList(), emptyMap()); final RecoverySettings recoverySettings = new RecoverySettings(settings, clusterSettings); final ActionFilters actionFilters = new ActionFilters(emptySet()); snapshotShardsService = new SnapshotShardsService(settings, clusterService, snapshotsService, threadPool, transportService, indicesService, actionFilters, indexNameExpressionResolver); final ShardStateAction shardStateAction = new ShardStateAction(clusterService, transportService, allocationService, new BatchedRerouteService(clusterService, allocationService::reroute), threadPool); @SuppressWarnings("rawtypes") Map<ActionType, TransportAction> actions = new HashMap<>(); actions.put(GlobalCheckpointSyncAction.TYPE, new GlobalCheckpointSyncAction(settings, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, indexNameExpressionResolver)); actions.put(RetentionLeaseBackgroundSyncAction.TYPE, new RetentionLeaseBackgroundSyncAction(settings, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, indexNameExpressionResolver)); actions.put(RetentionLeaseSyncAction.TYPE, new RetentionLeaseSyncAction(settings, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, indexNameExpressionResolver)); final MetaDataMappingService metaDataMappingService = new MetaDataMappingService(clusterService, indicesService); indicesClusterStateService = new IndicesClusterStateService(settings, indicesService, clusterService, threadPool, new PeerRecoveryTargetService(threadPool, transportService, recoverySettings, clusterService), shardStateAction, new NodeMappingRefreshAction(transportService, metaDataMappingService), repositoriesService, mock(SearchService.class), new SyncedFlushService(indicesService, clusterService, transportService, indexNameExpressionResolver), new PeerRecoverySourceService(transportService, indicesService, recoverySettings), snapshotShardsService, new PrimaryReplicaSyncer(transportService, new TransportResyncReplicationAction(settings, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, indexNameExpressionResolver)), client); final MetaDataCreateIndexService metaDataCreateIndexService = new MetaDataCreateIndexService(settings, clusterService, indicesService, allocationService, new AliasValidator(), environment, indexScopedSettings, threadPool, namedXContentRegistry, false); actions.put(CreateIndexAction.INSTANCE, new TransportCreateIndexAction(transportService, clusterService, threadPool, metaDataCreateIndexService, actionFilters, indexNameExpressionResolver)); final MappingUpdatedAction mappingUpdatedAction = new MappingUpdatedAction(settings, clusterSettings); mappingUpdatedAction.setClient(client); actions.put(BulkAction.INSTANCE, new TransportBulkAction(threadPool, transportService, clusterService, new IngestService(clusterService, threadPool, environment, scriptService, new AnalysisModule(environment, Collections.emptyList()).getAnalysisRegistry(), Collections.emptyList(), client), client, actionFilters, indexNameExpressionResolver, new AutoCreateIndex(settings, clusterSettings, indexNameExpressionResolver))); final TransportShardBulkAction transportShardBulkAction = new TransportShardBulkAction(settings, transportService, clusterService, indicesService, threadPool, shardStateAction, mappingUpdatedAction, new UpdateHelper(scriptService), actionFilters, indexNameExpressionResolver); actions.put(TransportShardBulkAction.TYPE, transportShardBulkAction); final RestoreService restoreService = new RestoreService(clusterService, repositoriesService, allocationService, metaDataCreateIndexService, new MetaDataIndexUpgradeService(settings, namedXContentRegistry, mapperRegistry, indexScopedSettings, Collections.emptyList()), clusterSettings); actions.put(PutMappingAction.INSTANCE, new TransportPutMappingAction(transportService, clusterService, threadPool, metaDataMappingService, actionFilters, indexNameExpressionResolver, new RequestValidators<>(Collections.emptyList()))); final ResponseCollectorService responseCollectorService = new ResponseCollectorService(clusterService); final SearchTransportService searchTransportService = new SearchTransportService(transportService, SearchExecutionStatsCollector.makeWrapper(responseCollectorService)); final SearchService searchService = new SearchService(clusterService, indicesService, threadPool, scriptService, bigArrays, new FetchPhase(Collections.emptyList()), responseCollectorService); actions.put(SearchAction.INSTANCE, new TransportSearchAction(threadPool, transportService, searchService, searchTransportService, new SearchPhaseController(searchService::createReduceContext), clusterService, actionFilters, indexNameExpressionResolver)); actions.put(RestoreSnapshotAction.INSTANCE, new TransportRestoreSnapshotAction(transportService, clusterService, threadPool, restoreService, actionFilters, indexNameExpressionResolver)); actions.put(DeleteIndexAction.INSTANCE, new TransportDeleteIndexAction(transportService, clusterService, threadPool, new MetaDataDeleteIndexService(settings, clusterService, allocationService), actionFilters, indexNameExpressionResolver, new DestructiveOperations(settings, clusterSettings))); actions.put(PutRepositoryAction.INSTANCE, new TransportPutRepositoryAction(transportService, clusterService, repositoriesService, threadPool, actionFilters, indexNameExpressionResolver)); actions.put(CreateSnapshotAction.INSTANCE, new TransportCreateSnapshotAction(transportService, clusterService, threadPool, snapshotsService, actionFilters, indexNameExpressionResolver)); actions.put(ClusterRerouteAction.INSTANCE, new TransportClusterRerouteAction(transportService, clusterService, threadPool, allocationService, actionFilters, indexNameExpressionResolver)); actions.put(ClusterStateAction.INSTANCE, new TransportClusterStateAction(transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver)); actions.put(IndicesShardStoresAction.INSTANCE, new TransportIndicesShardStoresAction(transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, client)); actions.put(TransportNodesListGatewayStartedShards.TYPE, new TransportNodesListGatewayStartedShards(settings, threadPool, clusterService, transportService, actionFilters, nodeEnv, indicesService, namedXContentRegistry)); actions.put(DeleteSnapshotAction.INSTANCE, new TransportDeleteSnapshotAction(transportService, clusterService, threadPool, snapshotsService, actionFilters, indexNameExpressionResolver)); client.initialize(actions, () -> clusterService.localNode().getId(), transportService.getRemoteClusterService()); } private Repository.Factory getRepoFactory(Environment environment) { if (blobStoreContext == null) { return metaData -> { final Repository repository = new FsRepository(metaData, environment, xContentRegistry(), threadPool) { @Override protected void assertSnapshotOrGenericThread() { } }; repository.start(); return repository; }; } else { return metaData -> { final Repository repository = new MockEventuallyConsistentRepository(metaData, environment, xContentRegistry(), deterministicTaskQueue.getThreadPool(), blobStoreContext); repository.start(); return repository; }; } } public void restart() { testClusterNodes.disconnectNode(this); final ClusterState oldState = this.clusterService.state(); stop(); testClusterNodes.nodes.remove(node.getName()); scheduleSoon(() -> { try { final TestClusterNode restartedNode = new TestClusterNode(new DiscoveryNode(node.getName(), node.getId(), node.getAddress(), emptyMap(), node.getRoles(), Version.CURRENT), disruption); testClusterNodes.nodes.put(node.getName(), restartedNode); restartedNode.start(oldState); } catch (IOException e) { throw new AssertionError(e); } }); } public void stop() { testClusterNodes.disconnectNode(this); indicesService.close(); clusterService.close(); indicesClusterStateService.close(); if (coordinator != null) { coordinator.close(); } nodeEnv.close(); } public void start(ClusterState initialState) { transportService.start(); transportService.acceptIncomingRequests(); snapshotsService.start(); snapshotShardsService.start(); final CoordinationState.PersistedState persistedState = new InMemoryPersistedState(initialState.term(), stateForNode(initialState, node)); coordinator = new Coordinator(node.getName(), clusterService.getSettings(), clusterService.getClusterSettings(), transportService, namedWriteableRegistry, allocationService, masterService, () -> persistedState, hostsResolver -> testClusterNodes.nodes.values().stream().filter(n -> n.node.isMasterNode()).map(n -> n.node.getAddress()).collect(Collectors.toList()), clusterService.getClusterApplierService(), Collections.emptyList(), random(), new BatchedRerouteService(clusterService, allocationService::reroute), ElectionStrategy.DEFAULT_INSTANCE); masterService.setClusterStatePublisher(coordinator); coordinator.start(); masterService.start(); clusterService.getClusterApplierService().setNodeConnectionsService(new NodeConnectionsService(clusterService.getSettings(), threadPool, transportService)); clusterService.getClusterApplierService().start(); indicesService.start(); indicesClusterStateService.start(); coordinator.startInitialJoin(); } } private final class DisconnectedNodes extends NetworkDisruption.DisruptedLinks { private final Set<String> disconnected = new HashSet<>(); @Override public boolean disrupt(String node1, String node2) { if (node1.equals(node2)) { return false; } if (testClusterNodes.nodes.containsKey(node1) == false || testClusterNodes.nodes.containsKey(node2) == false) { return true; } return disconnected.contains(node1) || disconnected.contains(node2); } public void disconnect(String node) { disconnected.add(node); } public void clear() { disconnected.clear(); } } }
[ "namasikanam@gmail.com" ]
namasikanam@gmail.com
0dd49cc2f22be5e6660d8c5f33a0da8171067f44
dcb92070b51f63ac3716b0709a7207109a0aee73
/Nanifarfalla/src/main/java/nanifarfalla/app/repository/PrivilegeRepository.java
33c1bbb85d1d5f521aa9ef2f9368b3e6236d5838
[]
no_license
joffrehermosilla/NanifarfallaApp
5a3f3a5d75e7ce3a2ba20d255147c0087a276f5b
9efae6d187cd4558ab2a3f167406eb4dd988e779
refs/heads/master
2023-01-07T12:40:43.139563
2023-01-02T00:26:18
2023-01-02T00:26:18
248,025,245
2
1
null
2022-12-16T15:50:04
2020-03-17T16:56:21
Java
UTF-8
Java
false
false
372
java
package nanifarfalla.app.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import nanifarfalla.app.model.Privilege; @Repository public interface PrivilegeRepository extends JpaRepository<Privilege, Integer> { Privilege findByName(String name); @Override void delete(Privilege privilege); }
[ "joffre.hermosilla@gmail.com" ]
joffre.hermosilla@gmail.com
ae2a43ff30533d1affb533079b64ad26a37e343f
c47136fc4bcb6548128bd10455e0942fa0c249a2
/eCommerce/src/eCommerce/adapters/GoogleRegistrationManagerAdapters.java
8f2f22f1d188474a9cc277a539de6817e8b01bba
[]
no_license
busraknya/day5
5e7b3d51de39b04d6ffadd3cc513acafdd2cc36c
acf737cffeb35606722e602caa4dc29b36a6e416
refs/heads/master
2023-04-12T04:55:41.637884
2021-05-19T18:33:07
2021-05-19T18:33:07
368,966,819
1
0
null
null
null
null
UTF-8
Java
false
false
398
java
package eCommerce.adapters; import eCommerce.business.concretes.GoogleRegistrationManager; import eCommerce.core.SignUpService; public class GoogleRegistrationManagerAdapters implements SignUpService{ @Override public void signUpToSystem() { GoogleRegistrationManager googleRegistrationManager = new GoogleRegistrationManager(); googleRegistrationManager.signUp(); } }
[ "busra@example.com" ]
busra@example.com
ec43816549e0820ff6b999653b5ae286139f5bb1
e6640144038dab496e868d28e324c3c72aaa0840
/src/main/数组/t31/NextPermutation.java
6f7223e8a966b4b5af925abd381065c26caac57c
[]
no_license
sotowang/leetcode
f8de0530521eb864b07509ae45c5c916341b5f12
83970f766c95ea8dd84b187dd583ee1ac6ee330e
refs/heads/master
2021-12-01T01:32:50.646299
2021-11-15T13:25:37
2021-11-15T13:25:37
207,312,983
1
0
null
null
null
null
UTF-8
Java
false
false
1,789
java
package 数组.t31; import java.util.Arrays; /** * @auther: sotowang * @date: 2019/12/03 21:01 */ public class NextPermutation { public void nextPermutation(int[] nums) { if(nums == null || nums.length <= 1){ return; } //找最大的索引nums[k]<nums[k+1] int k = -1; for(int i=nums.length-1;i> 0;i--){ if(nums[i]>nums[i-1]){ k = i-1; break; } } //原数组为逆序排序,翻转数组 if(k == -1){ reverse(nums,0,nums.length-1); return; } //找最大索引 nums[m]>nums[k] int m = -1; for(int i=nums.length-1;i>k;i--){ if(nums[i]>nums[k]){ m = i; break; } } swap(nums,k,m); reverse(nums,k+1,nums.length-1); } private void reverse(int[] nums,int start,int end){ while(start<end){ swap(nums,start++,end--); } } private void swap(int[] nums,int i,int j){ int tem = nums[i]; nums[i] = nums[j]; nums[j] = tem; } public static void main(String[] args) { int[] nums3 = { 1 }; new NextPermutation().nextPermutation(nums3); Arrays.stream(nums3).forEach(System.out::print); System.out.println(); int[] nums1 = { 1, 2, 7, 4, 3, 1 }; new NextPermutation().nextPermutation(nums1); Arrays.stream(nums1).forEach(System.out::print); System.out.println(); int[] nums2 = { 1,2,3 }; new NextPermutation().nextPermutation(nums2); Arrays.stream(nums2).forEach(System.out::print); } }
[ "sotowang@qq.com" ]
sotowang@qq.com
a551791ad6901e21c25a53d08ddff52fc6413725
526525e2b51b717cb621b1350e77786e18c7bbb1
/java/v1/wsm-gateway/src/main/java/com/study/controller/FallbackController.java
69c07ecad3635c6eaa9060dfc4f36802e823b38c
[]
no_license
wsm1217395196/my-study
f2781fe213b2fe6c5749c2146c866ba48dce280c
884aeb82cc16ad11fb7a9f0e3cd82df9ec2e7a80
refs/heads/master
2022-12-13T06:46:20.257428
2021-04-22T08:38:00
2021-04-22T08:38:00
170,282,056
120
81
null
2022-12-09T15:45:42
2019-02-12T08:37:26
Java
UTF-8
Java
false
false
681
java
package com.study.controller; import com.study.result.ResultEnum; import com.study.result.ResultView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 通用熔断器 */ @RestController @RequestMapping("common") public class FallbackController { Logger logger = LoggerFactory.getLogger(FallbackController.class); @RequestMapping("fallback") public ResultView fallback() { ResultView resultView = ResultView.error(ResultEnum.CODE_504); logger.error(resultView.toString()); return resultView; } }
[ "1217395196@qq.com" ]
1217395196@qq.com
43a8d571aabaa20e0669af9e4f8c457d52598fd4
8e9475c1a3027b17135d92509d32f36fc535bdbd
/manger-service/src/main/java/com/neusoft/mangerservice/dao/SkuSaleAttrValueMapper.java
3edf2870a14def6489b89fc3b59dcf65266de425
[]
no_license
LiYangHui/guli2019
67b58d72fbe56cc22afd2a89e19553a334e6868c
4d967e85a707a9a95fa2d8a3d69f5ba787acb61b
refs/heads/master
2020-05-25T02:54:26.342639
2019-05-20T07:25:26
2019-05-20T07:25:26
187,589,422
0
0
null
null
null
null
UTF-8
Java
false
false
203
java
package com.neusoft.mangerservice.dao; import com.neusoft.bean.po.SkuSaleAttrValue; import tk.mybatis.mapper.common.Mapper; public interface SkuSaleAttrValueMapper extends Mapper<SkuSaleAttrValue> { }
[ "473035600@qq.com" ]
473035600@qq.com
d75dfe610a2c71588ca38d469432ceea3c7b702a
5ebf65936485d5f96a31107da434dd39d7fbd7fe
/app/src/main/java/com/example/applicationstore/BannerPagerAdapter.java
caf7fbc28f0ff495675e7a0a23fb001762d07763
[]
no_license
yenan-wang/ApplicationStore
7cda56ce8f970a5135082ff48f96ca72be24b9dd
aeaf2eba4b4af8697d8317b3766abf0861ba859c
refs/heads/master
2023-02-18T18:11:01.977571
2021-01-16T03:43:20
2021-01-16T03:43:20
330,077,215
0
0
null
null
null
null
UTF-8
Java
false
false
259
java
package com.example.applicationstore; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager;
[ "3428141843@qq.com" ]
3428141843@qq.com
e8aeeea6b1c90f734c75eb77c132fc2f8e0a4955
5d074dd947c711363a839631e9d9ef1db6025535
/src/main/java/com/example/validate/annotation/validate/MultipleOfThreeForInteger.java
e5724562b2daf2e0659876bd58b752ab6933db4c
[]
no_license
weixiding/springValidateExample
f6c928a47dbb7e1169e2b7240d3ae2f152f1848e
5595f2790a470995a4932d0076ea0a868e1d87bb
refs/heads/master
2022-12-13T22:47:23.352627
2020-09-13T15:53:23
2020-09-13T15:53:23
295,182,022
0
0
null
null
null
null
UTF-8
Java
false
false
1,028
java
/** * Copyright (C), 2015-2020, XXX有限公司 * FileName: MultipleOfThreeForInteger * Author: Administrator * Date: 2020/9/13 21:09 * Description: * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.example.validate.annotation.validate; import com.example.validate.annotation.MultipleOfThree; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * 〈一句话功能简述〉<br> * 〈〉 * * @author Administrator * @create 2020/9/13 * @since 1.0.0 */ public class MultipleOfThreeForInteger implements ConstraintValidator<MultipleOfThree,Integer> { @Override public void initialize(MultipleOfThree constraintAnnotation) { } @Override public boolean isValid(Integer value, ConstraintValidatorContext context) { if(value == null) { return true; } return value % 3 == 0; } }
[ "18513655955@163.com" ]
18513655955@163.com
e05c5daa9732ffbd12fb2e5007e158b7c471d260
4d1123fabcb4fc00ccf0da606c9e888d39ebc4fe
/src/main/java/cn/net/easyinfo/bean/Nation.java
1edb4351fe5a8cd013680da6f10fe8281dedc53c
[]
no_license
wzy010/chwx-server
8d4fbd854a5b6e167d660d58234bf80fcb75e4de
9bebffb070973ab1e7213dcba1afedd2cd4e4647
refs/heads/master
2020-05-25T11:41:02.336385
2019-05-21T07:34:50
2019-05-21T07:34:50
187,783,589
0
0
null
null
null
null
UTF-8
Java
false
false
819
java
package cn.net.easyinfo.bean; public class Nation { private Long id; private String name; public Nation(String name) { this.name = name; } public Nation() { } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Nation nation = (Nation) o; return name != null ? name.equals(nation.name) : nation.name == null; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
[ "wzy_omg@163.com" ]
wzy_omg@163.com
34ada9eb3b66517a3168b41b3d1002ef0b898d74
9734788136d0f4e10b603b9b81e8e175b90480b4
/src/main/java/com/cloudaware/cloudmine/amazon/mq/ConfigurationRevisionsResponse.java
3ad4a61e4b117a82a323294942a11dcfbe049619
[]
no_license
cloudaware/cloudmine-amazon
09c9d601a84dc83a88f083ce3fc8aa07eef3baec
1d952c24ff4a22b81f0e45b9a94092da1aa7bcd3
refs/heads/master
2022-11-16T20:22:09.957296
2019-12-03T12:09:22
2019-12-03T12:09:22
90,200,079
1
12
null
2022-11-16T06:28:29
2017-05-03T22:53:22
Java
UTF-8
Java
false
false
524
java
package com.cloudaware.cloudmine.amazon.mq; import com.amazonaws.services.mq.model.ConfigurationRevision; import com.cloudaware.cloudmine.amazon.AmazonResponse; import java.util.List; public final class ConfigurationRevisionsResponse extends AmazonResponse { private List<ConfigurationRevision> revisions; public List<ConfigurationRevision> getRevisions() { return revisions; } public void setRevisions(final List<ConfigurationRevision> revisions) { this.revisions = revisions; } }
[ "kbabintsev@gmail.com" ]
kbabintsev@gmail.com
c4da38cfba1699b68fe2a6e100f0e8c51ef641ba
9f21173406f4be837c397441a18a50e56883eee9
/cs1550/a4/Opt.java
e9348a605fe028f60109342398a04cfd9da162f1
[]
no_license
JHauser48/University-of-Pittsburgh
0d464cba2c511ea1534c24ef4975562f4fc4b92b
36249b5960f1838a1340996eaa0e2129da321627
refs/heads/master
2021-07-21T08:09:11.956860
2019-08-04T19:34:00
2019-08-04T19:34:00
200,525,013
0
0
null
2020-07-28T04:41:50
2019-08-04T17:57:55
C
UTF-8
Java
false
false
6,051
java
/* Optimal Page Replacement Algorithm */ import java.lang.*; import java.io.*; import java.util.*; public class Opt { private String filename; private int num_frames; private int total_mem_acc, total_pg_faults, total_writes_to_disk; private PTE[] RAM; // used on the first runthrough to holds accessed pages in sequenced order, used to simulate optimal page replacement private Hashtable<Integer, LinkedList<Integer>> access_table; private Hashtable<Integer, Integer> page_table; // not full page table, holds accessed pages private BufferedReader br; // constructor public Opt(int frames, String tracefile) { filename = tracefile; num_frames = frames; total_mem_acc = 0; total_pg_faults = 0; total_writes_to_disk = 0; RAM = new PTE[num_frames]; page_table = new Hashtable<Integer, Integer>(); access_table = new Hashtable<Integer, LinkedList<Integer>>(); } public void run() throws IOException { // check for IO Errors try{ br = new BufferedReader(new FileReader(filename)); } catch (IOException e){ System.err.println(e); return; } int cur_page; int sequence = 0; String line = br.readLine(); //first run through to simulate optimal algorithm while(line != null) { // get the address, decode the value to an int and set it as the current page String address = "0x" + line.substring(0, 5); long mem_addr = Long.decode(address); cur_page = (int)(mem_addr); // if not in table, put it in with a new linked list if(!access_table.containsKey(cur_page)){ access_table.put(cur_page, new LinkedList<Integer>()); } // get the linked list of the current page LinkedList<Integer> next = access_table.get(cur_page); next.add(sequence); // update/add the sequence number, put in table access_table.put(cur_page, next); sequence++; line = br.readLine(); //next line } // check for IO errors try{ br = new BufferedReader(new FileReader(filename)); } catch (IOException e){ System.err.println(e); return; } line = br.readLine(); char r_w; int frames = 0; while(line != null){ // get the address, decode the value to an int and set it as the current page String address = "0x" + line.substring(0, 5); long mem_addr = Long.decode(address); cur_page = (int)(mem_addr); r_w = line.charAt(9); total_mem_acc++; // if room in memory, remove from access table if(frames < num_frames){ access_table.get(cur_page).remove(0); if(page_table.containsKey(cur_page)){ System.out.println(address + " hit"); if(r_w == 'W'){ // check for dirty bit int cur_frame = page_table.get(cur_page); RAM[cur_frame].setDirty(true); } }else{ System.out.println(address + " page fault, no eviction"); // add page to table, no need for eviction page_table.put(cur_page, frames); RAM[frames] = new PTE(cur_page); RAM[frames].setReference(true); RAM[frames].setValid(true); if (r_w == 'W'){ // check for dirty bit int cur_frame = page_table.get(cur_page); RAM[cur_frame].setDirty(true); } total_pg_faults++; frames++; } }else{ //remove page from access table access_table.get(cur_page).remove(0); // if page is in table if(page_table.containsKey(cur_page)){ System.out.println(address + " hit"); if(r_w == 'W'){ // check for dirty bit int cur_frame = page_table.get(cur_page); RAM[cur_frame].setDirty(true); } }else{ // need to evict the optimal page total_pg_faults++; int evicted = 0; int farthest = 0; // go through all pages in RAM for (PTE page : RAM){ int candidate_page = page.getPageNum(); // get page number of candidate if (access_table.get(candidate_page).isEmpty()){ // if empty, choose this page to evict evicted = page_table.get(candidate_page); break; } int next_use = access_table.get(candidate_page).get(0); // get the farthese away used reference from current candidate farthest = access_table.get(RAM[evicted].getPageNum()).get(0); if (next_use > farthest) evicted = page_table.get(candidate_page); // if farther, change candidate page } if (RAM[evicted].getDirty()){ //check for dirty bit, evict appropriately total_writes_to_disk++; System.out.println(address + " page fault, evict dirty"); }else{ System.out.println(address + " page fault, evict clean"); } // remove page from memory and reset its attributes int remove_page = RAM[evicted].getPageNum(); page_table.remove(remove_page); RAM[evicted] = new PTE(cur_page); page_table.put(cur_page, evicted); RAM[evicted].setReference(true); RAM[evicted].setValid(true); if (r_w == 'W') RAM[evicted].setDirty(true); // check for dirty bit } } line = br.readLine(); // next line in file } // summary information System.out.println("\nAlgorithm:\t\tOPT"); System.out.println("Number of frames:\t" + num_frames); System.out.println("Total memory accesses:\t" + total_mem_acc); System.out.println("Total page faults:\t" + total_pg_faults); System.out.println("Total writes to disk:\t" + total_writes_to_disk); } }
[ "noreply@github.com" ]
noreply@github.com
d8f3246c39de29b51a45f842605215e203dbf2b3
495bdd7cf547166e434941ae002d15dd60405541
/src/main/java/org/teasoft/exam/bee/osql/CacheTestDel.java
244d882373cf620ae211fba58adf6847365b7fc8
[]
no_license
CaSiOFT/bee-exam
782006201b863d2c856504bad3974bcd883421eb
9ce91000e67b267800ca1ae411bbcf31defba466
refs/heads/master
2022-12-06T00:40:28.463695
2020-08-22T15:30:32
2020-08-22T15:30:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,043
java
/* * Copyright 2013-2020 the original author.All rights reserved. * Kingstar(honeysoft@126.com) * The license,see the LICENSE file. */ package org.teasoft.exam.bee.osql; import org.teasoft.bee.osql.BeeException; import org.teasoft.bee.osql.Suid; import org.teasoft.bee.osql.SuidRich; import org.teasoft.exam.bee.osql.entity.Orders; import org.teasoft.honey.osql.core.BeeFactory; import org.teasoft.honey.osql.core.Logger; /** * @author Kingstar * @since 1.1 */ public class CacheTestDel { public static void main(String[] args) { test(); } public static void test() { try { Suid suid=BeeFactory.getHoneyFactory().getSuid(); SuidRich suidRich=BeeFactory.getHoneyFactory().getSuidRich(); Orders orders0=new Orders(); orders0.setUserid("bee0"); Orders orders1=new Orders(); orders1.setId(100001L); orders1.setName("Bee--ORM Framework"); Orders orders2=new Orders(); orders2.setUserid("bee2"); orders2.setName("Bee--ORM Framework"); orders2.setRemark(""); //empty String test Orders orders3=new Orders(); orders3.setUserid("bee3"); Orders orders4=new Orders(); orders4.setUserid("bee4"); Orders orders5=new Orders(); orders5.setUserid("bee5"); Orders orders6=new Orders(); orders6.setUserid("bee6"); Orders orders7=new Orders(); orders7.setUserid("bee7"); Orders orders8=new Orders(); orders8.setUserid("bee8"); Orders orders9=new Orders(); orders9.setUserid("bee9"); Orders orders10=new Orders(); orders10.setUserid("bee10"); Orders orders11=new Orders(); orders11.setUserid("bee11"); Orders orders12=new Orders(); orders12.setUserid("bee12"); suid.select(orders0); suid.select(orders1); // orders1.setRemark("other"); // suid.update(orders1); // suid.select(orders1); suid.delete(orders1); suid.select(orders2); suid.select(orders3); suid.select(orders4); suid.select(orders5); suid.select(orders6); try { Thread.sleep(12000); } catch (Exception e) { e.printStackTrace(); } suid.select(orders3); //delete 0,3 suid.select(orders7); suid.select(orders8); suid.select(orders9); suid.select(orders10); try { Thread.sleep(12000); } catch (Exception e) { e.printStackTrace(); } suid.select(orders3); suid.select(orders8); suid.select(orders11); try { Thread.sleep(12000); } catch (Exception e) { // TODO: handle exception } // suid.select(orders8); //delete one suid.select(orders11);//delte some suid.select(orders8); } catch (BeeException e) { Logger.error("In CacheTestDel (BeeException):"+e.getMessage()); e.printStackTrace(); }catch (Exception e) { Logger.error("In CacheTestDel (Exception):"+e.getMessage()); e.printStackTrace(); } } }
[ "honeysoft@126.com" ]
honeysoft@126.com
c204df4303c0bc23163b802ccab78c1cedf8d097
ce1e2f4b42d8d2565435e6a2f7699b232400895e
/src/focus/SortIntegersDecrease.java
01abd127e74fab145c64ccfdfd6d02255dda7349
[]
no_license
vdvz/ProjectForShiftFocus
5bd68dfed6da48255d6b53fd49554466c38e6005
031ab78a1832ad2d64c7dfda01d7ffa6906f48b0
refs/heads/master
2023-03-09T03:05:33.538968
2021-02-28T17:00:22
2021-02-28T17:00:22
295,663,732
0
0
null
null
null
null
UTF-8
Java
false
false
1,080
java
package focus; import java.io.EOFException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Map; public class SortIntegersDecrease extends SortIntegers { SortIntegersDecrease(ArrayList<String> in, String out) throws FileNotFoundException, IOException { super(in, out); } @Override public Integer getNext() throws OrderViolationException, IllegalArgumentException { Integer maxInt = Integer.MIN_VALUE; Reader_I reader = null; for (Map.Entry<Reader_I, Integer> entry: map.entrySet()) { if(entry.getValue() > maxInt){ maxInt = entry.getValue(); reader = entry.getKey(); } } try{ assert reader != null; map.replace(reader, Integer.valueOf(reader.getNext())); } catch (EOFException e){ map.remove(reader); } if(lastWrittenInt!=null && maxInt > lastWrittenInt) throw new OrderViolationException(); return maxInt; } }
[ "vizir.vadim@mail.ru" ]
vizir.vadim@mail.ru
e3fb46f3fbaeda7bfeaddd39108f65fde3ca26e1
129f58086770fc74c171e9c1edfd63b4257210f3
/src/testcases/CWE191_Integer_Underflow/CWE191_Integer_Underflow__byte_rand_multiply_75b.java
84b3e0e40123b55ba40e248502a070f2c542c785
[]
no_license
glopezGitHub/Android23
1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba
6215d0684c4fbdc7217ccfbedfccfca69824cc5e
refs/heads/master
2023-03-07T15:14:59.447795
2023-02-06T13:59:49
2023-02-06T13:59:49
6,856,387
0
3
null
2023-02-06T18:38:17
2012-11-25T22:04:23
Java
UTF-8
Java
false
false
6,072
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__byte_rand_multiply_75b.java Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-75b.tmpl.java */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: multiply * GoodSink: Ensure there will not be an underflow before multiplying data by 2 * BadSink : If data is negative, multiply by 2, which can cause an underflow * Flow Variant: 75 Data flow: data passed in a serialized object from one method to another in different source files in the same package * * */ package testcases.CWE191_Integer_Underflow; import testcasesupport.*; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class CWE191_Integer_Underflow__byte_rand_multiply_75b { public void bad_sink(byte[] data_serialized ) throws Throwable { // unserialize data ByteArrayInputStream bais = null; ObjectInputStream in = null; try { bais = new ByteArrayInputStream(data_serialized); in = new ObjectInputStream(bais); byte data = (Byte)in.readObject(); if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Byte.MIN_VALUE, this will underflow */ byte result = (byte)(data * 2); IO.writeLine("result: " + result); } } catch (IOException e) { IO.logger.log(Level.WARNING, "IOException in deserialization", e); } catch (ClassNotFoundException e) { IO.logger.log(Level.WARNING, "ClassNotFoundException in deserialization", e); } finally { // clean up stream reading objects try { if (in != null) { in.close(); } } catch (IOException ioe) { IO.logger.log(Level.WARNING, "Error closing ObjectInputStream", ioe); } try { if (bais != null) { bais.close(); } } catch (IOException ioe) { IO.logger.log(Level.WARNING, "Error closing ByteArrayInputStream", ioe); } } } /* goodG2B() - use GoodSource and BadSink */ public void goodG2B_sink(byte[] data_serialized ) throws Throwable { // unserialize data ByteArrayInputStream bais = null; ObjectInputStream in = null; try { bais = new ByteArrayInputStream(data_serialized); in = new ObjectInputStream(bais); byte data = (Byte)in.readObject(); if(data < 0) /* ensure we won't have an overflow */ { /* POTENTIAL FLAW: if (data * 2) < Byte.MIN_VALUE, this will underflow */ byte result = (byte)(data * 2); IO.writeLine("result: " + result); } } catch (IOException e) { IO.logger.log(Level.WARNING, "IOException in deserialization", e); } catch (ClassNotFoundException e) { IO.logger.log(Level.WARNING, "ClassNotFoundException in deserialization", e); } finally { // clean up stream reading objects try { if (in != null) { in.close(); } } catch (IOException ioe) { IO.logger.log(Level.WARNING, "Error closing ObjectInputStream", ioe); } try { if (bais != null) { bais.close(); } } catch (IOException ioe) { IO.logger.log(Level.WARNING, "Error closing ByteArrayInputStream", ioe); } } } /* goodB2G() - use BadSource and GoodSink */ public void goodB2G_sink(byte[] data_serialized ) throws Throwable { // unserialize data ByteArrayInputStream bais = null; ObjectInputStream in = null; try { bais = new ByteArrayInputStream(data_serialized); in = new ObjectInputStream(bais); byte data = (Byte)in.readObject(); if(data < 0) /* ensure we won't have an overflow */ { /* FIX: Add a check to prevent an underflow from occurring */ if (data > (Byte.MIN_VALUE/2)) { byte result = (byte)(data * 2); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform multiplication."); } } } catch (IOException e) { IO.logger.log(Level.WARNING, "IOException in deserialization", e); } catch (ClassNotFoundException e) { IO.logger.log(Level.WARNING, "ClassNotFoundException in deserialization", e); } finally { // clean up stream reading objects try { if (in != null) { in.close(); } } catch (IOException ioe) { IO.logger.log(Level.WARNING, "Error closing ObjectInputStream", ioe); } try { if (bais != null) { bais.close(); } } catch (IOException ioe) { IO.logger.log(Level.WARNING, "Error closing ByteArrayInputStream", ioe); } } } }
[ "guillermo.pando@gmail.com" ]
guillermo.pando@gmail.com
5c2aa628ae876f522dd696ce18276120f045418e
423d4f2ef7e7af8153e5143d7e410f519c73b431
/app/src/main/java/com/Tamm/Hotels/wcf/RoomCombination.java
2dd0e77852fc15e785b7e8e9dfc52301ece8fd2e
[]
no_license
Abd-Allah-muhammed-muhammed/FaceArApp
5e1ca10d9d1bac86ad195415d17bcf00e5e6415a
0232f534ded0f15a91c55cd85416a996770261ee
refs/heads/master
2022-04-10T11:30:15.692919
2020-01-30T09:58:57
2020-01-30T09:58:57
216,262,702
0
0
null
null
null
null
UTF-8
Java
false
false
4,143
java
package com.Tamm.Hotels.wcf; //---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.5.6.0 // // Created by Quasar Development // //--------------------------------------------------- import org.ksoap2.serialization.AttributeContainer; import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import java.util.ArrayList; import java.util.Hashtable; public class RoomCombination extends AttributeContainer implements KvmSerializable { public ArrayList<Integer> RoomIndex = new ArrayList<Integer>(); public String TestElement; private transient java.lang.Object __source; public void loadFromSoap(java.lang.Object paramObj, ExtendedSoapSerializationEnvelope __envelope) { if (paramObj == null) return; AttributeContainer inObj = (AttributeContainer) paramObj; __source = inObj; if (inObj instanceof SoapObject) { SoapObject soapObject = (SoapObject) inObj; int size = soapObject.getPropertyCount(); for (int i0 = 0; i0 < size; i0++) { PropertyInfo info = soapObject.getPropertyInfo(i0); if (!loadProperty(info, soapObject, __envelope)) { } } } } protected boolean loadProperty(PropertyInfo info, SoapObject soapObject, ExtendedSoapSerializationEnvelope __envelope) { java.lang.Object obj = info.getValue(); if (info.name.equals("RoomIndex")) { if (obj != null) { if (this.RoomIndex == null) { this.RoomIndex = new java.util.ArrayList<Integer>(); } java.lang.Object j = obj; Integer j1 = Integer.parseInt(j.toString()); this.RoomIndex.add(j1); } return true; } if (info.name.equals("TestElement")) { if (obj != null) { if (obj.getClass().equals(SoapPrimitive.class)) { SoapPrimitive j = (SoapPrimitive) obj; if (j.toString() != null) { this.TestElement = j.toString(); } } else if (obj instanceof String) { this.TestElement = (String) obj; } } return true; } return false; } public java.lang.Object getOriginalXmlSource() { return __source; } @Override public java.lang.Object getProperty(int propertyIndex) { //!!!!! If you have a compilation error here then you are using old version of ksoap2 library. Please upgrade to the latest version. //!!!!! You can find a correct version in Lib folder from generated zip file!!!!! if (propertyIndex >= 0 && propertyIndex < 0 + this.RoomIndex.size()) { java.lang.Object RoomIndex = this.RoomIndex.get(propertyIndex - (0)); return RoomIndex != null ? RoomIndex : SoapPrimitive.NullNilElement; } if (propertyIndex == 0 + this.RoomIndex.size()) { return this.TestElement != null ? this.TestElement : SoapPrimitive.NullSkip; } return null; } @Override public int getPropertyCount() { return 1 + RoomIndex.size(); } @Override public void getPropertyInfo(int propertyIndex, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) { if (propertyIndex >= 0 && propertyIndex < 0 + this.RoomIndex.size()) { info.type = PropertyInfo.INTEGER_CLASS; info.name = "RoomIndex"; info.namespace = "http://TekTravel/HotelBookingApi"; } if (propertyIndex == 0 + this.RoomIndex.size()) { info.type = PropertyInfo.STRING_CLASS; info.name = "TestElement"; info.namespace = "http://TekTravel/HotelBookingApi"; } } @Override public void setProperty(int arg0, java.lang.Object arg1) { } }
[ "shahawi273@gmail.com" ]
shahawi273@gmail.com
10a7f0642b9f2a2e606eef07916c37d50e462304
2bc2eadc9b0f70d6d1286ef474902466988a880f
/tags/mule-2.0.0-RC1/modules/xml/src/main/java/org/mule/transformers/xml/AbstractXmlTransformer.java
42832f2165bb6ffa524d31cb779fcf2db8960d16
[]
no_license
OrgSmells/codehaus-mule-git
085434a4b7781a5def2b9b4e37396081eaeba394
f8584627c7acb13efdf3276396015439ea6a0721
refs/heads/master
2022-12-24T07:33:30.190368
2020-02-27T19:10:29
2020-02-27T19:10:29
243,593,543
0
0
null
2022-12-15T23:30:00
2020-02-27T18:56:48
null
UTF-8
Java
false
false
10,335
java
/* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.transformers.xml; import org.mule.transformers.AbstractTransformer; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.output.ByteArrayOutputStream; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; /** * <code>AbstractXmlTransformer</code> offers some XSLT transform on a DOM (or * other XML-ish) object. */ public abstract class AbstractXmlTransformer extends AbstractTransformer { private String outputEncoding; public AbstractXmlTransformer() { registerSourceType(String.class); registerSourceType(byte[].class); registerSourceType(DocumentSource.class); registerSourceType(Document.class); registerSourceType(org.w3c.dom.Document.class); registerSourceType(org.w3c.dom.Element.class); registerSourceType(InputStream.class); setReturnClass(byte[].class); } public Source getXmlSource(Object src) { if (src instanceof byte[]) { return new StreamSource(new ByteArrayInputStream((byte[]) src)); } else if (src instanceof InputStream) { return new StreamSource((InputStream) src); } else if (src instanceof String) { return new StreamSource(new StringReader((String) src)); } else if (src instanceof DocumentSource) { return (Source) src; } else if (src instanceof Document) { return new DocumentSource((Document) src); } else if (src instanceof org.w3c.dom.Document || src instanceof org.w3c.dom.Element) { return new DOMSource((org.w3c.dom.Node) src); } else { return null; } } /** Result callback interface used when processing XML through JAXP */ protected static interface ResultHolder { /** * @return A Result to use in a transformation (e.g. writing a DOM to a * stream) */ Result getResult(); /** @return The actual result as produced after the call to 'transform'. */ Object getResultObject(); } /** * @param desiredClass Java class representing the desired format * @return Callback interface representing the desiredClass - or null if the * return class isn't supported (or is null). */ protected static ResultHolder getResultHolder(Class desiredClass) { if (desiredClass == null) { return null; } if (byte[].class.equals(desiredClass) || InputStream.class.isAssignableFrom(desiredClass)) { return new ResultHolder() { ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(resultStream); public Result getResult() { return result; } public Object getResultObject() { return resultStream.toByteArray(); } }; } else if (String.class.equals(desiredClass)) { return new ResultHolder() { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); public Result getResult() { return result; } public Object getResultObject() { return writer.getBuffer().toString(); } }; } else if (org.w3c.dom.Document.class.isAssignableFrom(desiredClass)) { return new ResultHolder() { DOMResult result = new DOMResult(); public Result getResult() { return result; } public Object getResultObject() { return result.getNode(); } }; } else if (org.dom4j.io.DocumentResult.class.isAssignableFrom(desiredClass)) { return new ResultHolder() { DocumentResult result = new DocumentResult(); public Result getResult() { return result; } public Object getResultObject() { return result; } }; } else if (org.dom4j.Document.class.isAssignableFrom(desiredClass)) { return new ResultHolder() { DocumentResult result = new DocumentResult(); public Result getResult() { return result; } public Object getResultObject() { return result.getDocument(); } }; } return null; } /** * Converts an XML in-memory representation to a String * * @param obj Object to convert (could be byte[], String, DOM, DOM4J) * @return String including XML header using default (UTF-8) encoding * @throws TransformerFactoryConfigurationError * On error * @throws javax.xml.transform.TransformerException * On error * @deprecated Replaced by convertToText(Object obj, String ouputEncoding) */ protected String convertToText(Object obj) throws TransformerFactoryConfigurationError, javax.xml.transform.TransformerException { return convertToText(obj, null); } /** * Converts an XML in-memory representation to a String using a specific encoding. * If using an encoding which cannot represent specific characters, these are * written as entities, even if they can be represented as a Java String. * * @param obj Object to convert (could be byte[], String, DOM, or DOM4J Document). * If the object is a byte[], the character * encoding used MUST match the declared encoding standard, or a parse error will occur. * @param outputEncoding Name of the XML encoding to use, e.g. US-ASCII, or null for UTF-8 * @return String including XML header using the specified encoding * @throws TransformerFactoryConfigurationError * On error * @throws javax.xml.transform.TransformerException * On error */ protected String convertToText(Object obj, String outputEncoding) throws TransformerFactoryConfigurationError, javax.xml.transform.TransformerException { // Catch the direct translations if (obj instanceof String) { return (String) obj; } else if (obj instanceof Document) { return ((Document) obj).asXML(); } // No easy fix, so use the transformer. Source src = getXmlSource(obj); if (src == null) { return null; } StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); if (outputEncoding != null) { idTransformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); } idTransformer.transform(src, result); return writer.getBuffer().toString(); } /** * Converts an XML in-memory representation to a String using a specific encoding. * * @param obj Object to convert (could be byte[], String, DOM, or DOM4J Document). * If the object is a byte[], the character * encoding used MUST match the declared encoding standard, or a parse error will occur. * @param outputEncoding Name of the XML encoding to use, e.g. US-ASCII, or null for UTF-8 * @return String including XML header using the specified encoding * @throws TransformerFactoryConfigurationError * On error * @throws javax.xml.transform.TransformerException * On error */ protected String convertToBytes(Object obj, String outputEncoding) throws TransformerFactoryConfigurationError, javax.xml.transform.TransformerException { // Always use the transformer, even for byte[] (to get the encoding right!) Source src = getXmlSource(obj); if (src == null) { return null; } StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); idTransformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); idTransformer.transform(src, result); return writer.getBuffer().toString(); } /** @return the outputEncoding */ public String getOutputEncoding() { return outputEncoding; } /** @param outputEncoding the outputEncoding to set */ public void setOutputEncoding(String outputEncoding) { this.outputEncoding = outputEncoding; } }
[ "tcarlson@bf997673-6b11-0410-b953-e057580c5b09" ]
tcarlson@bf997673-6b11-0410-b953-e057580c5b09
61e13ffe174f3908da1f20842532924abe7e4ab3
31d6d2db13336642608bb976cd5c658fd01f4c80
/JungOl/src/Basis/Select/Control/Main121.java
13e2b66f511a624429e9f7ec988e07cff52e9b2e
[]
no_license
yotegy/algorithm
e632e34be1c7902d686c0dbb9587790befc0591f
9908b00f7fd2843103f82ca910b19906dc97482f
refs/heads/master
2020-04-05T14:38:38.583290
2016-11-11T15:45:54
2016-11-11T15:45:54
56,971,226
0
0
null
null
null
null
UTF-8
Java
false
false
384
java
package Basis.Select.Control; import java.util.Scanner; public class Main121 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int a = in.nextInt(); if(a > 0 ){ System.out.println("plus"); }else if( a == 0){ System.out.println("zero"); }else{ System.out.println("minus"); } } }
[ "yotegy@gmail.com" ]
yotegy@gmail.com
dab2cdfde5163ff5796ee58ceb51f9c9a543a26f
750d976222ec6f5910c2104cbd26e0f26091e550
/src/main/java/com/mcin/RunReptile/ExportExcel.java
85349fd6ffd5f765460bc9dddaf5ca44ef379076
[]
no_license
chenmingq/padata
e6f09d7535ef0c64435d250db204d49713241ef0
543821f10c81591552a4f9c018fb94e3b91e0492
refs/heads/master
2021-06-19T09:25:24.443856
2017-05-31T03:11:33
2017-05-31T03:11:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,081
java
package com.mcin.RunReptile; import com.mcin.dao.InfoMapper; import com.mcin.dao.impl.InfoDaoImpl; import com.mcin.model.Info; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by Mcin on 2017/5/17. * 导出excel */ public class ExportExcel { private static final Logger logger = Logger.getLogger(ExportExcel.class); /** * 保存路径和文件名 */ static String FILE_NAME_PATH = "E:/慧聪___服装信息企业联系信息"+new Date().getTime()+".xls"; /** * 手工构建一个excel * @return * @throws Exception */ private static List<Info> getStudent() { InfoMapper infoMapper = new InfoDaoImpl(); List<Info> list = new ArrayList<Info>(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); list = infoMapper.selectInfo(); return list; } public static void main(String[] args) { // 第一步,创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet("企业联系信息"); // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row = sheet.createRow( 0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell((short) 0); cell.setCellValue("序号"); cell.setCellStyle(style); cell = row.createCell((short) 1); cell.setCellValue("公司名称"); cell.setCellStyle(style); cell = row.createCell((short) 2); cell.setCellValue("公司信息"); cell.setCellStyle(style); cell = row.createCell((short) 3); cell.setCellValue("公司网站"); cell.setCellStyle(style); cell = row.createCell((short) 4); cell.setCellValue("创建时间"); cell.setCellStyle(style); // 第五步,写入实体数据 实际应用中这些数据从数据库得到, List list = ExportExcel.getStudent(); for (int i = 0; i < list.size(); i++) { row = sheet.createRow((int) i + 1); Info info = (Info) list.get(i); // 第四步,创建单元格,并设置值 row .createCell((short) 0) .setCellValue(i+1); row .createCell((short) 1) .setCellValue(info.getCompanyName().replaceAll("\\s*", "")); row .createCell((short) 2) .setCellValue(info.getUserInfo()); row .createCell((short) 3) .setCellValue(info.getHost()); if (null != info.getCreateTime() ){ cell = row.createCell((short) 4); cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(info.getCreateTime()) ); } } // 第六步,将文件存到指定位置 try { long startTime = System.currentTimeMillis(); logger.info("*****开始进行导出文件*****"); FileOutputStream fout = new FileOutputStream(FILE_NAME_PATH); wb.write(fout); fout.close(); long ennTime = System.currentTimeMillis(); logger.info(FILE_NAME_PATH + " 文件导出成功,共耗时:"+ (double)(ennTime-startTime)/1000); } catch (IOException e) { e.printStackTrace(); logger.error("文件导出出现异常 "+e.getMessage()); } } }
[ "520520cmq" ]
520520cmq
a7e7e484fcc3341dd77ffb7b6d8e695b88206363
d7f9e9d8a161c9c155516de4030547d21103330a
/src/main/java/cl/moena/comanda/Model/Producto.java
fb89ba545a5ab39c313253214e4e19ac3693f660
[]
no_license
oswmoena/comanda
75a4aa02def9691b119eef95459587e768892e41
80f3d929ef573da7e1fb151f3ee1c13ca4a11741
refs/heads/master
2021-01-26T08:59:22.102740
2020-03-02T03:04:31
2020-03-02T03:04:31
243,392,313
0
0
null
null
null
null
UTF-8
Java
false
false
2,284
java
package cl.moena.comanda.Model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @Entity @Table(name="producto") public class Producto { @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } @Id @SequenceGenerator(name = "sec_producto", sequenceName = "sec_producto", allocationSize = 1) @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "producto") private Integer id; @Column (name = "nombre", length = 200) private String nombre; @Column (name = "precio") private Integer precio; @Column (name = "detalle", columnDefinition = "text") private String detalle; @Column (name= "vigencia") private Boolean vigencia; @OneToOne(targetEntity = Tipo.class ) @JoinColumn(name = "id_tipo", referencedColumnName = "id", insertable = true, updatable = true) private Tipo idTipo; @OneToOne(targetEntity = Estado.class ) @JoinColumn(name = "id_estado", referencedColumnName = "id", insertable = true, updatable = true) private Estado idEstado; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Integer getPrecio() { return precio; } public void setPrecio(Integer precio) { this.precio = precio; } public Boolean getVigencia() { return vigencia; } public void setVigencia(Boolean vigencia) { this.vigencia = vigencia; } public Tipo getIdTipo() { return idTipo; } public void setIdTipo(Tipo idTipo) { this.idTipo = idTipo; } public String getDetalle() { return detalle; } public void setDetalle(String detalle) { this.detalle = detalle; } public Estado getIdEstado() { return idEstado; } public void setIdEstado(Estado idEstado) { this.idEstado = idEstado; } }
[ "oswmoena@gmail.com" ]
oswmoena@gmail.com
3a10fc7e3d3908c81349a280b083099287a51895
bc53aecdbb40d389f563f76f8a706d61d0a4b380
/source/SQLParserDemo/src/test/formatsql/testCompactMode.java
7c85c2b020d054e7d43d9b3770022c0cd26f7768
[ "MIT" ]
permissive
kyryl-bogach/sql-jpql-compiler
f0d5462945199e879d68a409969043d4e76e0ffd
03a9f11bcd68651e22bc36a4ac587fb2b474266a
refs/heads/master
2023-03-03T14:16:18.442644
2021-02-11T19:11:41
2021-02-11T19:11:41
159,367,377
0
0
null
null
null
null
UTF-8
Java
false
false
1,585
java
package test.formatsql; /* * Date: 11-3-23 */ import gudusoft.gsqlparser.EDbVendor; import gudusoft.gsqlparser.TGSqlParser; import gudusoft.gsqlparser.pp.para.GFmtOpt; import gudusoft.gsqlparser.pp.para.GFmtOptFactory; import gudusoft.gsqlparser.pp.para.styleenums.TCompactMode; import gudusoft.gsqlparser.pp.stmtformatter.FormatterFactory; import junit.framework.TestCase; public class testCompactMode extends TestCase { /** * turn sql into a single line, or multiple lines with a fixed line width * no need to format this sql * be careful when there are single line comment in SQL statement. */ public static void testSingleLine(){ GFmtOpt option = GFmtOptFactory.newInstance(new Exception().getStackTrace()[0].getClassName() + "." + new Exception().getStackTrace()[0].getMethodName()); TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvmssql); sqlparser.sqltext = "select department_id,\n" + " min( salary ) -- single line comment \n" + "from employees \n" + "group by department_id"; sqlparser.parse(); option.compactMode = TCompactMode.Cpmugly; option.lineWidth = 60; String result = FormatterFactory.pp(sqlparser, option); assertTrue(result.trim().equalsIgnoreCase("SELECT department_id, Min( salary ) \n" + "/* -- single line comment */ FROM employees GROUP BY \n" + "department_id")); //System.out.println(result); } }
[ "kyryl.bogachy@um.es" ]
kyryl.bogachy@um.es
8fb1997e5f8c7335e3600b8e433de493024ea213
f5f3813f503545184e8c6f16ccb740254a1e9019
/Backend/licorstore/src/main/java/com/aglayatech/licorstore/service/impl/MarcaProductoServiceImpl.java
0f7266d387dbf50e1b9949a550619dd80dbd4ddf
[]
no_license
eduardo19Fu/new-dimsa
99574d46277186d4c4b7736f97afac89a34b8b41
74abf00674eff017ecc6abc35b6de67effdc1260
refs/heads/main
2023-08-29T12:11:12.091667
2021-10-25T13:57:21
2021-10-25T13:57:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,418
java
package com.aglayatech.licorstore.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; import com.aglayatech.licorstore.model.MarcaProducto; import com.aglayatech.licorstore.repository.IMarcaProductoRepository; import com.aglayatech.licorstore.service.IMarcaProductoService; @Service public class MarcaProductoServiceImpl implements IMarcaProductoService { @Autowired private IMarcaProductoRepository marcaProductoRepo; @Override public List<MarcaProducto> findAll() { return marcaProductoRepo.findAll(Sort.by(Direction.ASC, "idMarcaProducto")); } @Override public Page<MarcaProducto> findAll(Pageable pageable) { return marcaProductoRepo.findAll(pageable); } @Override public MarcaProducto findById(Integer idMarca) { return marcaProductoRepo.findById(idMarca).orElse(null); } @Override public List<MarcaProducto> findByMarca(String marca) { return marcaProductoRepo.findByMarca(marca); } @Override public MarcaProducto save(MarcaProducto marca) { return marcaProductoRepo.save(marca); } @Override public void deleteMarca(Integer idMarca) { marcaProductoRepo.deleteById(idMarca); } }
[ "ramieduar@gmail.com" ]
ramieduar@gmail.com
a9937ecee27483e8d88068d5e20981ca3fdaed1b
6e977faca828f6a95980a9adda5dbb8de442cbdb
/app/src/main/java/com/example/maxuejun/firstapptest/model/BaseModel.java
eac54a4e139c3c2013f1cb22e255229de47f9aff
[]
no_license
maxuejun/FirstAppTest
b119a050046a46736e05e66ffa7b802a20b19782
182b57506899dab2365c73c1997bf49f74c54d2c
refs/heads/master
2021-01-10T07:29:42.372336
2016-09-07T08:55:22
2016-09-07T08:55:22
51,975,638
0
0
null
null
null
null
UTF-8
Java
false
false
187
java
package com.example.maxuejun.firstapptest.model; import java.io.Serializable; /** * Created by Administrator on 16-8-11. */ public abstract class BaseModel implements Serializable{ }
[ "maxuejun2014@gmail.com" ]
maxuejun2014@gmail.com
0e872f4b60e1dcdaff155cdac9ea047441fc4b29
bfb416f92de47a7d3a4238ad0498b29b01d38511
/akka-project/src/main/java/com/gof/akka/operators/SplitOperator.java
2281c9108bd7c0a26ea2c4acc57e2bf4fd1c1c03
[ "Apache-2.0" ]
permissive
tmscarla/akka-big-data
88cb9ec79e5423a2be94dfb0ce50fb4cba50b5e5
ffda629db69b65879076da514a5cc40d2f1c02fd
refs/heads/master
2023-02-21T21:51:00.924589
2023-02-20T14:29:42
2023-02-20T14:29:42
171,008,152
12
1
Apache-2.0
2023-02-20T14:29:44
2019-02-16T13:42:15
Java
UTF-8
Java
false
false
290
java
package com.gof.akka.operators; public class SplitOperator extends Operator { public SplitOperator(String name, int batchSize) { super(name, batchSize); } @Override public SplitOperator clone(){ return new SplitOperator(this.name, this.batchSize); } }
[ "scarlattitommaso@gmail.com" ]
scarlattitommaso@gmail.com
7d8ebc205e503dcf671d096456ce0f5b393a8d5a
ffbf6ca8b1809179aa03dae3e2fa1b139a05ebc5
/app/src/main/java/jc/sky/display/SKYIDisplay.java
677416aa32480f8743f6b5d752e7527906c16c27
[]
no_license
menteelin/sky
29982fea6ee2dfaa1a51f17cd03eb62a873903b1
f4fbccd06338cb11632af260963ac77062530144
refs/heads/master
2021-06-12T02:07:01.832571
2017-01-12T10:50:14
2017-01-12T10:50:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,876
java
package jc.sky.display; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.AnimRes; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.view.View; import org.jetbrains.annotations.NotNull; import jc.sky.core.Impl; /** * @author sky * @version 版本 */ @Impl(SKYDisplay.class) public interface SKYIDisplay { /** * 获取上下文 * * @return 返回值 */ Context context(); /** * @param <T> * 参数 * @return 返回值 */ <T extends FragmentActivity> T activity(); /** * 跳转 * * @param clazz * 参数 * @param fragment * 参数 * @param requestCode * 参数 */ void intentFromFragment(@NotNull Class clazz, @NotNull Fragment fragment, int requestCode); /** * 跳转 * * @param intent * 参数 * @param fragment * 参数 * @param requestCode * 参数 */ void intentFromFragment(@NotNull Intent intent, @NotNull Fragment fragment, int requestCode); /** * home键 */ void onKeyHome(); /** * */ void popBackStack(); /** * @param clazz * 参数 */ void popBackStack(@NotNull Class clazz); /** * @param clazzName * 参数 */ void popBackStack(@NotNull String clazzName); /** * */ void popBackStackAll(); /** * @param fragment * 参数 */ void commitAdd(@NotNull Fragment fragment); /** * @param layoutId * 参数 * @param fragment * 参数 */ void commitAdd(@IdRes int layoutId, @NotNull Fragment fragment); /** * @param fragment * 参数 */ void commitReplace(@NotNull Fragment fragment); /** * @param srcFragment * 参数 * @param layoutId * 参数 * @param fragment * 参数 */ void commitChildReplace(@NotNull Fragment srcFragment, @IdRes int layoutId, @NotNull Fragment fragment); /** * @param layoutId * 参数 * @param fragment * 参数 */ void commitReplace(@IdRes int layoutId, @NotNull Fragment fragment); /** * @param fragment * 参数 */ void commitBackStack(@NotNull Fragment fragment); /** * @param srcFragment * 参数 * @param fragment * 参数 */ void commitHideAndBackStack(@NotNull Fragment srcFragment, @NotNull Fragment fragment); /** * @param srcFragment * 参数 * @param fragment * 参数 */ void commitDetachAndBackStack(@NotNull Fragment srcFragment, @NotNull Fragment fragment); /** * @param layoutId * 参数 * @param fragment * 参数 */ void commitBackStack(@IdRes int layoutId, @NotNull Fragment fragment); /** * @param layoutId * 参数 * @param fragment * 参数 * @param animation * 参数 */ void commitBackStack(@IdRes int layoutId, @NotNull Fragment fragment, int animation); /** * 跳转intent * * @param clazz * 参数 **/ void intent(@NotNull Class clazz); /** * @param clazzName * 参数 */ void intent(@NotNull String clazzName); /** * @param clazz * 参数 */ void intentNotAnimation(@NotNull Class clazz); /** * @param clazz * 参数 * @param bundle * 参数 */ void intent(@NotNull Class clazz, Bundle bundle); /** * @param clazz * 参数 * @param bundle * 参数 */ void intentNotAnimation(@NotNull Class clazz, @NotNull Bundle bundle); /** * @param intent * 参数 */ void intent(@NotNull Intent intent); /** * @param intent * 参数 * @param options * 参数 */ void intent(@NotNull Intent intent, @NotNull Bundle options); /** * @param clazz * 参数 * @param requestCode * 参数 */ void intentForResult(@NotNull Class clazz, int requestCode); /** * @param clazz * 参数 * @param bundle * 参数 * @param requestCode * 参数 * @param fragment * 参数 */ void intentForResultFromFragment(@NotNull Class clazz, Bundle bundle, int requestCode, @NotNull Fragment fragment); /** * @param clazz * 参数 * @param bundle * 参数 * @param requestCode * 参数 */ void intentForResult(@NotNull Class clazz, @NotNull Bundle bundle, int requestCode); /** * @param intent * 参数 * @param requestCod * 参数 */ void intentForResult(@NotNull Intent intent, int requestCod); /** * @param intent * 参数 * @param options * 参数 * @param requestCode * 参数 */ void intentForResult(@NotNull Intent intent, @NotNull Bundle options, int requestCode); /** * @param clazz * 参数 * @param view * 参数 * @param bundle * 参数 */ void intentAnimation(@NotNull Class clazz, @NotNull View view, Bundle bundle); /** * @param clazz * 参数 * @param in * 参数 * @param out * 参数 */ void intentAnimation(@NotNull Class clazz, @AnimRes int in, @AnimRes int out); /** * @param clazz * 参数 * @param in * 参数 * @param out * 参数 * @param bundle * 参数 */ void intentAnimation(@NotNull Class clazz, @AnimRes int in, @AnimRes int out, @NonNull Bundle bundle); /** * @param clazz * 参数 * @param view * 参数 * @param requestCode * 参数 */ void intentForResultAnimation(@NotNull Class clazz, @NotNull View view, int requestCode); /** * @param clazz * 参数 * @param view * 参数 * @param bundle * 参数 * @param requestCode * 参数 */ void intentForResultAnimation(@NotNull Class clazz, @NotNull View view, @NotNull Bundle bundle, int requestCode); /** * @param clazz * 参数 * @param in * 参数 * @param out * 参数 * @param requestCode * 参数 */ void intentForResultAnimation(@NotNull Class clazz, @AnimRes int in, @AnimRes int out, int requestCode); /** * @param clazz * 参数 * @param in * 参数 * @param out * 参数 * @param bundle * 参数 * @param requestCode * 参数 */ void intentForResultAnimation(@NotNull Class clazz, @AnimRes int in, @AnimRes int out, @NonNull Bundle bundle, int requestCode); }
[ "jincan0213@hotmail.com" ]
jincan0213@hotmail.com
e1b421f0996386fc133177d5860d7d18cfd3ed60
af4bb16152a7082f5ac83cb53145d0e8d9d12c7f
/MVC/flower/src/com/lc/servlet/InsertServlet.java
c3c14c0b2270446131f2507b5ee0f933d06d4496
[]
no_license
Ticsmyc/Java-Learning
c001209ea8ef48ee68128fe95fae850281f4e94b
c81e6b804021e5ab634bfd1d7e4ae9577f52fdb2
refs/heads/master
2020-06-14T17:45:45.331511
2019-12-19T09:00:22
2019-12-19T09:00:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,071
java
package com.lc.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lc.pojo.Flower; import com.lc.service.FlowerService; import com.lc.service.impl.FlowerServiceImpl; @WebServlet("/insert") public class InsertServlet extends HttpServlet{ private FlowerService flowerService = new FlowerServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); String name =req.getParameter("name"); String price = req.getParameter("price"); String production =req.getParameter("production"); int index = flowerService.add(new Flower(0,name,Double.parseDouble(price),production)); if(index>0) { resp.sendRedirect("show"); }else { resp.sendRedirect("add.jsp"); } } }
[ "liu0148@outlook.com" ]
liu0148@outlook.com
9b7072b84646cf02b5d0f6cb33633db83d40a201
462379c1d591773ba232a77398020270a73fb7bb
/A2/Q3/RemoteInterface.java
e100963b7b327671d9ad41b8f98e036e5c66f2e2
[]
no_license
RickMConstantine/Distributed-Computing-COMP3010
28908c3bea6a8e964af3096777631830938d9dd9
108f7cb278f96841eb3d535d1a4a2992eceda1ca
refs/heads/master
2020-07-31T20:38:23.651410
2019-09-25T04:27:18
2019-09-25T04:27:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
500
java
import java.rmi.Remote; import java.rmi.RemoteException; public interface RemoteInterface extends Remote { String welcomeMessage() throws RemoteException; String createAccount(int acctNumber) throws RemoteException; String retrieveBalance(int acctNumber) throws RemoteException; String depositAmount(int acctNumber, int amount) throws RemoteException; String withdrawAmount(int acctNumber, int amount) throws RemoteException; String accountSummary() throws RemoteException; }
[ "rickmaelikconstantine@live.com" ]
rickmaelikconstantine@live.com
74f3b3cdbaa0caad1c98913a126adbae47e3eeb3
3f3549cb6b69555884337cb6cd03c359a8a51413
/app/src/test/java/com/tech4use/texttospeech/ExampleUnitTest.java
0c0bd696bbc4ea8cd0a42fba6cdd6990c6daed3a
[]
no_license
harshbarnwal/TextToSpeech
bee6c94b1d075d78b1c078b42de9d6ca76ed600d
3033c2281560c3bdcbabd8a0efc0dc04d3b08861
refs/heads/master
2020-05-18T17:42:25.370192
2019-05-02T10:43:52
2019-05-02T10:43:52
184,563,550
0
0
null
null
null
null
UTF-8
Java
false
false
386
java
package com.tech4use.texttospeech; 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); } }
[ "harshbarnwal@users.noreply.github.com" ]
harshbarnwal@users.noreply.github.com
f211b1d95c2690d66c53b94fd7bd1f5934de3ca7
8967bcc767cea2fc2feaaebc818654ecde33b23c
/src/main/java/com/stefan/combination/combinationapplication/algorithm/search/SearchAlgorithm.java
f906f9bc0d9cec88c4579712df9b029cb4caf3f6
[]
no_license
Stef-risk/Combination-of-SpringAOP-Jdbc-H2-JUnit-Mockito
0ec08843849e29971e33ee08124152f547e6187c
88e13a9532f36c10d15fea1b9769a80195d555c3
refs/heads/master
2023-07-06T15:18:49.367081
2021-08-11T04:06:13
2021-08-11T04:06:13
394,649,930
2
0
null
null
null
null
UTF-8
Java
false
false
157
java
package com.stefan.combination.combinationapplication.algorithm.search; public interface SearchAlgorithm { int search(int[] nums,int numberToSearch); }
[ "stefrisk3@gmail.com" ]
stefrisk3@gmail.com
a2c58a6f377c12d312df6fdcc5e6a1495aadfba1
e290601b463b7edc3723fcf010ec38047751e3b9
/05 - Abstract Factory/Lab05_00_AbstractFactory/src/PizzaAF/CheesePizza.java
5f3af1f580059cde1dcd10c24f07b900ac43a584
[]
no_license
kelvng/Design-Patterns
f5ba7517a97506f47952fb537d8bad9ac0bf8002
e509cc2732e16133e2191ec7131cb1b3f3daac90
refs/heads/main
2023-08-25T16:19:20.174092
2021-10-20T12:20:46
2021-10-20T12:20:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package PizzaAF; public class CheesePizza extends Pizza { PizzaIngredientFactory ingredientFactory; public CheesePizza(PizzaIngredientFactory ingredientFactory) { this.ingredientFactory = ingredientFactory; } void prepare() { System.out.println("Preparing " + name); dough = ingredientFactory.createDough(); sauce = ingredientFactory.createSauce(); cheese = ingredientFactory.createCheese(); } }
[ "nthanhkhang@outlook.com" ]
nthanhkhang@outlook.com
60a467ec9a2459dbd9deaa522762042c5471731b
814acdbdff8d065d336af7956f024f9f2d296632
/src/main/java/com/wosai/generate/plugin/MysqlPaginationPlugin.java
8bac283dcde22fd7e40afe18e311c40e47192951
[]
no_license
hugezhou/gc
e91390b083d4f1ab1e767f40990915392da2c469
b153e527f70fd186ff32a74f66b4ca6f8bea389f
refs/heads/master
2023-01-18T23:41:44.286499
2020-10-30T08:52:39
2020-10-30T08:52:39
308,569,531
0
0
null
null
null
null
UTF-8
Java
false
false
4,129
java
package com.wosai.generate.plugin; import java.util.List; import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.ShellRunner; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Parameter; import org.mybatis.generator.api.dom.java.TopLevelClass; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; /** * <pre> * mysql分页插件 */ public class MysqlPaginationPlugin extends PluginAdapter { @Override public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // add field, getter, setter for limit clause addLimit(topLevelClass, introspectedTable, "limitStart"); addLimit(topLevelClass, introspectedTable, "limitEnd"); return super.modelExampleClassGenerated(topLevelClass, introspectedTable); } @Override public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated( XmlElement element, IntrospectedTable introspectedTable) { XmlElement isParameterPresenteElemen = (XmlElement) element.getElements().get(element.getElements().size() - 1); XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$ isNotNullElement.addAttribute(new Attribute("test", "limitStart > -1")); isNotNullElement.addElement(new TextElement("limit ${limitStart} , ${limitEnd}")); isParameterPresenteElemen.addElement(isNotNullElement); return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable); } private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, String name) { CommentGenerator commentGenerator = context.getCommentGenerator(); Field field = new Field(); field.setVisibility(JavaVisibility.PROTECTED); field.setType(FullyQualifiedJavaType.getIntInstance()); field.setName(name); field.setInitializationString("-1"); commentGenerator.addFieldComment(field, introspectedTable); topLevelClass.addField(field); char c = name.charAt(0); String camel = Character.toUpperCase(c) + name.substring(1); Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.setName("set" + camel); method.addParameter(new Parameter(FullyQualifiedJavaType .getIntInstance(), name)); method.addBodyLine("this." + name + "=" + name + ";"); commentGenerator.addGeneralMethodComment(method, introspectedTable); topLevelClass.addMethod(method); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.setReturnType(FullyQualifiedJavaType.getIntInstance()); method.setName("get" + camel); method.addBodyLine("return " + name + ";"); commentGenerator.addGeneralMethodComment(method, introspectedTable); topLevelClass.addMethod(method); } /** * This plugin is always valid - no properties are required */ public boolean validate(List<String> warnings) { return true; } public static void generate() { String config = MysqlPaginationPlugin.class.getClassLoader().getResource( "mybatisConfig.xml").getFile(); String[] arg = { "-configfile", config, "-overwrite" }; ShellRunner.main(arg); } public static void main(String[] args) { generate(); } }
[ "804331017@qq.com" ]
804331017@qq.com
b7653f7f1f2757bb87a85f484ef42c6c5cd6006d
0ceaa1917e2a514a437920fb2545d395378367ca
/src/main/java/io/backpackr/api/backpackrapi/domain/member/dto/MemberJoinDto.java
39cab41212ed7a7f4ed719c3035b5086a34822c6
[]
no_license
goslim56/backpackr-api
71770fcfcdb8a37aaf1e15dffc921a27fd94e8cf
382d13dc68dff804c1721629bfb49c7a470b8d13
refs/heads/master
2023-09-02T12:20:48.206857
2021-11-21T11:56:50
2021-11-21T11:56:50
430,352,713
0
0
null
null
null
null
UTF-8
Java
false
false
1,555
java
package io.backpackr.api.backpackrapi.domain.member.dto; import io.backpackr.api.backpackrapi.domain.member.Member; import lombok.Getter; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; @Getter public class MemberJoinDto { @NotEmpty(message = "name(이름)은 필수값입니다.") @Size(max = 20, message = "password(패스워드)는 최소 10자리 이상 일력하세요.") @Pattern(regexp = "[a-zA-Z가-힣]", message = "이름(name)은 한글, 영문 대소문자만 허용합니다.") private String name; @NotEmpty(message = "nickname(별명)은 필수값입니다.") private String nickname; @NotEmpty(message = "password(패스워드)는 필수값입니다.") @Size(min = 10, message = "password(패스워드)는 최소 10자리 이상 일력하세요.") private String password; @NotEmpty(message = "phone(전화번호)는 필수값입니다.") private String phone; @NotEmpty(message = "email 은 필수값입니다.") @Email(message = "email 형식에 맞지않습니다 (ex: example@google.com)") private String email; private String gender; public Member converter() { return Member.builder() .name(this.name) .nickname(this.nickname) .password(this.password) .phone(this.phone) .email(this.email) .gender(this.gender).build(); } }
[ "goslim@MacBook.local" ]
goslim@MacBook.local
8bf1e33b72788a45a7abbd9a35316779e9f696eb
ac1e1f3b63804dad3678fab3fbe70b97aed6f5f8
/src/icrs/InsertForm.java
e74ce8d596dd8911bc8fccb8af2d3e8ae2ec5cd3
[]
no_license
rizaldihz/PPL_FP
fab2a4bf0d241f380e90bd6ed7ceab93d75c9a7b
ef33dfec2a8ed2c2630bcaeeafb938c13950e44f
refs/heads/master
2020-09-23T13:58:45.328297
2019-12-16T23:36:24
2019-12-16T23:36:24
225,516,598
0
0
null
null
null
null
UTF-8
Java
false
false
12,897
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 icrs; /** * * @author rizaldi */ import java.sql.*; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.JFrame; public class InsertForm extends javax.swing.JFrame { /** * Creates new form InsertForm */ public InsertForm() { initComponents(); List<String> authors = InsertPageControl.getAuthors(); System.err.println(authors); penulisSelect.setModel(new DefaultComboBoxModel<String>(authors.toArray(new String[0]))); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); progressBar.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); judulField = new javax.swing.JTextField(); keywordField = new javax.swing.JTextField(); tahunField = new javax.swing.JTextField(); abstrakField = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); refField = new javax.swing.JTextField(); submit = new javax.swing.JButton(); penulisSelect = new javax.swing.JComboBox<>(); progressBar = new javax.swing.JProgressBar(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Insert Metada Form"); jLabel2.setText("Judul"); jLabel3.setText("Penulis"); jLabel4.setText("Keyword"); jLabel5.setText("Abstraksi"); jLabel6.setText("Tahun Publikasi"); judulField.setToolTipText("Judul Artikel"); keywordField.setToolTipText("Keyword Artikel"); tahunField.setToolTipText("Tahun Publikasi"); abstrakField.setToolTipText("Penulis Artikel"); jLabel7.setText("Referensi"); refField.setToolTipText("Penulis Artikel"); submit.setText("Submit"); submit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitActionPerformed(evt); } }); penulisSelect.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(keywordField, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tahunField, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(abstrakField, javax.swing.GroupLayout.PREFERRED_SIZE, 466, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(judulField, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(penulisSelect, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(297, 297, 297)))) .addGroup(layout.createSequentialGroup() .addGap(184, 184, 184) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(refField, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(120, 120, 120) .addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(55, Short.MAX_VALUE)) .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(judulField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(keywordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel6) .addComponent(tahunField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(penulisSelect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(abstrakField, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(refField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(submit)) .addContainerGap(67, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed String nama = judulField.getText(); String keyword = keywordField.getText(); String tahun = tahunField.getText(); String penulis = penulisSelect.getItemAt(penulisSelect.getSelectedIndex()); String reference = refField.getText(); String abstrak = abstrakField.getText(); int submit; submit = InsertPageControl.insertArtikel(nama,tahun,keyword,penulis,abstrak,reference, this); }//GEN-LAST:event_submitActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InsertForm().setVisible(true); } }); } public void setProgress(int i) { progressBar.setValue(i); } public void showProgress(boolean i) { progressBar.setVisible(i); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField abstrakField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JTextField judulField; private javax.swing.JTextField keywordField; private javax.swing.JComboBox<String> penulisSelect; private javax.swing.JProgressBar progressBar; private javax.swing.JTextField refField; private javax.swing.JButton submit; private javax.swing.JTextField tahunField; // End of variables declaration//GEN-END:variables }
[ "rizaldihz@users.noreply.github.com" ]
rizaldihz@users.noreply.github.com
eee0d4e4c725d7d9045d5b7a6f335c64eafa65ee
e7202556332ee036a5860212c590dee9896b5bf2
/app/src/main/java/com/donatenaccept/dna/MainActivity.java
c03bc1b5fff40f37e2a659b0fedb53e4cf9a720c
[]
no_license
abhilucks93Personal/DonateNAccept
6ba7ea1f88d154a3e2f3cecffed4b3cd3ce010fa
46f58ec20ab71f9c57dd3e9826988766e5f15de7
refs/heads/master
2021-01-19T19:40:39.691229
2017-09-14T03:44:41
2017-09-14T03:44:41
101,200,949
0
0
null
null
null
null
UTF-8
Java
false
false
334
java
package com.donatenaccept.dna; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "abhishek.wildnettech@gmail.com" ]
abhishek.wildnettech@gmail.com
310d3d42e869b3ea9175041fcfe8987e1e82e309
a19c129ec67e8c77f45806356032246d4cde87c6
/Module3/HotTargui-ProgProj-F08-PeerToPeer/src/hottargui/framework/RoundObserver.java
074ea04ae1b1be7991fb6ddea3ece7d6c5eb6d0d
[]
no_license
ahpoder/pasoos2007hbc
cb86204521292fa0f43661eea9a9e3a1515b11f1
7d6e91d68ad720c58b55ba439f07e7a225df21da
refs/heads/master
2021-01-22T18:18:38.518056
2008-05-29T20:43:41
2008-05-29T20:43:41
33,121,113
0
0
null
null
null
null
UTF-8
Java
false
false
88
java
package hottargui.framework; public interface RoundObserver { void roundDone(); }
[ "ahpoder@cd5ad199-9c3d-0410-9d3f-bdd6d08f3b64" ]
ahpoder@cd5ad199-9c3d-0410-9d3f-bdd6d08f3b64
7de82d8fc452b8f3643e0fb78e35b0c436c318f8
a367e5639006093cddf198fe761f598d84a86e06
/VINA-VIDAI/SOURCE/JAVA/org/ahp/core/managers/IAhpMessageResourceManager.java
2de906575afa20318a231106b50ba5ed4270b079
[ "Apache-2.0" ]
permissive
shankarkarthik/Arima
b16df749915c5a785a6f2eaa5d34151e1079edc7
5bdc606f498dd446c716dab901a372c8ed9eefa2
refs/heads/master
2023-04-08T02:07:27.573821
2023-03-24T01:22:56
2023-03-24T01:22:56
3,880,464
0
0
null
null
null
null
UTF-8
Java
false
false
598
java
package org.ahp.core.managers; import org.ahp.core.exceptions.AhpExceptionCodes; /** * * @author Shankar Karthik Vaithianathan * */ public interface IAhpMessageResourceManager extends IAhpManagerLifecycle { public String getMessage( AhpExceptionCodes pExceptionCode, Object[] pMessageArguments, String pResourceName ); public String getMessage( AhpExceptionCodes pExceptionCode, Object[] pMessageArguments ); public String getMessage( AhpExceptionCodes pExceptionCode ); public String getMessage( AhpExceptionCodes pExceptionCode, String pResourceName ); }
[ "shankar.karthik@gmail.com" ]
shankar.karthik@gmail.com
ccb4be71208bb6eac7cf3f0371a4eb0112b92271
9d96232fad88a724290acc60886442693ef3e24f
/src/main/java/tech/getarrays/employeemanager/model/Employee.java
3ab5b567edb28521c9233e8efd9981447e2a7606
[]
no_license
abhishek14k/Employee-Manager-SpringBoot-backend-
316fa6db32cf538c75b275289c3bcaa50ae4100c
4ef36231c8a675d774cecbeb095f325ab5f62e33
refs/heads/master
2023-05-04T14:45:49.113971
2021-05-16T18:21:40
2021-05-16T18:21:40
367,955,373
1
0
null
null
null
null
UTF-8
Java
false
false
2,140
java
package tech.getarrays.employeemanager.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(nullable = false, updatable = false) private Long id; private String name; private String email; private String jobTitle; private String phone; private String imageUrl; @Column(nullable = false, updatable = false) private String employeeCode; public Employee() { super(); } public Employee(Long id, String name, String email, String jobTitle, String phone, String imageUrl, String employeeCode) { this.id = id; this.name = name; this.email = email; this.jobTitle = jobTitle; this.phone = phone; this.imageUrl = imageUrl; this.employeeCode = employeeCode; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getEmployeeCode() { return employeeCode; } public void setEmployeeCode(String employeeCode) { this.employeeCode = employeeCode; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", email=" + email + ", jobTitle=" + jobTitle + ", phone=" + phone + ", imageUrl=" + imageUrl + ", employeeCode=" + employeeCode + "]"; } }
[ "abhishekramakrishna1995@gmail.com" ]
abhishekramakrishna1995@gmail.com
8746909873a38910220499571c42d169acbcfb9f
d68b23f38afb03c3d9148be0305bbee63655bf94
/Reversing a String.java
738dce23549e38097d1a740d1b9145ace338b1af
[]
no_license
VarunNNayak/JavaPractices
f8f3b4b950a92e3a6321921c6f2bf102400c2be5
ae32fa16d624eebac7cad3141fae73962695c1ca
refs/heads/main
2023-03-25T19:14:57.097623
2021-03-15T10:00:03
2021-03-15T10:00:03
339,054,958
0
0
null
null
null
null
UTF-8
Java
false
false
678
java
public class Reverse { public static void main(String[] args) { String string = "Dream big"; //Stores the reverse of given string String reversedStr = ""; //Iterate through the string from last and add each character to variable reversedStr for(int i = string.length()-1; i >= 0; i--){ reversedStr = reversedStr + string.charAt(i); } System.out.println("Original string: " + string); //Displays the reverse of given string System.out.println("Reverse of given string: " + reversedStr); } }
[ "noreply@github.com" ]
noreply@github.com
7c73504e68bbe4dcc651ad63d4290fb1b47eb05e
75950d61f2e7517f3fe4c32f0109b203d41466bf
/modules/branches/1.9.5-SNAPSHOT-spring/extension/other/databinding/fabric3-databinding-json/src/main/java/org/fabric3/databinding/json/transform/Object2StringJsonTransformer.java
5fbc9fc454c41c4ae66c4be593e1816cf8aa6e83
[]
no_license
codehaus/fabric3
3677d558dca066fb58845db5b0ad73d951acf880
491ff9ddaff6cb47cbb4452e4ddbf715314cd340
refs/heads/master
2023-07-20T00:34:33.992727
2012-10-31T16:32:19
2012-10-31T16:32:19
36,338,853
0
0
null
null
null
null
UTF-8
Java
false
false
3,703
java
/* * Fabric3 * Copyright (c) 2009-2012 Metaform Systems * * Fabric3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version, with the * following exception: * * Linking this software statically or dynamically with other * modules is making a combined work based on this software. * Thus, the terms and conditions of the GNU General Public * License cover the whole combination. * * As a special exception, the copyright holders of this software * give you permission to link this software with independent * modules to produce an executable, regardless of the license * terms of these independent modules, and to copy and distribute * the resulting executable under terms of your choice, provided * that you also meet, for each linked independent module, the * terms and conditions of the license of that module. An * independent module is a module which is not derived from or * based on this software. If you modify this software, you may * extend this exception to your version of the software, but * you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. * * Fabric3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the * GNU General Public License along with Fabric3. * If not, see <http://www.gnu.org/licenses/>. * * --- Original Apache License --- * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.fabric3.databinding.json.transform; import java.io.IOException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.fabric3.spi.transform.TransformationException; import org.fabric3.spi.transform.Transformer; /** * Transforms a Java object to a serialized JSON String. * * @version $Rev: 7714 $ $Date: 2009-09-29 10:24:45 +0200 (Tue, 29 Sep 2009) $ */ public class Object2StringJsonTransformer implements Transformer<Object, String> { private ObjectMapper mapper; public Object2StringJsonTransformer(ObjectMapper mapper) { this.mapper = mapper; } public String transform(Object source, ClassLoader loader) throws TransformationException { try { return mapper.writeValueAsString(source); } catch (JsonMappingException e) { throw new TransformationException(e); } catch (JsonParseException e) { throw new TransformationException(e); } catch (IOException e) { throw new TransformationException(e); } } }
[ "palmalcheg@83866bfc-822f-0410-aa35-bd5043b85eaf" ]
palmalcheg@83866bfc-822f-0410-aa35-bd5043b85eaf
a2777944d434278f71750fb730d7abdef0a84bab
4d38f89105f30d5aed3f6da303c4fa8c3ce9e724
/ServerCore/src/main/java/com/db/server/transactions/MyJpaTransactionManager.java
0724bd13409b48406814eacfac3b20e12af559d7
[]
no_license
tymiles003/DroneServer
9c4a6ee5418bfc36e60de73f2b311d3fba0e15f2
b1ad3f92cedc07fedec659c4823423f60f034b40
refs/heads/master
2021-09-22T16:32:43.324858
2018-03-10T19:14:48
2018-03-10T19:15:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,464
java
package com.db.server.transactions; import org.apache.log4j.Logger; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.DefaultTransactionStatus; import java.util.Map; public class MyJpaTransactionManager extends JpaTransactionManager { private final static Logger LOGGER = Logger.getLogger(MyJpaTransactionManager.class); static int itr; public MyJpaTransactionManager() { itr++; // LOGGER.debug("Creation " + itr); } @Override public Map<String, Object> getJpaPropertyMap() { Map<String, Object> mapper = super.getJpaPropertyMap(); for (Map.Entry<String, Object> entry : mapper.entrySet()) { LOGGER.debug("-> " + entry.getKey() + " " + entry.getValue()); } return mapper; } @Override protected void doBegin(Object transaction, TransactionDefinition definition) { LOGGER.error("DoBegin " + transaction + " " + definition); super.doBegin(transaction, definition); } @Override protected void doCommit(DefaultTransactionStatus status) { LOGGER.error("DoCommit " + status); // getJpaPropertyMap(); super.doCommit(status); } @Override protected void doRollback(DefaultTransactionStatus status) { // LOGGER.debug("DoRollback " + status); super.doRollback(status); } }
[ "taljmars@gmail.com" ]
taljmars@gmail.com
13301b3391fc167b4930558c3e245af300ce449c
e418334dc61bf90547544a7d4e3b67f18154cd15
/Semestralni/src/main/java/cz/com/LevyatonRPGEngine/LevyBuild/Objects/Character/Specie.java
9f07c9e178c6854e8b9bac591081e41ae496fc2c
[]
no_license
Levyaton/Java-Game-Engine-v1
caa665e763b2eb640a655806ec0b76a8023045a5
074db470d528bdc885898b9831c38ce9ab4b5fbe
refs/heads/master
2022-12-30T06:19:27.900785
2020-06-30T13:34:34
2020-06-30T13:34:34
276,096,785
0
0
null
2020-10-13T23:12:04
2020-06-30T12:48:39
Java
UTF-8
Java
false
false
4,243
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 cz.com.LevyatonRPGEngine.LevyBuild.Objects.Character; /** * * @author czech */ import cz.com.LevyatonRPGEngine.LevyBuild.Objects.Item; import cz.com.LevyatonRPGEngine.LevyBuild.Objects.GameObject; import cz.com.LevyatonRPGEngine.LevyBuild.Objects.Attack; public class Specie extends GameObject{ protected int str;//Strength protected int speed; protected Double luck; protected int def;//Defense protected int hp;//Health Points protected Item[] loot; //What loot will be possible protected Attack[] attacks; protected int givenExp; protected int levelAttacks = 1; protected String focus; public Specie(String givenName, int giveStr, int giveSpeed, Double giveLuck, int giveDef, int giveHP, Item[] giveLoot, Attack[] giveAttacks, String giveFocus) { super(givenName); properties(giveStr,giveSpeed,giveLuck,giveDef,giveHP,giveLoot,giveAttacks, giveFocus); } public Specie(String givenName, int giveStr, int giveSpeed, Double giveLuck, int giveDef, int giveHP, Item[] giveLoot, Attack[] giveAttacks, int giveAttackLevel, String giveFocus) { super(givenName); properties(giveStr,giveSpeed,giveLuck,giveDef,giveHP,giveLoot,giveAttacks,giveAttackLevel, giveFocus); } protected void properties(int giveStr, int giveSpeed, Double giveLuck, int giveDef, int giveHP, Item[] giveLoot, Attack[] giveAttacks, String giveFocus) { str = giveStr; speed = giveSpeed; luck = giveLuck; def = giveDef; hp = giveHP; loot = giveLoot; attacks = giveAttacks; givenExp = Math.round(this.str*(this.hp/10 + this.speed/4 + this.def/2)*this.attacks.length); focus = giveFocus; } protected void properties(int giveStr, int giveSpeed, Double giveLuck, int giveDef, int giveHP, Item[] giveLoot, Attack[] giveAttacks, int giveAttackLevel,String giveFocus) { str = giveStr; speed = giveSpeed; luck = giveLuck; def = giveDef; hp = giveHP; loot = giveLoot; attacks = giveAttacks; levelAttacks = giveAttackLevel; setLevels(levelAttacks); givenExp = Math.round(this.str*(this.hp/10 + this.speed/4 + this.def/2)*this.attacks.length); focus = giveFocus; } public String getFocus() { return focus; } private void setLevels(int levelAttacks) { for(Attack attack : attacks) { attack.setLevel(levelAttacks); } } public int getStr() { return str; } public int getSpeed() { return speed; } public Double getLuck() { return luck; } public int getDef() { return def; } public int getHP() { return hp; } public int getExp() { return givenExp; } public Item[] getLoot() { return loot; } public String getStringLoot() { String lootStats = null; for (Item loot1 : loot) { lootStats = lootStats + "Loot name: " + loot1.getName() + " Loot Drop Rate: " + loot1.getDropRate() + " "; } return lootStats; } public Attack[] getAttacks() { return attacks; } public void setLevelOfAttack(Attack chosenAttack, int giveLevel) { int x = 0; boolean exists = false; for(Attack attack : attacks) { if(attack.getName().equals(chosenAttack.getName())) { attacks[x].setLevel(giveLevel); exists = true; } x++; } if(exists == false) { System.out.println("The attack was not found\n"); } } }
[ "czech@DESKTOP-H4O4EDF.mshome.net" ]
czech@DESKTOP-H4O4EDF.mshome.net
47dcc3c41a6d781d6b75727d499d72a19d046a6a
684300b2a57ce3418a13e3f9a4717640044b1ee4
/app/src/main/java/com/xxzlkj/huayiyanglao/adapter/MessageAdapter.java
0a7fc38e092f9e95b2e351c8cebf24bd1aa948c7
[]
no_license
leifeng1991/HYYL
524d12466dca04d72c946ec6c38f3970b998a880
18354d4998ed4f0c27ce7e22d6941b238cb09537
refs/heads/master
2020-04-25T03:12:44.782366
2019-02-25T08:46:08
2019-02-25T08:46:08
172,467,651
0
1
null
null
null
null
UTF-8
Java
false
false
4,780
java
package com.xxzlkj.huayiyanglao.adapter; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.xxzlkj.huayiyanglao.R; import com.xxzlkj.huayiyanglao.config.ZLConstants; import com.xxzlkj.huayiyanglao.util.RongYunUtils; import com.xxzlkj.huayiyanglao.util.ZLUserUtils; import com.xxzlkj.huayiyanglao.weight.ShapeButton; import com.xxzlkj.zhaolinshare.base.base.BaseAdapter; import com.xxzlkj.zhaolinshare.base.base.BaseViewHolder; import com.xxzlkj.zhaolinshare.base.model.User; import com.xxzlkj.zhaolinshare.base.util.PicassoUtils; import com.xxzlkj.zhaolinshare.base.util.UserUtils; import com.xxzlkj.zhaolinshare.chat.TimeUtils; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.MessageContent; import io.rong.message.ImageMessage; import io.rong.message.LocationMessage; import io.rong.message.TextMessage; import io.rong.message.VoiceMessage; /** * 描述: * * @author zhangrq * 2017/9/20 11:25 */ public class MessageAdapter extends BaseAdapter<Conversation> { public MessageAdapter(Context context, int itemId) { super(context, itemId); } @Override public void convert(BaseViewHolder holder, int position, Conversation itemBean) { ImageView mImage = holder.getView(R.id.id_message_image);// 头像 ShapeButton mUnreadMessageCount = holder.getView(R.id.id_unread_message);// 未读消息数量 TextView mTitle = holder.getView(R.id.id_title);// 标题 ShapeButton mRedCircle = holder.getView(R.id.id_red_circle);// 红点 TextView mTime = holder.getView(R.id.id_time);// 时间 TextView mContent = holder.getView(R.id.id_content);// 内容 // 设置头像、用户名 // 设置默认值 mImage.setImageDrawable(null);// 头像 mTitle.setText("");// 用户名 String rongYunTargetId = itemBean.getTargetId(); ZLUserUtils.getUserInfo(UserUtils.getUserID(rongYunTargetId, false), new ZLUserUtils.OnGetUserInfoListener() { @Override public void onSuccess(User bean) { PicassoUtils.setImageSmall(mContext, bean.getData().getSimg(), mImage);// 头像 mTitle.setText(bean.getData().getUsername());// 用户名 } @Override public void onError(int errorCode, String errorMessage) { } }); // 设置时间 mTime.setText(TimeUtils.getMsgFormatTime(itemBean.getSentTime()));// 时间 // 设置内容 MessageContent latestMessage = itemBean.getLatestMessage(); if (latestMessage instanceof TextMessage) { // 文本 String content = ((TextMessage) latestMessage).getContent(); mContent.setText(content);// 内容 } else if (latestMessage instanceof VoiceMessage) { // 声音 mContent.setText("[语音]");// 内容 } else if (latestMessage instanceof ImageMessage) { // 图片 mContent.setText("[图片]");// 内容 } else if (latestMessage instanceof LocationMessage) { // 位置 mContent.setText("[位置]");// 内容 } // 设置消息提示 // 设置默认值 mRedCircle.setVisibility(View.GONE); mUnreadMessageCount.setVisibility(View.GONE); RongYunUtils.getUnreadCount(Conversation.ConversationType.PRIVATE, rongYunTargetId, new RongIMClient.ResultCallback<Integer>() { @Override public void onSuccess(Integer integer) { // 1000:系统消息;1001互动消息 if (ZLConstants.Strings.INTERACTIVE_MESSAGE_ID.equals(rongYunTargetId) || ZLConstants.Strings.SYSTEM_MESSAGE_ID.equals(rongYunTargetId)) { // 特殊的用户 mUnreadMessageCount.setVisibility(View.GONE); mRedCircle.setVisibility(integer > 0 ? View.VISIBLE : View.GONE); } else { // 普通的用户 mRedCircle.setVisibility(View.GONE); if (integer > 0) { mUnreadMessageCount.setVisibility(View.VISIBLE); mUnreadMessageCount.setText(integer > 99 ? "99+" : String.valueOf(integer)); } else { mUnreadMessageCount.setVisibility(View.GONE); } } } @Override public void onError(RongIMClient.ErrorCode errorCode) { mRedCircle.setVisibility(View.GONE); mUnreadMessageCount.setVisibility(View.GONE); } }); } }
[ "15036833790@163.com" ]
15036833790@163.com
d01c2e3a1f0940a51fbd5aaf5582ea53946daea5
14760b5bfb854c728a0cc6180ffcbb6bd3eba928
/.mvn/wrapper/MavenWrapperDownloader.java
a5e6a054605742f2be7e0088f5f902c5beca1dde
[]
no_license
sungwony0906/test-study
891d37bb8291e50dd125b62beca7bf8c3db11649
34291ba091387e2748de7f18e84962d518a21730
refs/heads/master
2023-07-24T14:21:53.885450
2021-09-02T16:45:53
2021-09-02T16:45:53
399,848,738
0
0
null
null
null
null
UTF-8
Java
false
false
5,051
java
/* * Copyright 2007-present 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.net.*; import java.io.*; import java.nio.channels.*; import java.util.Properties; public class MavenWrapperDownloader { private static final String WRAPPER_VERSION = "0.5.6"; /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use * instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the * wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output directory '" + outputFile.getParentFile() .getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { String username = System.getenv("MVNW_USERNAME"); char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
[ "sungwony0906@gmail.com" ]
sungwony0906@gmail.com
d0dad1170641e033ec881cd2a43e16513e505471
e8f7a323c46dd047460d9db5a899d1917f0dd332
/jbpm-designer-vdml/jbpm-designer-vdml-backend/src/test/java/org/jbpm/designer/vdlib/VdmlLibraryDiagramGenerationTest.java
14c07de863cae7f0d0f3029a390b790540da63e5
[]
no_license
ifu-lobuntu/jbpm-designer-extensions
cc1e67366ea23bf4b7129730c502868a5f5e2035
8166cb1064b4e830d04346381f441a2e9830219d
refs/heads/master
2020-12-21T21:02:46.439177
2016-08-07T07:38:16
2016-08-07T07:38:16
31,703,967
0
0
null
null
null
null
UTF-8
Java
false
false
2,120
java
package org.jbpm.designer.vdlib; import static org.junit.Assert.*; import org.eclipse.uml2.uml.Property; import org.eclipse.uml2.uml.UMLFactory; import org.eclipse.uml2.uml.Class; import org.jbpm.designer.extensions.diagram.Diagram; import org.jbpm.designer.ucd.AbstractClassDiagramProfileImpl; import org.jbpm.designer.vdml.VdmlUmlHelper; import org.junit.Test; import org.omg.vdml.*; public class VdmlLibraryDiagramGenerationTest extends AbstractVdmlLibraryDiagramTest { @SuppressWarnings("unused") @Test public void testIt() throws Exception { Class clss = addCarrierClass("MyBusinessItemDefinition"); BusinessItemDefinition def = VdmlUmlHelper.createBusinessDefinition(clss, vdm.getBusinessItemLibrary().get(0)); def.setIsFungible(false); def.setIsShareable(true); Property characteristicDef = UMLFactory.eINSTANCE.createProperty(); characteristicDef.setName(characteristic.getName()); characteristicDef.createEAnnotation(VdmlLibraryStencil.VDLIB_URI).getReferences().add(characteristic); clss.getOwnedAttributes().add(characteristicDef); def.getCharacteristicDefinition().add(characteristic); characteristicDef.setType(AbstractClassDiagramProfileImpl.getCmmnTypes(resourceSet).getOwnedType("Double")); Class clss2 = addCarrierClass("CapabilityDefinition"); CapabilityDefinition cd = VdmlUmlHelper.createCapabilityDefinition(clss2, vdm.getCapabilitylibrary().get(0)); Class clss3 = addCarrierClass("CapabilityCategory"); CapabilityCategory cc = VdmlUmlHelper.createCapabilityCategory(clss3, vdm.getCapabilitylibrary().get(0)); saveCollaborationResource(); Diagram json = super.unmarshaller.convert(inputResource); assertNotNull( json.findChildShapeById(collaborationResource.getID(characteristicDef))); assertNotNull( json.findChildShapeById(collaborationResource.getID(clss))); assertNotNull( json.findChildShapeById(collaborationResource.getID(clss2))); assertNotNull( json.findChildShapeById(collaborationResource.getID(clss3))); } }
[ "ampieb@gmail.com" ]
ampieb@gmail.com
051f62c93ef1885d49adcd1088b27a1d563d90cf
9252f040dc98305c14678d8ede960a91bfc4fc7d
/modules/service/system-based-service-impl/src/main/java/com/lx/pop/service/dao/RefRolePrivEntityDao.java
07a5bba2dee79c0eaf2bb494513d2cffdddefcdb
[ "Apache-2.0" ]
permissive
yangluxi/lx-server
13fbbdb07cd5c244acb0c61b4111a684f5b5a3b1
f198eaa3e9c704f99f6159656b040943296700cc
refs/heads/master
2021-09-03T18:42:11.751437
2018-01-11T02:40:51
2018-01-11T05:59:51
117,039,200
1
0
null
null
null
null
UTF-8
Java
false
false
834
java
package com.lx.pop.service.dao; import com.lx.pop.entity.RefRolePrivEntity; import com.lx.pop.query.RefRolePrivEntityQuery; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Repository public interface RefRolePrivEntityDao { int countByExample(RefRolePrivEntityQuery example); int deleteByExample(RefRolePrivEntityQuery example); int insert(RefRolePrivEntity record); int insertSelective(RefRolePrivEntity record); List<RefRolePrivEntity> selectByExample(RefRolePrivEntityQuery example); int updateByExampleSelective(@Param("record") RefRolePrivEntity record, @Param("example") RefRolePrivEntityQuery example); int updateByExample(@Param("record") RefRolePrivEntity record, @Param("example") RefRolePrivEntityQuery example); }
[ "yang@lx.com" ]
yang@lx.com
5dccd4442baf53d9b1c8d2e666448fd782b809ec
47e0be9881c63777236aea87a4aedc98af512cf0
/app/src/main/java/lee/com/tianqidemo/HttpUtils.java
c86b93b87aff77d82b2b034d7cafe9107d2249d7
[]
no_license
leejcode/android-weather-forecast-application
6e5c76405083f120aa1a0850356f0dfedd9de3da
7bb6fec7b9ed68c8a277f8c6347d6c40434995f7
refs/heads/master
2020-05-02T20:02:48.206421
2019-03-28T10:54:44
2019-03-28T10:54:44
178,177,788
0
0
null
null
null
null
UTF-8
Java
false
false
858
java
package lee.com.tianqidemo; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by admin on 2017/2/3. */ public class HttpUtils { public static String readMyInputStream(InputStream is) { byte[] result; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer))!=-1) { baos.write(buffer,0,len); } is.close(); baos.close(); result = baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); String errorStr = "获取数据失败。"; return errorStr; } return new String(result); } }
[ "noreply@github.com" ]
noreply@github.com
2ef690c6c87208316150d304b86d62eb336d927e
5319d9b4eea4cb67a18e11e63a300598a53515ef
/JAVA/DAY_05/iacsd/problem2/TestEmployee.java
2b9771d7c4e349d4a345fb30034a502b87a2d844
[]
no_license
pranavvadanere/IACSDAssignment-
dfd0f804773c6ecbbb75751495953e6e0238dfb1
bd78e3678191d63319afe6a38af34cbe352df80a
refs/heads/master
2023-07-06T22:54:58.022322
2021-08-05T22:50:49
2021-08-05T22:50:49
362,573,929
1
0
null
null
null
null
UTF-8
Java
false
false
708
java
package com.iacsd.problem2; import java.util.Scanner; public class TestEmployee { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("enter number of employess"); int size = scan.nextInt(); Employee[] employees = new Employee[size]; // for - each loop for(Employee emp : employees) { emp.accept(); } for(Employee emp : employees) { if(emp.getSalary() > 20000 ) emp.display(); } // for loop for(int i = 0; i < employees.length; i++) { employees[i].accept(); } for(int i = 0; i < employees.length; i++) { if(employees[i].getSalary() > 20000) { employees[i].display(); } } scan.close(); } }
[ "pranav.vadanere@gmail.com" ]
pranav.vadanere@gmail.com
955d962f18c7884522f87afadba0ae7f91436047
bf00b404f8da08d1618ec25641636d80e0f22531
/src/main/java/br/usjt/exercicio1/controller/PrevisaoController.java
a279756dff31dc63773b1150af6bb3d24d27a9de
[]
no_license
gama-p/usjt2_19
62caeef5a6b0c6d5ed6824dfb5e307f845c49a77
a04824d45ea0ad21bf03aa758d5bfd7c783efa87
refs/heads/master
2020-07-08T13:06:27.610828
2019-10-26T13:42:59
2019-10-26T13:42:59
203,682,258
0
0
null
null
null
null
UTF-8
Java
false
false
996
java
package br.usjt.exercicio1.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import br.usjt.exercicio1.model.Periodo; import br.usjt.exercicio1.repository.PrevisaoRepository; import br.usjt.exercicio1.service.PrevisaoService; @Controller public class PrevisaoController { // a injeção de dependência ocorre aqui @Autowired private PrevisaoRepository previsaoRepo; @GetMapping("/previsao") public ModelAndView listarPrevisoes() { // passe o nome da página ao construtor ModelAndView mv = new ModelAndView("lista_previsoes"); // Busque a coleção com o repositório List<Periodo> previsoes = previsaoRepo.findAll(); // adicione a coleção ao objeto ModelAndView mv.addObject("previsoes", previsoes); // devolva o ModelAndView return mv; } }
[ "gama.p@outlook.com" ]
gama.p@outlook.com
44147507d9d4517f51fe916913d273b3e3f2a96f
dccb8ce0e4c507ae1bc396d66749b660e2ad38d5
/net/minecraft/block/BlockEnchantmentTable.java
e8700a4c459966bb6ccd86e56b2e9c7f29c1631f
[]
no_license
Saxalinproject/Java_Mod_Effections_Set
27cb3116a548295ff70c8585c4c802392e370f44
1799f11d74ecff594e1742a94df1ddc926be38a6
refs/heads/master
2020-04-08T22:10:29.373716
2013-11-04T13:33:01
2013-11-04T13:33:01
14,109,890
1
0
null
null
null
null
UTF-8
Java
false
false
5,348
java
package net.minecraft.block; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityEnchantmentTable; import net.minecraft.util.Icon; import net.minecraft.world.World; public class BlockEnchantmentTable extends BlockContainer { @SideOnly(Side.CLIENT) private Icon field_94461_a; @SideOnly(Side.CLIENT) private Icon field_94460_b; protected BlockEnchantmentTable(int par1) { super(par1, Material.rock); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); this.setLightOpacity(0); this.setCreativeTab(CreativeTabs.tabDecorations); } /** * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc) */ public boolean renderAsNormalBlock() { return false; } @SideOnly(Side.CLIENT) /** * A randomly called display update to be able to add particles or other items for display */ public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random) { super.randomDisplayTick(par1World, par2, par3, par4, par5Random); for (int l = par2 - 2; l <= par2 + 2; ++l) { for (int i1 = par4 - 2; i1 <= par4 + 2; ++i1) { if (l > par2 - 2 && l < par2 + 2 && i1 == par4 - 1) { i1 = par4 + 2; } if (par5Random.nextInt(16) == 0) { for (int j1 = par3; j1 <= par3 + 1; ++j1) { if (par1World.getBlockId(l, j1, i1) == Block.bookShelf.blockID) { if (!par1World.isAirBlock((l - par2) / 2 + par2, j1, (i1 - par4) / 2 + par4)) { break; } par1World.spawnParticle("enchantmenttable", (double)par2 + 0.5D, (double)par3 + 2.0D, (double)par4 + 0.5D, (double)((float)(l - par2) + par5Random.nextFloat()) - 0.5D, (double)((float)(j1 - par3) - par5Random.nextFloat() - 1.0F), (double)((float)(i1 - par4) + par5Random.nextFloat()) - 0.5D); } } } } } } /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two * adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block. */ public boolean isOpaqueCube() { return false; } @SideOnly(Side.CLIENT) /** * From the specified side and block metadata retrieves the blocks texture. Args: side, metadata */ public Icon getIcon(int par1, int par2) { return par1 == 0 ? this.field_94460_b : (par1 == 1 ? this.field_94461_a : this.blockIcon); } /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ public TileEntity createNewTileEntity(World par1World) { return new TileEntityEnchantmentTable(); } /** * Called upon block activation (right click on the block.) */ public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { if (par1World.isRemote) { return true; } else { TileEntityEnchantmentTable tileentityenchantmenttable = (TileEntityEnchantmentTable)par1World.getBlockTileEntity(par2, par3, par4); par5EntityPlayer.displayGUIEnchantment(par2, par3, par4, tileentityenchantmenttable.func_94135_b() ? tileentityenchantmenttable.func_94133_a() : null); return true; } } /** * Called when the block is placed in the world. */ public void onBlockPlacedBy(World par1World, int par2, int par3, int par4, EntityLivingBase par5EntityLivingBase, ItemStack par6ItemStack) { super.onBlockPlacedBy(par1World, par2, par3, par4, par5EntityLivingBase, par6ItemStack); if (par6ItemStack.hasDisplayName()) { ((TileEntityEnchantmentTable)par1World.getBlockTileEntity(par2, par3, par4)).func_94134_a(par6ItemStack.getDisplayName()); } } @SideOnly(Side.CLIENT) /** * When this method is called, your block should register all the icons it needs with the given IconRegister. This * is the only chance you get to register icons. */ public void registerIcons(IconRegister par1IconRegister) { this.blockIcon = par1IconRegister.registerIcon(this.func_111023_E() + "_" + "side"); this.field_94461_a = par1IconRegister.registerIcon(this.func_111023_E() + "_" + "top"); this.field_94460_b = par1IconRegister.registerIcon(this.func_111023_E() + "_" + "bottom"); } }
[ "pein-t-m@mail.ru" ]
pein-t-m@mail.ru
11163dfbc15d042b3fc86a2b90ad3b0f27d5c69e
326b1cda745e4679718baa6fb4c6f81028a5473d
/src/rateLimiter/IRateLimiterBuilder.java
07fc2426f09980adcf3bf1b40cdd0b43acb0ef88
[]
no_license
shabshay/rate-limiter
fc485f5eefc53841a086670e678b9d48a3fed25f
540307b4f3ff48aa8c25f7d6dc93846fa6fbd38a
refs/heads/master
2020-08-05T04:47:47.640734
2019-10-02T17:55:49
2019-10-02T17:55:49
212,401,387
0
0
null
null
null
null
UTF-8
Java
false
false
429
java
package rateLimiter; import java.util.concurrent.TimeUnit; public interface IRateLimiterBuilder<TKey> { IRateLimiter<TKey> build(); int getIntervalTime(); IRateLimiterBuilder setIntervalTime(int intervalTime); int getRateLimit(); IRateLimiterBuilder setRateLimit(int rateLimit); TimeUnit getTimeUnit(); IRateLimiterBuilder setTimeUnit(TimeUnit timeUnit); int getCalendarTimeUnitCode(); }
[ "shay.shabshay@gmail.com" ]
shay.shabshay@gmail.com
57bfb82d71255a28a8ef554883257da3a69b7575
abdd09b2c14eb56f8902ce264b018e1efac971f2
/src/main/java/com/epmserver/gateway/security/UserNotActivatedException.java
52ba6e91bf333b93135febee2d2a68ef1b79a2b6
[]
no_license
thetlwinoo/epm-gateway
e9494594344dff8dc3bf3d26a0f3c5027962eb14
c612ae8d7c382045b2960de259c856f16527a7fc
refs/heads/master
2022-12-24T14:16:40.723688
2019-11-22T09:54:42
2019-11-22T09:54:42
217,490,624
0
0
null
null
null
null
UTF-8
Java
false
false
517
java
package com.epmserver.gateway.security; import org.springframework.security.core.AuthenticationException; /** * This exception is thrown in case of a not activated user trying to authenticate. */ public class UserNotActivatedException extends AuthenticationException { private static final long serialVersionUID = 1L; public UserNotActivatedException(String message) { super(message); } public UserNotActivatedException(String message, Throwable t) { super(message, t); } }
[ "thetlwinoo85@yahoo.com" ]
thetlwinoo85@yahoo.com
3b2c49f8ae5b3e566e9cfd30a0c5fa2a5ffd50ef
654f1d874e6fd4becb0514fb7dcda3f10353dc16
/core/src/main/java/org/xchain/framework/jxpath/QNameVariables.java
0f17816db68f7b1e35457e8551cb4021a86a75e5
[ "Apache-2.0" ]
permissive
ctrimble/xchain
bea38de21d776a8a9610e04f2e06a4f1f3e21995
a45558b9f11b6ecf95cb7952272777af720e69d5
refs/heads/master
2016-09-05T22:46:49.447997
2013-04-07T16:15:44
2013-04-07T17:18:30
1,688,823
2
0
null
null
null
null
UTF-8
Java
false
false
2,526
java
/** * Copyright 2011 meltmedia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xchain.framework.jxpath; import java.util.Map; import javax.xml.namespace.QName; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.Variables; /** * An extension the Variables interface that properly resolves namespace prefixes. * * @author Christian Trimble * @author Devon Tackett */ public interface QNameVariables extends Variables { /** * Sets the JXPathContext that is used to lookup namespace uris. * * @param context the JXPathContext that will be used to lookup namespace uris. */ public void setJXPathContext( JXPathContext context ); /** * Returns the JXPathContext that is used to lookup namespace uris. * * @return the JXPathContext that is used to lookup namespace uris. */ public JXPathContext getJXPathContext(); /** * Declares a variable for the specified qName and value. * * @param qName the name of the variable being declared or replaced. * @param value the value of the variable being declared or replaced. */ public void declareVariable( QName qName, Object value ); /** * Gets a variable by the specified qName. * * @param qName the name of the variable to retrieve. * @return the value of the variable or null if the variable could not be found. */ public Object getVariable( QName qName ); /** * Returns true if the specified qName is defined, false otherwise. * * @param qName the name of the variable being tested. * @return true if the variable is declared, false otherwise. */ public boolean isDeclaredVariable( QName qName ); /** * Undeclares the variable for the specified qName. * * @param qName the name of the variable to undeclare. */ public void undeclareVariable( QName qName ); /** * @return A mapping of variable QName to variable values. */ public Map<QName, Object> getVariableMap(); }
[ "christian.trimble@meltmedia.com" ]
christian.trimble@meltmedia.com
523281e7f32f5dcc1a229f10ce952f8686e144cb
a10abab6bb7298403d7726bac96ae82bc0cce650
/src/main/java/org/pfaa/chemica/processing/Compaction.java
ac619b094411668c7d36fae41e9a40fdb06b7257
[ "Artistic-2.0" ]
permissive
Jorch72/PerFabricaAdAstra
b1a0f2579c051207b9229f80d464fea2e7579d9d
8abf89e96d9f75978138be8cad7c1fc08bb276b2
refs/heads/master
2020-03-29T11:24:26.743243
2017-06-05T12:34:05
2017-06-05T12:34:05
149,850,913
0
0
null
null
null
null
UTF-8
Java
false
false
764
java
package org.pfaa.chemica.processing; import org.pfaa.chemica.model.Condition; import org.pfaa.chemica.model.IndustrialMaterial; public class Compaction extends DegenerateConversion implements Sizing { protected Compaction(IndustrialMaterial material) { super(material); } @Override public Direction getDirection() { return Direction.INCREASE; } @Override public Condition getCondition() { return this.getMaterial().getSinteringCondition(); } @Override public double getEnergy() { return this.getMaterial().getEnthalpyChange(this.getCondition()); } @Override public Form getOutputForm(Form inputForm) { return inputForm.compact(); } public static Compaction of(IndustrialMaterial material) { return new Compaction(material); } }
[ "michafla@gene.com" ]
michafla@gene.com
5698e8dba5e9b3cbe0c553cb5de9a3bc9af744d3
d867f801f1b5da92b32b670e0617ff09a3650138
/auth-3scale/src/main/java/io/apiman/plugins/auth3scale/authrep/apikey/ApiKeyReportData.java
7002a953e12be30848984df87096fd7c50c6b8c8
[ "Apache-2.0" ]
permissive
OSMOSA44/apiman-plugins
f21fd9829668b5814d68da1f291cdf7301b70d10
0f9a79720c33f8c544b66d101e6998f8f8eaee73
refs/heads/master
2021-06-11T10:34:42.170853
2021-03-03T16:22:09
2021-03-03T16:22:09
137,735,078
0
0
null
2018-06-18T09:50:34
2018-06-18T09:50:34
null
UTF-8
Java
false
false
5,659
java
/* * Copyright 2016 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.plugins.auth3scale.authrep.apikey; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.LOG; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.REFERRER; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.SERVICE_ID; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.SERVICE_TOKEN; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.TIMESTAMP; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.USAGE; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.USER_ID; import static io.apiman.plugins.auth3scale.Auth3ScaleConstants.USER_KEY; import static io.apiman.plugins.auth3scale.util.Auth3ScaleUtils.setIfNotNull; import io.apiman.plugins.auth3scale.util.ParameterMap; import io.apiman.plugins.auth3scale.util.report.batchedreporter.ReportData; import java.net.URI; import java.util.Objects; /** * @author Marc Savy {@literal <msavy@redhat.com>} */ public class ApiKeyReportData implements ReportData { private URI endpoint; private String serviceToken; private String userKey; private String serviceId; private String timestamp; private String userId; private ParameterMap usage; private ParameterMap log; private String referrer; public URI getEndpoint() { return endpoint; } public ApiKeyReportData setEndpoint(URI endpoint) { this.endpoint = endpoint; return this; } @Override public String getServiceToken() { return serviceToken; } public ApiKeyReportData setServiceToken(String serviceToken) { this.serviceToken = serviceToken; return this; } public String getUserKey() { return userKey; } public ApiKeyReportData setUserKey(String userKey) { this.userKey = userKey; return this; } @Override public String getServiceId() { return serviceId; } public ApiKeyReportData setServiceId(String serviceId) { this.serviceId = serviceId; return this; } public String getTimestamp() { return timestamp; } @Override public ApiKeyReportData setTimestamp(String timestamp) { this.timestamp = timestamp; return this; } public String getUserId() { return userId; } public ApiKeyReportData setUserId(String userId) { this.userId = userId; return this; } @Override public ParameterMap getUsage() { return usage; } public ApiKeyReportData setUsage(ParameterMap usage) { this.usage = usage; return this; } @Override public ParameterMap getLog() { return log; } public ApiKeyReportData setLog(ParameterMap log) { this.log = log; return this; } @Override public int bucketId() { return hashCode(); } private String getReferrer() { return referrer; } public ApiKeyReportData setReferrer(String referrer) { this.referrer = referrer; return this; } @Override public int hashCode() { // TODO return Objects.hash(endpoint, serviceToken, serviceId); } @SuppressWarnings("nls") @Override public String toString() { return "ApiKeyReportData [endpoint=" + endpoint + ", serviceToken=" + serviceToken + ", userKey=" + userKey + ", serviceId=" + serviceId + ", timestamp=" + timestamp + ", userId=" + userId + ", usage=" + usage + ", log=" + log + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ApiKeyReportData other = (ApiKeyReportData) obj; if (endpoint == null) { if (other.endpoint != null) return false; } else if (!endpoint.equals(other.endpoint)) return false; if (serviceId == null) { if (other.serviceId != null) return false; } else if (!serviceId.equals(other.serviceId)) return false; if (serviceToken == null) { if (other.serviceToken != null) return false; } else if (!serviceToken.equals(other.serviceToken)) return false; return true; } @Override public ParameterMap toParameterMap() { ParameterMap paramMap = new ParameterMap(); paramMap.add(USER_KEY, getUserKey()); paramMap.add(SERVICE_TOKEN, getServiceToken()); paramMap.add(SERVICE_ID, getServiceId()); paramMap.add(USAGE, getUsage()); setIfNotNull(paramMap, TIMESTAMP, getTimestamp()); setIfNotNull(paramMap, LOG, getLog()); setIfNotNull(paramMap, REFERRER, getReferrer()); setIfNotNull(paramMap, USER_ID, getUserId()); return paramMap; } @Override public String encode() { return toParameterMap().encode(); } }
[ "marc@rhymewithgravy.com" ]
marc@rhymewithgravy.com
412c447f752249f8ac9d8f814c1754b9b252df7b
b45b2255856f2480564710e76b35a4a211ea0c9c
/java-in-depth/src/main/java/top/ljming/javaindepth/designpatterns/geeklesson/templatemethod/TemplateApplication.java
0039ec9519f8cdc3e27adbbda9d6a47f109afeef
[ "Apache-2.0" ]
permissive
ljm516/java-knowledge
be50c6e2cec9c26f2b943854e121380cbc130fc9
74822f9cc25fd60dba3ee5d3ec6f5b19cc5de048
refs/heads/master
2022-12-25T16:48:03.601608
2020-09-22T03:24:12
2020-09-22T03:24:12
173,557,548
3
0
Apache-2.0
2022-12-16T15:17:32
2019-03-03T09:59:28
Java
UTF-8
Java
false
false
569
java
package top.ljming.javaindepth.designpatterns.geeklesson.templatemethod; /** * 模板方法模式. * * 模板方式模式在一个方法中第一一个算法骨架,并将某些步骤推迟到子类中实现。 * 模板方法模式可以让子类在不改变算法的整体结构的情况下,重新定义算法中的某些步骤。 * * @author ljming */ public class TemplateApplication { public static void main(String[] args) { TemplateMethodAbstractClass abstractClass = new ConcreateClass1(); abstractClass.templateMethod(); } }
[ "lijiangming@ybm100.com" ]
lijiangming@ybm100.com
f2d4fe33ceef19f4e7e7254a912c8f5aa449f0ee
42c54089fb8dcbc4e725ca3ff41c558d465d43bd
/MyShop/src/cn/wangchenhui/filter/AdminActionFilter.java
d2d7ae0c4062833c44a296f811c835ed938c3156
[]
no_license
Henaner/MyShop
28277d2e9b0d840b5fe1c5abbecad8a7042f6f7c
002b87f370a758752e6a7c3280b237b9d75c1e8a
refs/heads/master
2021-01-10T17:50:07.971144
2016-03-26T14:10:47
2016-03-26T14:10:47
48,987,799
0
0
null
null
null
null
UTF-8
Java
false
false
1,333
java
package cn.wangchenhui.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.wangchenhui.model.User; public class AdminActionFilter implements Filter{ @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; HttpSession session = request.getSession(); User user = (User)session.getAttribute("loginUser"); if(user == null){ response.sendRedirect(request.getContextPath()+"/admin/admin.jsp"); return ; } filterChain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
[ "565999928@qq.com" ]
565999928@qq.com
0643805925ee0a05d3cdc9f34dde0ac0fc8046cb
daffd26347380a78b624bba096bed17f45f62de5
/src/main/java/edu/usc/cs/ir/cwork/es/EsIndexer.java
2c5567bb95262985454af39a8545148ba78f8bd5
[]
no_license
thammegowda/parser-indexer
fa56926c423c0191d08765437a40fbdc87566720
eefdbf8a6be781c6390bc057c34e5f289fd2cc24
refs/heads/master
2021-01-10T03:00:35.172609
2016-03-23T19:09:31
2016-03-23T19:09:31
47,856,913
3
2
null
null
null
null
UTF-8
Java
false
false
7,689
java
package edu.usc.cs.ir.cwork.es; import edu.usc.cs.ir.cwork.nutch.NutchDumpPathBuilder; import edu.usc.cs.ir.cwork.nutch.RecordIterator; import edu.usc.cs.ir.cwork.nutch.SegContentReader; import edu.usc.cs.ir.cwork.solr.ContentBean; import edu.usc.cs.ir.cwork.tika.Parser; import io.searchbox.client.JestClient; import io.searchbox.client.JestClientFactory; import io.searchbox.client.JestResult; import io.searchbox.client.config.HttpClientConfig; import io.searchbox.core.Bulk; import io.searchbox.core.Index; import org.apache.commons.io.IOUtils; import org.apache.commons.math3.util.Pair; import org.apache.nutch.protocol.Content; import org.apache.solr.client.solrj.SolrServerException; import org.json.JSONObject; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.function.Function; /** * This class accepts CLI args containing paths to Nutch segments and elastic search, * then runs the indexes the documents to elastic search by parsing the metadata. */ public class EsIndexer { private static Logger LOG = LoggerFactory.getLogger(EsIndexer.class); @Option(name = "-segs", usage = "Path to a text file containing segment paths. One path per line", required = true) private File segsFile; @Option(name = "-nutch", usage = "Path to Nutch home.", required = true) private String nutchHome; @Option(name = "-dump", usage = "Path to dump prefix.") private String dumpPath = "/data2/USCWeaponsStatsGathering/nutch/full_dump/"; @Option(name = "-batch", usage = "Number of documents to buffer and post to solr", required = false) private int batchSize = 1000; @Option(name= "-cdrcreds", usage = "CDR credentials properties file.", required = true) private File cdrCredsFile; private CDRCreds creds; private Function<URL, String> pathMapper; /** * This POJO stores MEMEX credentials */ public static class CDRCreds { public String clusterUri; public String username; public String password; public String indexType; public String indexName; public CDRCreds(Properties props){ this.clusterUri = props.getProperty("memex.cdr.cluster"); this.username = props.getProperty("memex.cdr.username"); this.password = props.getProperty("memex.cdr.password"); this.indexName = props.getProperty("memex.cdr.index"); this.indexType = props.getProperty("memex.cdr.type"); } } /** * runs the solr index command * @throws IOException * @throws InterruptedException * @throws SolrServerException */ public void run() throws IOException, InterruptedException, SolrServerException { //STEP 1: initialize NUTCH System.setProperty("nutch.home", nutchHome); //step 2: path mapper this.pathMapper = new NutchDumpPathBuilder(this.dumpPath); //Step LOG.info("Getting cdr details from {}", cdrCredsFile); Properties props = new Properties(); props.load(new FileInputStream(cdrCredsFile)); this.creds = new CDRCreds(props); JestClient client = openCDRClient(); try { //Step FileInputStream stream = new FileInputStream(segsFile); List<String> paths = IOUtils.readLines(stream); IOUtils.closeQuietly(stream); LOG.info("Found {} lines in {}", paths.size(), segsFile.getAbsolutePath()); SegContentReader reader = new SegContentReader(paths); RecordIterator recs = reader.read(); //Step 4: elastic client index(recs, client); System.out.println(recs.getCount()); }finally { LOG.info("Shutting down jest client"); client.shutdownClient(); } } private JestClient openCDRClient(){ LOG.info("CDR name:type = {}:{}", creds.indexName, creds.indexType); JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig(new HttpClientConfig.Builder(creds.clusterUri) .discoveryEnabled(false) .discoveryFrequency(1l, TimeUnit.MINUTES) .multiThreaded(true) .defaultCredentials(creds.username, creds.password) .connTimeout(300000).readTimeout(300000) .build()); return factory.getObject(); } private void index(RecordIterator recs, JestClient elastic) throws IOException, SolrServerException { long st = System.currentTimeMillis(); long count = 0; long delay = 2 * 1000; Parser parser = Parser.getInstance(); List<JSONObject> buffer = new ArrayList<>(batchSize); while (recs.hasNext()) { Pair<String, Content> rec = recs.next(); Content content = rec.getValue(); ContentBean bean = new ContentBean(); try { parser.loadMetadataBean(content, pathMapper, bean); buffer.add(ESMapper.toCDRSchema(bean)); count++; if (buffer.size() >= batchSize) { try { indexAll(buffer, elastic); buffer.clear(); } catch (Exception e) { throw new RuntimeException(e); } } if (System.currentTimeMillis() - st > delay) { LOG.info("Num Docs : {}", count); st = System.currentTimeMillis(); } } catch (Exception e){ LOG.error("Error processing {}", content.getUrl()); LOG.error(e.getMessage(), e); } } //left out if (!buffer.isEmpty()) { indexAll(buffer, elastic); buffer.clear(); } LOG.info("Num Docs = {}", count); } private void indexAll(List<JSONObject> docs, JestClient client) throws IOException { List<Index> inputDocs = new ArrayList<>(); for (JSONObject doc : docs) { String id = (String) doc.remove("obj_id"); if (id == null) { LOG.warn("No ID set to document. Skipped"); continue; } inputDocs.add(new Index.Builder(doc.toString()).id(id).build()); } Bulk bulk = new Bulk.Builder() .defaultIndex(creds.indexName) .defaultType(creds.indexType) .addAction(inputDocs) .build(); JestResult result = client.execute(bulk); if (!result.isSucceeded()){ LOG.error("Failure in bulk commit: {}", result.getErrorMessage()); } } public static void main(String[] args) throws InterruptedException, SolrServerException, IOException { EsIndexer indexer = new EsIndexer(); CmdLineParser cmdLineParser = new CmdLineParser(indexer); try { cmdLineParser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); cmdLineParser.printUsage(System.out); return; } indexer.run(); LOG.info("Done"); System.out.println("Done"); } }
[ "tgowdan@gmail.com" ]
tgowdan@gmail.com
4e4b96ea257fec90ac63c30b6c9deb33aa86e915
f2c004cd049d94ec6c39d9d8e03463a41cbf9b62
/src/main/java/org/team639/robot/subsystems/Lift.java
ae4c2549a24e486193ca80b13877e38dd00edb29
[]
no_license
CRRobotics/2018Robot
c892ce798eeefcdbdb244b6b643ec93bb8856eec
23fd3a2dad019f215788209ae2479adff88c9574
refs/heads/master
2021-03-22T00:25:36.940894
2018-10-27T13:15:18
2018-10-27T13:15:18
118,819,856
0
1
null
null
null
null
UTF-8
Java
false
false
6,731
java
package org.team639.robot.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.FeedbackDevice; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.StatusFrameEnhanced; import com.ctre.phoenix.motorcontrol.can.TalonSRX; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.command.Subsystem; import org.team639.robot.RobotMap; import org.team639.robot.commands.lift.MoveLiftWithJoystick; import static org.team639.robot.Constants.*; /** * The lift subsystem. * Responsible for moving the acquisition system up and down. */ public class Lift extends Subsystem { private TalonSRX mainTalon; private TalonSRX followerTalon; private Solenoid brake; private ControlMode currentControlMode; // private Solenoid climbingPiston; private double kP; private double kI; private double kD; private double kF; public Lift() { mainTalon = RobotMap.getLiftMain(); followerTalon = RobotMap.getLiftFollower(); followerTalon.follow(mainTalon); // mainTalon.setSensorPhase(true); mainTalon.setInverted(true); followerTalon.setInverted(true); mainTalon.configReverseSoftLimitEnable(false, 0); mainTalon.configForwardSoftLimitEnable(true, 0); mainTalon.configForwardSoftLimitThreshold(LIFT_MAX_HEIGHT, 0); mainTalon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, 0, 0); mainTalon.setSensorPhase(true); mainTalon.setStatusFramePeriod(StatusFrameEnhanced.Status_3_Quadrature, 20, 0); mainTalon.setNeutralMode(NeutralMode.Brake); mainTalon.configAllowableClosedloopError(0, 50, 0); brake = RobotMap.getLiftBrake(); // climbingPiston = RobotMap.getClimbPiston(); // mainTalon.configMotionCruiseVelocity(LIFT_CRUISE, 0); // mainTalon.configMotionAcceleration(LIFT_ACCELERATION, 0); setPID(LIFT_P, LIFT_I, LIFT_D, LIFT_F); if (encoderPresent()) setCurrentControlMode(ControlMode.Velocity); else setCurrentControlMode(ControlMode.PercentOutput); } /** * Sets the speed of the lift with a percent of total speed from -1 to 1. Negative is down and positive is up. * @param speed The speed to move the lift. */ public void setSpeedPercent(double speed) { if (speed > 1) speed = 1; else if (speed < -1) speed = -1; switch (currentControlMode) { case PercentOutput: mainTalon.set(currentControlMode, speed); break; case Velocity: mainTalon.set(currentControlMode, speed * LIFT_MAX_SPEED); break; } } /** * Sets a certain position (in encoder ticks) to travel to using motion magic. * @param tickCount The position to travel to. */ public void setMotionMagicPosition(int tickCount) { mainTalon.set(ControlMode.MotionMagic, tickCount); } /** * Returns the current value read by the encoder. * @return The current value read by the encoder. */ public int getEncPos() { return mainTalon.getSelectedSensorPosition(0); } /** * Sets the current position of the relative encoder to zero. */ public void zeroEncoder() { mainTalon.getSensorCollection().setQuadraturePosition(0, 0); } /** * Returns whether or not the lift is at the lower limit. * @return Whether or not the lift is at the lower limit. */ public boolean isAtLowerLimit() { // return lowerLimit.get(); return mainTalon.getSensorCollection().isRevLimitSwitchClosed(); } /** * Locks or unlocks the first stage of the lift. * @param locked Whether or not the first stage should be locked. */ public void setBrake(boolean locked) { //brake.set(true); brake.set(!locked); } /** * Returns whether of not the first stage is locked. * @return Whether of not the first stage is locked. */ public boolean isBraking() { return !brake.get(); } /** * Returns the current control mode. * @return The current control mode. */ public ControlMode getCurrentControlMode() { return currentControlMode; } /** * Sets the current control mode. * @param controlMode The control mode. */ public void setCurrentControlMode(ControlMode controlMode) { this.currentControlMode = controlMode; } /** * Sets the talon internal pid. * @param p The p constant. * @param i The i constant. * @param d The d constant. * @param f The f constant. */ public void setPID(double p, double i, double d, double f) { this.kP = p; this.kI = i; this.kD = d; this.kF = f; mainTalon.config_kP(0, p, 0); mainTalon.config_kI(0, i, 0); mainTalon.config_kD(0, d, 0); mainTalon.config_kF(0, f, 0); } /** * Returns the current p constant. * @return The current p constant. */ public double getkP() { return kP; } /** * Returns the current i constant. * @return The current i constant. */ public double getkI() { return kI; } /** * Returns the current d constant. * @return The current d constant. */ public double getkD() { return kD; } /** * Returns the current f constant. * @return The current f constant. */ public double getkF() { return kF; } /** * Returns whether or not the encoder is present on the lift. * @return Whether or not the encoder is present. */ public boolean encoderPresent() { return mainTalon.getSensorCollection().getPulseWidthRiseToRiseUs() != 0; } public double getEncVelocity() { return mainTalon.getSelectedSensorVelocity(0); } public void setMotionCruiseVelocity(int velocity) { mainTalon.configMotionCruiseVelocity(velocity, 0); } public void setMotionAccelerationVelocity(int velocity) { mainTalon.configMotionAcceleration(velocity, 0); } /** * Initialize the default command for a subsystem By default subsystems have no default command, * but if they do, the default command is set with this method. It is called on all Subsystems by * CommandBase in the users program after all the Subsystems are created. */ @Override protected void initDefaultCommand() { setDefaultCommand(new MoveLiftWithJoystick()); } }
[ "theProgrammerJack@gmail.com" ]
theProgrammerJack@gmail.com
c8fdcd69833a93a70d8b3136ebbbd3b0e452fd52
08004a0f5015e5fea17901e78f94efc52128d45b
/Assignment_3/src/vendorInterface/UpdateJPanel.java
8da73514c458590fb2e658b02583e0f3ae492da6
[]
no_license
Zeqiang/workspace_info5100_javaGUI
c2add89350ddc2aaefa669548a827a4938e7d3d0
685f5dd17ea6b51ad1583f51cf11d770453ed821
refs/heads/master
2021-08-07T05:53:48.928009
2017-11-07T17:22:11
2017-11-07T17:22:11
109,866,595
0
0
null
null
null
null
UTF-8
Java
false
false
19,771
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 vendorInterface; import vendorInterface.ManageJPanel; import Bussiness.Product; import Bussiness.ProductDirectory; import java.awt.CardLayout; import java.awt.Component; import java.sql.Date; import javax.swing.JOptionPane; import javax.swing.JPanel; import jdk.nashorn.internal.scripts.JO; /** * * @author Eric */ public class UpdateJPanel extends javax.swing.JPanel { /** * Creates new form ViewJPanel */ private JPanel processJPanel; private Product product; public UpdateJPanel(JPanel processJPanel, Product product) { initComponents(); this.processJPanel = processJPanel; this.product = product; populateDetail(); SaveBtn.setEnabled(false); UpdateBtn.setEnabled(true); } public void populateDetail(){ TypeTextF.setText(product.getType()); NameTextF.setText(product.getName()); ModelTextF.setText(product.getModelNumber()); VendorTextF.setText(product.getVendor()); DescriptionTextF.setText(product.getDescription()); BasePriceTextF.setText(String.valueOf(product.getBasePrice())); CeilingPriceTextF.setText(String.valueOf(product.getCeilingPrice())); FloorPriceTextF.setText(String.valueOf(product.getFloorPrice())); FeatureTextA.setText(product.getFeature()); BenefitTextA.setText(product.getBenefit()); TimeTextF.setText(String.valueOf(product.getCreateOn())); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); NameTextF = new javax.swing.JTextField(); ModelTextF = new javax.swing.JTextField(); DescriptionTextF = new javax.swing.JTextField(); BasePriceTextF = new javax.swing.JTextField(); CeilingPriceTextF = new javax.swing.JTextField(); FloorPriceTextF = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); FeatureTextA = new javax.swing.JTextArea(); jLabel11 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); BenefitTextA = new javax.swing.JTextArea(); jLabel12 = new javax.swing.JLabel(); TimeTextF = new javax.swing.JTextField(); BackBtn = new javax.swing.JButton(); TypeTextF = new javax.swing.JTextField(); VendorTextF = new javax.swing.JTextField(); SaveBtn = new javax.swing.JButton(); UpdateBtn = new javax.swing.JButton(); jLabel1.setFont(new java.awt.Font("Monaco", 1, 24)); // NOI18N jLabel1.setText("View Product Details"); jLabel2.setText("Product Type :"); jLabel3.setText("Product Name :"); jLabel4.setText("Model Number :"); jLabel5.setText("Vendor :"); jLabel6.setText("Description :"); jLabel7.setText("Base Price :"); jLabel8.setText("Ceiling Price :"); jLabel9.setText("Floor Price :"); NameTextF.setEnabled(false); ModelTextF.setEnabled(false); DescriptionTextF.setEnabled(false); BasePriceTextF.setEnabled(false); CeilingPriceTextF.setEnabled(false); FloorPriceTextF.setEnabled(false); jLabel10.setText("Feature :"); FeatureTextA.setColumns(20); FeatureTextA.setRows(5); FeatureTextA.setEnabled(false); jScrollPane2.setViewportView(FeatureTextA); jLabel11.setText("Benefit :"); BenefitTextA.setColumns(20); BenefitTextA.setRows(5); BenefitTextA.setEnabled(false); jScrollPane3.setViewportView(BenefitTextA); jLabel12.setText("Create Time :"); TimeTextF.setEnabled(false); BackBtn.setText("<Back"); BackBtn.setPreferredSize(new java.awt.Dimension(100, 40)); BackBtn.setSize(new java.awt.Dimension(80, 29)); BackBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackBtnActionPerformed(evt); } }); TypeTextF.setEnabled(false); VendorTextF.setEnabled(false); SaveBtn.setText("Save"); SaveBtn.setEnabled(false); SaveBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveBtnActionPerformed(evt); } }); UpdateBtn.setText("Update"); UpdateBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UpdateBtnActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(61, 61, 61) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel2) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel8) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(ModelTextF) .addComponent(DescriptionTextF) .addComponent(BasePriceTextF) .addComponent(CeilingPriceTextF) .addComponent(FloorPriceTextF, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) .addComponent(TypeTextF) .addComponent(VendorTextF) .addComponent(NameTextF)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(66, 66, 66) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel10) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(TimeTextF)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(87, 87, 87) .addComponent(SaveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(UpdateBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(BackBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(158, 158, 158) .addComponent(jLabel1))) .addContainerGap(37, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(BackBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(TypeTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(NameTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(11, 11, 11) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(ModelTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(VendorTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(DescriptionTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(BasePriceTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(CeilingPriceTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(FloorPriceTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(TimeTextF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(SaveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(UpdateBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(45, 45, 45)))) ); jScrollPane1.setViewportView(jPanel1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 720, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void BackBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackBtnActionPerformed // TODO add your handling code here: processJPanel.remove(this); Component[] componentArray = processJPanel.getComponents(); Component component = componentArray[componentArray.length-1]; ManageJPanel managejp = (ManageJPanel) component; managejp.populateTable(); CardLayout layout = (CardLayout)processJPanel.getLayout(); layout.previous(processJPanel); }//GEN-LAST:event_BackBtnActionPerformed private void SaveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveBtnActionPerformed // TODO add your handling code here: product.setType(TypeTextF.getText()); product.setName(NameTextF.getText()); product.setModelNumber(ModelTextF.getText()); product.setVendor(VendorTextF.getText()); product.setDescription(DescriptionTextF.getText()); product.setBasePrice(Integer.parseInt(BasePriceTextF.getText())); product.setCeilingPrice(Integer.parseInt(CeilingPriceTextF.getText())); product.setFloorPrice(Integer.parseInt(FloorPriceTextF.getText())); product.setFeature(FeatureTextA.getText()); product.setBenefit(BenefitTextA.getText()); product.setCreateOn(TimeTextF.getText()); SaveBtn.setEnabled(false); UpdateBtn.setEnabled(true); JOptionPane.showMessageDialog(null, "Product Updated Successfully", "Information", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_SaveBtnActionPerformed private void UpdateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateBtnActionPerformed // TODO add your handling code here: NameTextF.setEnabled(true); ModelTextF.setEnabled(true); DescriptionTextF.setEnabled(true); BasePriceTextF.setEnabled(true); CeilingPriceTextF.setEnabled(true); FloorPriceTextF.setEnabled(true); FeatureTextA.setEnabled(true); BenefitTextA.setEnabled(true); SaveBtn.setEnabled(true); UpdateBtn.setEnabled(false); }//GEN-LAST:event_UpdateBtnActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BackBtn; private javax.swing.JTextField BasePriceTextF; private javax.swing.JTextArea BenefitTextA; private javax.swing.JTextField CeilingPriceTextF; private javax.swing.JTextField DescriptionTextF; private javax.swing.JTextArea FeatureTextA; private javax.swing.JTextField FloorPriceTextF; private javax.swing.JTextField ModelTextF; private javax.swing.JTextField NameTextF; private javax.swing.JButton SaveBtn; private javax.swing.JTextField TimeTextF; private javax.swing.JTextField TypeTextF; private javax.swing.JButton UpdateBtn; private javax.swing.JTextField VendorTextF; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; // End of variables declaration//GEN-END:variables }
[ "zeqiang.lee@gmail.com" ]
zeqiang.lee@gmail.com
850e62217a8751f7544e950d80a4fbb1c5582f55
f543462dbbb6d59f5cb0c8caee9e25dfbde9e3c5
/springboot-rabbitmq/rabbitmq-producer/src/main/java/cn/lovingliu/rabbitmqproducer/service/impl/OrderServiceImpl.java
5dfdc9b503d66453590e0dc52924b055760771ae
[]
no_license
LovingLiuMeMe/springboot-study
5929e8e15bb99a218f3e773d9e28998b73e7f2bc
572c9d2a105b5e1fe13208489846c53a4f359a0f
refs/heads/master
2022-07-05T03:30:05.363237
2019-10-15T16:26:14
2019-10-15T16:26:14
214,101,307
0
0
null
2022-06-17T02:33:30
2019-10-10T06:12:46
Java
UTF-8
Java
false
false
1,810
java
package cn.lovingliu.rabbitmqproducer.service.impl; import cn.lovingliu.rabbitmqproducer.constant.Constants; import cn.lovingliu.rabbitmqproducer.dao.MessageLogMapper; import cn.lovingliu.rabbitmqproducer.dao.OrderMapper; import cn.lovingliu.rabbitmqproducer.domain.MessageLog; import cn.lovingliu.rabbitmqproducer.domain.Order; import cn.lovingliu.rabbitmqproducer.producer.RabbitOrderSender; import cn.lovingliu.rabbitmqproducer.service.OrderService; import cn.lovingliu.rabbitmqproducer.utils.DateUtils; import cn.lovingliu.rabbitmqproducer.utils.FastJsonConvertUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; /** * @Author:LovingLiu * @Description: * @Date:Created in 2019-09-24 */ @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderMapper orderMapper; @Autowired private MessageLogMapper messageLogMapper; @Autowired private RabbitOrderSender rabbitOrderSender; public void createOrder(Order order) throws Exception { // 插入消息记录表数据 MessageLog messageLog = new MessageLog(); // 消息唯一ID messageLog.setMessageId(order.getMessageId()); // 保存消息整体 转为JSON 格式存储入库 messageLog.setMessage(FastJsonConvertUtil.convertObjectToJSON(order)); // 设置消息状态为0 表示发送中 messageLog.setStatus("0"); // 设置消息未确认超时时间窗口为 一分钟 Date orderTime = new Date(); messageLog.setNextRetry(DateUtils.addMinutes(orderTime, Constants.ORDER_TIMEOUT)); messageLogMapper.insertSelective(messageLog); // 发送消息 rabbitOrderSender.sendOrder(order); } }
[ "cmds12345678@163.com" ]
cmds12345678@163.com
abbc1debdab4ed04ec422aa51a9743be4d247d54
a78b493dbdc0b0d49f5b85bf6f8d2120b3020909
/src/examples/serialization/counter/package-info.java
a76925b75670bc6836c614226030f72937abfd22
[]
no_license
pdewan/GIPC
6998839307eedf37dda0451bfe331c45c0bfc1b5
46c18824b7a5cf73bf12122023a714194a464415
refs/heads/master
2022-04-26T20:32:09.075467
2022-04-03T19:48:39
2022-04-03T19:48:39
16,309,078
3
6
null
2017-05-10T23:29:18
2014-01-28T10:45:03
Java
UTF-8
Java
false
false
86
java
/** * */ /** * @author dewan * */ package examples.serialization.counter;
[ "dewan@cs.unc.edu" ]
dewan@cs.unc.edu
67f307f70f39b816c73b8444e705be3126270476
0b199d3925a8933f474b9db2cb133eb890cd1978
/src/main/java/com/finra/inventory/service/InventoryImpl.java
04b2cd43c6f4faa3fb4da657752f11bd5d703200
[]
no_license
sandeep544/ProductDemo
1ef4b78fff0799875263d6d18bca1c9234fd7561
1a9f3cd806c4e1b2fe36ebd7541db45c318c870c
refs/heads/master
2021-08-23T21:30:34.171879
2017-12-06T16:46:15
2017-12-06T16:46:15
113,342,681
0
0
null
null
null
null
UTF-8
Java
false
false
429
java
package com.finra.inventory.service; import org.springframework.stereotype.Component; @Component public class InventoryImpl implements Inventory { @Override public boolean CheckInventory(String id, int qty) { if (null != id && 0 != qty) { // Need to Read records from database by default making the total // quality as 100 int totQty = 100; if (qty < totQty) { return true; } } return false; } }
[ "34313696+sandeep544@users.noreply.github.com" ]
34313696+sandeep544@users.noreply.github.com
4969ce16410ab863d80264e15a4c05e78d98ae47
c33a780ec85379cbeb07c32106494ca1c75d823c
/Coderanch/exceptions/Excep.java
4cc6f7d3dfc8ee84267ad52d758740da72dc5ece
[]
no_license
Baristopcu08/OCP-study-guide
64aa8007fa6ed0ad3a3b0bb7b1d8568ffbaa0a6f
1dfba8126767119698320adeb50a362106a128e0
refs/heads/master
2023-03-17T10:19:26.740260
2018-01-15T18:06:49
2018-01-15T18:06:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,233
java
import java.io.IOException; import java.io.FileNotFoundException; import java.util.*; import java.io.EOFException; class A{} class B extends A{} class C extends B{} class D extends C{} public class Excep { public static void main(String[] args) throws IOException { List<? super B> exceptions = new ArrayList<>(); exceptions.add(new C()); exceptions.add(new B()); //exceptions.add(new A()); erro /**(upperbounded and unbounded generics are immutable)**/ //passUpperBounded(new ArrayList<A>()); passUpperBounded(new ArrayList<B>()); passUpperBounded(new ArrayList<C>()); passUpperBounded(new ArrayList<D>()); List<? super IOException> exceptions2 = new ArrayList<Exception>(); //exceptions.add(new Exception()); // DOES NOT COMPILE exceptions2.add(new IOException()); exceptions2.add(new FileNotFoundException()); //passUpperBoundedIO(new ArrayList<Exception>()); passUpperBoundedIO(new ArrayList<IOException>()); passUpperBoundedIO(new ArrayList<FileNotFoundException>()); passUpperBoundedIO(new ArrayList<EOFException>()); } public static void passUpperBounded(List<? extends B> list){ } public static void passUpperBoundedIO(List<? extends IOException> list){ } }
[ "rafael_possenti@hotmail.com" ]
rafael_possenti@hotmail.com
e6bb29232994e95a69b39dbcaf9695313f7f3c62
fcbb4d30ed8c0ccd93b1e92771bc486d0bbea748
/src/main/java/dao/OrderDAO.java
aac428a7f4bb18d86a8e008366abc3afeeab49e1
[]
no_license
RusuDaniel98/WarehouseManagement
abf8092a39074d4bea3fcf77d09f7313d5e70cfe
1b9205f0a2a9c0a65748e87c930d2e589155f94b
refs/heads/master
2021-04-14T16:46:37.897793
2020-03-22T18:29:53
2020-03-22T18:29:53
249,246,942
0
0
null
null
null
null
UTF-8
Java
false
false
4,554
java
package dao; import connection.ConnectionFactory; import model.Order; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; /** * <h1>DAO Package</h1> * Class used to interact with the database 'order' table. * It contains methods to insert, delete and find the data in this table. * @author Rusu Daniel * @version 1.0 * @since 2019-04-15 */ public class OrderDAO { protected static final Logger LOGGER = Logger.getLogger(OrderDAO.class.getName()); private static final String insertStatementString = "INSERT INTO `order` (idClient,idProduct,totalPrice,idPayment)" + " VALUES (?,?,?,?)"; private final static String findStatementString = "SELECT * FROM order where idOrder = ?"; private final static String deleteStatementString = "DELETE FROM order WHERE idOrder = ?"; /** * Method used to find the row in the database table by id. * It uses a select sql statement. * @param idOrder This is the id that should be found in the database 'order' table. * @return An object of type Order, representing the one found by id in the database. */ public static Order findById(int idOrder){ Order toReturn = null; Connection dbConnection = ConnectionFactory.getConnection(); PreparedStatement findStatement = null; ResultSet rs = null; try{ findStatement = dbConnection.prepareStatement(findStatementString); findStatement.setLong(1, idOrder); rs = findStatement.executeQuery(); rs.next(); int idClient = rs.getInt("idClient"); int idProduct = rs.getInt("idProduct"); int totalPrice = rs.getInt("totalPrice"); int idPayment = rs.getInt("idPayment"); toReturn = new Order(idClient, idProduct, totalPrice, idPayment); } catch (SQLException e) { LOGGER.log(Level.WARNING, "OrderDAO:findById " + e.getMessage()); } finally{ ConnectionFactory.close(rs); ConnectionFactory.close(findStatement); ConnectionFactory.close(dbConnection); } return toReturn; } /** * This method is used to insert an order in the database table. * It uses a insert sql statement. * @param order This is the object to be inserted in the database table. * @return The id of the row it was inserted at. */ public static int insertOrder(Order order){ Connection dbConnection = ConnectionFactory.getConnection(); PreparedStatement insertStatement = null; int insertedId = -1; try{ insertStatement = dbConnection.prepareStatement(insertStatementString, Statement.RETURN_GENERATED_KEYS); insertStatement.setInt(1, order.getIdClient()); insertStatement.setInt(2, order.getIdProduct()); insertStatement.setInt(3, order.getTotalPrice()); insertStatement.setInt(4, order.getIdPayment()); insertStatement.executeUpdate(); ResultSet rs = insertStatement.getGeneratedKeys(); if (rs.next()){ insertedId = rs.getInt(1); } } catch (SQLException e){ LOGGER.log(Level.WARNING, "OrderDAO:insert " + e.getMessage()); } finally { ConnectionFactory.close(insertStatement); ConnectionFactory.close(dbConnection); } return insertedId; } /** * Method used to delete a row (entry) in the database 'order' table. * It uses a delete sql statement. * @param id This is the id of the item to be deleted. * @return The id if it worked, or a '-1' otherwise. */ public static int removeById(int id){ Connection dbConnection = ConnectionFactory.getConnection(); PreparedStatement deleteStatement = null; int removedId = -1; try{ deleteStatement = dbConnection.prepareStatement(deleteStatementString, Statement.RETURN_GENERATED_KEYS); deleteStatement.setLong(1, id); deleteStatement.executeUpdate(); ResultSet rs = deleteStatement.getGeneratedKeys(); if (rs.next()){ removedId = rs.getInt(1); } } catch (SQLException e){ LOGGER.log(Level.WARNING, "OrderDAO:remove " + e.getMessage()); } finally { ConnectionFactory.close(deleteStatement); ConnectionFactory.close(dbConnection); } return removedId; } }
[ "daniel98rusu@gmail.com" ]
daniel98rusu@gmail.com
23ef0dd7c0f6af3f32d77876f86c3c8b9632f1cf
96b318a0637a1fece94e60c5542add3887d48fb5
/spark-manager-service/src/main/java/tn/insat/pfe/sparkmanagerservice/config/SparkManagerConfig.java
ac5f249152412f453491e99f149a2be2d5e98505
[]
no_license
karimsaieh/indexini
6148505ed503392426acbf98a913918ac291e8bf
c8b81e646877634b9122750df71203929bd98394
refs/heads/master
2023-01-11T16:34:20.739467
2019-09-12T19:25:37
2019-09-12T19:25:37
170,025,011
2
0
null
2023-01-04T10:18:24
2019-02-10T20:43:57
Vue
UTF-8
Java
false
false
359
java
package tn.insat.pfe.sparkmanagerservice.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class SparkManagerConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
[ "ksayeh@ymail.com" ]
ksayeh@ymail.com