hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923989437bce621f8cf577373bae8dce975122e9
3,263
java
Java
structr-rest/src/main/java/org/structr/rest/resource/TransformationResource.java
dlaske/structr
e829a57d42c1b82774ef4d61b816fef6f1950846
[ "IJG", "ADSL" ]
null
null
null
structr-rest/src/main/java/org/structr/rest/resource/TransformationResource.java
dlaske/structr
e829a57d42c1b82774ef4d61b816fef6f1950846
[ "IJG", "ADSL" ]
null
null
null
structr-rest/src/main/java/org/structr/rest/resource/TransformationResource.java
dlaske/structr
e829a57d42c1b82774ef4d61b816fef6f1950846
[ "IJG", "ADSL" ]
null
null
null
32.63
148
0.757585
998,861
/** * Copyright (C) 2010-2015 Morgner UG (haftungsbeschränkt) * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.rest.resource; import org.structr.common.PagingHelper; import org.structr.core.Result; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.structr.core.property.PropertyKey; import org.structr.common.SecurityContext; import org.structr.common.error.FrameworkException; import org.structr.core.GraphObject; import org.structr.core.ViewTransformation; import org.structr.core.graph.NodeFactory; /** * * @author Christian Morgner */ public class TransformationResource extends WrappingResource { private ViewTransformation transformation = null; public TransformationResource(SecurityContext securityContext, ViewTransformation transformation) { this.securityContext = securityContext; this.transformation = transformation; } @Override public boolean checkAndConfigure(String part, SecurityContext securityContext, HttpServletRequest request) throws FrameworkException { return false; // no direct instantiation } @Override public Result doGet(PropertyKey sortKey, boolean sortDescending, int pageSize, int page, String offsetId) throws FrameworkException { if(wrappedResource != null && transformation != null) { // allow view transformation to avoid evaluation of wrapped resource if (transformation.evaluateWrappedResource()) { Result result = wrappedResource.doGet(sortKey, sortDescending, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE, null); try { transformation.apply(securityContext, result.getResults()); result.setRawResultCount(result.size()); } catch(Throwable t) { t.printStackTrace(); } // apply paging later return PagingHelper.subResult(result, pageSize, page, offsetId); } else { List<? extends GraphObject> listToTransform = new LinkedList<GraphObject>(); transformation.apply(securityContext, listToTransform); Result result = new Result(listToTransform, listToTransform.size(), wrappedResource.isCollectionResource(), wrappedResource.isPrimitiveArray()); // apply paging later return PagingHelper.subResult(result, pageSize, page, offsetId); } } List emptyList = Collections.emptyList(); return new Result(emptyList, null, isCollectionResource(), isPrimitiveArray()); } @Override public String getResourceSignature() { if(wrappedResource != null) { return wrappedResource.getResourceSignature(); } return ""; } }
9239897be680b3880d376eb71b56857c2833f116
11,596
java
Java
2019-03-24/SDK_java/code/CodeCraft-2019/src/main/java/com/huawei/problem/Road.java
gdhucoder/hwcodecraft
c08298c8f9cb80963ac4e04dde242a6e1c8e1345
[ "MIT" ]
null
null
null
2019-03-24/SDK_java/code/CodeCraft-2019/src/main/java/com/huawei/problem/Road.java
gdhucoder/hwcodecraft
c08298c8f9cb80963ac4e04dde242a6e1c8e1345
[ "MIT" ]
null
null
null
2019-03-24/SDK_java/code/CodeCraft-2019/src/main/java/com/huawei/problem/Road.java
gdhucoder/hwcodecraft
c08298c8f9cb80963ac4e04dde242a6e1c8e1345
[ "MIT" ]
null
null
null
23.958678
102
0.571231
998,862
package com.huawei.problem; import com.huawei.basic.StdOut; import java.util.Arrays; import static com.huawei.Constants.*; /** * Created by HuGuodong on 2019/3/13. */ public final class Road { public static final String PROVIDE = "provide"; public static final String RECEIVE = "receive"; public static final String BACKWARD = "backward"; public static final String FORWARD = "forward"; int id; int length; int speed; int channel; int from; // cross id int to; // cross id boolean isDuplex; // 是否双向 int carCapacity; int[][] forwardBucket; int[][] backwardBucket; int[] fx, fy, bx, by, forwardNum, backwardNum; boolean[] forwardDone, backwardDone; int[][] provideBucket; int[][] receiveBucket; int[] px, py, provideNum, receiveNum; boolean[] provideDone; public Road(int id, int length, int speed, int channel, int from, int to, int isDuplex) { // 静态参数 this.id = id; this.length = length; this.speed = speed; this.channel = channel; this.from = from; this.to = to; this.isDuplex = isDuplex == 1 ? true : false; // 路的容量 this.carCapacity = length * channel; // 动态参数 // absolute bucket this.forwardBucket = new int[length][channel]; for (int[] f : forwardBucket) { Arrays.fill(f, NONE); } if (this.isDuplex) { this.backwardBucket = new int[length][channel]; for (int[] b : backwardBucket) { Arrays.fill(b, NONE); } } fx = new int[1]; fy = new int[1]; bx = new int[1]; by = new int[1]; this.forwardNum = new int[1]; this.backwardNum = new int[1]; this.forwardDone = new boolean[1]; this.backwardDone = new boolean[1]; // relative bucket this.provideBucket = null; this.receiveBucket = null; this.px = null; this.py = null; this.provideNum = null; this.receiveNum = null; this.provideDone = null; } public String chooseAbsoluteBucket(int crossId, String pr) { if (crossId == this.from && pr.equals(PROVIDE)) { return BACKWARD; } else if (crossId == this.from && pr.equals(RECEIVE)) { return FORWARD; } else if (crossId == this.to && pr.equals(PROVIDE)) { return FORWARD; } else if (crossId == this.to && pr.equals(RECEIVE)) { return BACKWARD; } else { System.out.println("mistake in chooseAbsoluteBucket"); return null; } } public void setBucket(int crossId) { String bucket = chooseAbsoluteBucket(crossId, PROVIDE); if (bucket.equals(FORWARD)) { provideBucket = forwardBucket; px = fx; py = fy; provideNum = forwardNum; provideDone = forwardDone; if (isDuplex) { // 双向路 receiveBucket = backwardBucket; receiveNum = backwardNum; } else { receiveBucket = null; receiveNum = null; } } else if(bucket.equals(BACKWARD)) { receiveBucket = forwardBucket; receiveNum = forwardNum; if (isDuplex) { provideBucket = backwardBucket; px = bx; py = by; provideDone = backwardDone; provideNum = backwardNum; } else { provideBucket = null; px = null; py = null; provideDone = null; provideNum = null; } } } public void stepInit() { // dynamic param initialization fx[0] = 0; fy[0] = 0; bx[0] = 0; by[0] = 0; forwardDone[0] = false; backwardDone[0] = false; provideBucket = null; receiveBucket = null; px = null; py = null; provideNum = null; receiveNum = null; provideDone = null; // 车状态初始化 for (int i = 0; i < this.length; i++) { for (int j = 0; j < this.channel; j++) { if (this.forwardBucket[i][j] != NONE) { CarRoute forwardCar = CAR_ROUTE_MAP.get(String.valueOf(forwardBucket[i][j])); // 更新车的状态为等待 forwardCar.updateDynamic(WAITING, MINUS_ONE, MINUS_ONE, MINUS_ONE, MINUS_ONE); } if (this.isDuplex) { // 双向路 if (this.backwardBucket[i][j] != NONE) { CarRoute backwardCar = CAR_ROUTE_MAP.get(String.valueOf(backwardBucket[i][j])); backwardCar.updateDynamic(WAITING, MINUS_ONE, MINUS_ONE, MINUS_ONE, MINUS_ONE); } } } } // first step for (int chnl = 0; chnl < this.channel; chnl++) { this.moveInChannel(this.forwardBucket, chnl); if (this.isDuplex) { this.moveInChannel(this.backwardBucket, chnl); } } } public void moveInChannel(int[][] bucket, int channel) { // car state: 0,1,2,3 in carport,waiting,finishing,end // set guard int previousCar = NONE; int previousState = WAITING; for (int i = 0; i < this.length; i++) { if (bucket[i][channel] != NONE) { CarRoute car = CAR_ROUTE_MAP.get(String.valueOf(bucket[i][channel])); int v = Math.min(car.speed, this.speed); if (car.state == FINISHING) { previousCar = i; previousState = FINISHING; continue; } else if ((i - v) > previousCar) { bucket[i - v][channel] = bucket[i][channel]; bucket[i][channel] = NONE; previousCar = i - v; previousState = FINISHING; // 2 car.updateDynamic(FINISHING, previousCar, MINUS_ONE, MINUS_ONE, MINUS_ONE); } else if (previousState == FINISHING) { if ((previousCar + 1) != i) { bucket[previousCar + 1][channel] = bucket[i][channel]; bucket[i][channel] = NONE; } previousCar = previousCar + 1; previousState = FINISHING; car.updateDynamic(FINISHING, previousCar, MINUS_ONE, MINUS_ONE, MINUS_ONE); } else { previousCar = i; previousState = WAITING; } } } } /** * 找到一条通道上车的位置 i: 5 ,4 ,3 ,... * * @param start * @param end * @param channel * @param bucket * @return */ public int findCar(int start, int end, int channel, int[][] bucket) { for (int i = end; i > start; i--) { if (bucket[i][channel] != NONE) { return i; } } return NONE; } public int findPriorityCar() { if (this.provideBucket == null) { System.out.println("please do Car.setBucket() first"); } while (this.px[0] < this.length) { int carId = this.provideBucket[this.px[0]][this.py[0]]; if (carId != NONE && CAR_ROUTE_MAP.get(String.valueOf(carId)).state != FINISHING) { CarRoute car = CAR_ROUTE_MAP.get(String.valueOf(carId)); int left = Math.min(car.speed, this.speed); // 车的速度足够 并且 该车前方无车 if (left > this.px[0] && this.findCar(-1, this.px[0] - 1, this.py[0], this.provideBucket) == NONE) { return this.provideBucket[this.px[0]][this.py[0]]; } } if (this.py[0] == this.channel - 1) { this.px[0] = this.px[0] + 1; this.py[0] = 0; } else { this.py[0] += 1; } } this.provideDone[0] = true; return NONE; } public void firstPriorityCarAct(int action) { if (provideBucket == null) { System.out.println("Please do CAR.setBucket() first!"); } if (action == 0) { provideBucket[px[0]][py[0]] = NONE; provideNum[0] -= 1; } else if (action == 1) { int carId = provideBucket[px[0]][py[0]]; provideBucket[px[0]][py[0]] = NONE; provideBucket[0][py[0]] = carId; } this.moveInChannel(this.provideBucket, this.py[0]); } public int receiveCar(int carId) { if (this.receiveBucket == null) { System.out.println("Please do CAR.setBucket() first!"); } CarRoute car = CAR_ROUTE_MAP.get(String.valueOf(carId)); int leftX = Math.min(this.speed, car.speed) - car.x; // StdOut.printf("%d: %d %d %d\n",leftX, this.speed, car.speed, car.x); int nextCrossId = NONE; if (car.getNextCrossId() != this.from) { nextCrossId = this.from; } else { nextCrossId = this.to; } if (leftX <= 0) { car.updateDynamic(FINISHING, 0, MINUS_ONE, MINUS_ONE, MINUS_ONE); return 1; // ? 什么意思 } for (int c = 0; c < this.channel; c++) { int frontCarLoc = this.findCar(this.length - leftX - 1, this.length - 1, c, this.receiveBucket); if (frontCarLoc == NONE) { this.receiveBucket[this.length - leftX][c] = carId; this.receiveNum[0] += 1; car.updateDynamic(FINISHING, this.length - leftX, c, this.id, nextCrossId); return 0; } CarRoute frontCar = CAR_ROUTE_MAP.get(String.valueOf(this.receiveBucket[frontCarLoc][c])); if (frontCar.state == WAITING) { return 2; // ? } else if (frontCarLoc != this.length - 1) { this.receiveBucket[frontCarLoc + 1][c] = carId; this.receiveNum[0] += 1; car.updateDynamic(FINISHING, frontCarLoc + 1, c, this.id, nextCrossId); return 0; } else { continue; } } // if road is full car.updateDynamic(FINISHING, 0, MINUS_ONE, MINUS_ONE, MINUS_ONE); return 1; // ? } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getChannel() { return channel; } public void setChannel(int channel) { this.channel = channel; } public int getFrom() { return from; } public void setFrom(int from) { this.from = from; } public int getTo() { return to; } public void setTo(int to) { this.to = to; } public boolean isDuplex() { return isDuplex; } public void setDuplex(boolean duplex) { isDuplex = duplex; } public int getCarCapacity() { return carCapacity; } public int[][] getForwardBucket() { return forwardBucket; } public int[][] getBackwardBucket() { return backwardBucket; } public int[] getFx() { return fx; } public int[] getFy() { return fy; } public int[] getBx() { return bx; } public int[] getBy() { return by; } public int[] getForwardNum() { return forwardNum; } public int[] getBackwardNum() { return backwardNum; } public boolean[] getForwardDone() { return forwardDone; } public boolean[] getBackwardDone() { return backwardDone; } public int[][] getProvideBucket() { return provideBucket; } public int[][] getReceiveBucket() { return receiveBucket; } public int[] getPx() { return px; } public int[] getPy() { return py; } public int[] getProvideNum() { return provideNum; } public int[] getReceiveNum() { return receiveNum; } public boolean[] getProvideDone() { return provideDone; } public void showCars(int[][] bucket){ StdOut.println(TIME[0]+ "====================="+this.from +","+ this.to); StdOut.println(fx[0] +"," + fy[0]); for (int i = 0; i < bucket.length; i++) { for (int j = 0; j < bucket[i].length; j++) { StdOut.printf("%4d ", bucket[i][j]); } StdOut.println(); } } @Override public String toString() { return "Road{" + "id=" + id + ", length=" + length + ", speed=" + speed + ", channel=" + channel + ", from=" + from + ", to=" + to + ", isDuplex=" + isDuplex + '}'; } }
9239898f174897fbfadbdda841ec56e5cada44d5
9,554
java
Java
AL-Game/data/scripts/system/handlers/ai/instance/rentusBase/InfernalKuharaTheVolatileAI2.java
karllgiovany/Aion-Lightning-4.9-SRC
05beede3382ec7dbdabb2eb9f76e4e42d046ff59
[ "FTL" ]
1
2019-04-05T22:44:56.000Z
2019-04-05T22:44:56.000Z
AL-Game/data/scripts/system/handlers/ai/instance/rentusBase/InfernalKuharaTheVolatileAI2.java
korssar2008/Aion-Lightning-4.9
05beede3382ec7dbdabb2eb9f76e4e42d046ff59
[ "FTL" ]
null
null
null
AL-Game/data/scripts/system/handlers/ai/instance/rentusBase/InfernalKuharaTheVolatileAI2.java
korssar2008/Aion-Lightning-4.9
05beede3382ec7dbdabb2eb9f76e4e42d046ff59
[ "FTL" ]
1
2017-12-28T16:59:47.000Z
2017-12-28T16:59:47.000Z
35.917293
107
0.690287
998,863
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package ai.instance.rentusBase; import ai.AggressiveNpcAI2; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import com.aionemu.commons.network.util.ThreadPoolManager; import com.aionemu.commons.utils.Rnd; import com.aionemu.gameserver.ai2.AI2Actions; import com.aionemu.gameserver.ai2.AIName; import com.aionemu.gameserver.ai2.AIState; import com.aionemu.gameserver.ai2.manager.EmoteManager; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.geometry.Point3D; import com.aionemu.gameserver.services.NpcShoutsService; import com.aionemu.gameserver.skillengine.SkillEngine; import com.aionemu.gameserver.world.WorldPosition; /** * @author xTz */ @AIName("infernal_kuhara_the_volatile") //236298 public class InfernalKuharaTheVolatileAI2 extends AggressiveNpcAI2 { private boolean canThink = true; private Future<?> bombEventTask; private Future<?> activeEventTask; private Future<?> barrelEventTask; private Phase phase = Phase.ACTIVE; private AtomicBoolean isHome = new AtomicBoolean(true); private enum Phase { ACTIVE, BOMBS, } @Override public boolean canThink() { return canThink; } @Override public void handleAttack(Creature creature) { super.handleAttack(creature); if (isHome.compareAndSet(true, false)) { getPosition().getWorldMapInstance().getDoors().get(43).setOpen(true); getPosition().getWorldMapInstance().getDoors().get(150).setOpen(false); NpcShoutsService.getInstance().sendMsg(getOwner(), 1500393, getObjectId(), 0, 0); startActivEvent(); startBarrelEvent(); } } private void cancelActiveEventTask() { if (activeEventTask != null && !activeEventTask.isDone()) { activeEventTask.cancel(true); } } private void cancelBarrelEventTask() { if (barrelEventTask != null && !barrelEventTask.isDone()) { barrelEventTask.cancel(true); } } private void cancelBombEventTask() { if (bombEventTask != null && !bombEventTask.isDone()) { bombEventTask.cancel(true); } } private void startBarrelEvent() { barrelEventTask = ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable() { @Override public void run() { if (isAlreadyDead()) { cancelBarrelEventTask(); } else { switch(Rnd.get(1, 4)) { case 1: rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(126.528755f, 274.48883f, 209.81859f)); rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(126.528755f, 274.48883f, 209.81859f)); break; case 2: rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(162.22261f, 263.89288f, 209.81859f)); rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(162.22261f, 263.89288f, 209.81859f)); break; case 3: rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(156.32321f, 235.733f, 209.81859f)); rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(156.32321f, 235.733f, 209.81859f)); break; case 4: rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(119.23888f, 245.8903f, 209.81859f)); rndSpawnInRange(282394, Rnd.get(1, 4), new Point3D(119.23888f, 245.8903f, 209.81859f)); break; } startBombEvent(); } } }, 15000, 15000); } private void startBombEvent() { bombEventTask = ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isHome.get() && phase.equals(Phase.ACTIVE)) { phase = Phase.BOMBS; cancelActiveEventTask(); NpcShoutsService.getInstance().sendMsg(getOwner(), 1500394, getObjectId(), 0, 0); canThink = false; EmoteManager.emoteStopAttacking(getOwner()); setStateIfNot(AIState.WALKING); SkillEngine.getInstance().getSkill(getOwner(), 19703, 60, getOwner()).useNoAnimationSkill(); spawnBombEvent(); bombEventTask = ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isHome.get() && phase.equals(Phase.BOMBS)) { phase = Phase.ACTIVE; canThink = true; Creature creature = getAggroList().getMostHated(); if (creature == null || creature.getLifeStats().isAlreadyDead() || !getOwner().canSee(creature)) { setStateIfNot(AIState.FIGHT); think(); } else { getMoveController().abortMove(); getOwner().setTarget(creature); getOwner().getGameStats().renewLastAttackTime(); getOwner().getGameStats().renewLastAttackedTime(); getOwner().getGameStats().renewLastChangeTargetTime(); getOwner().getGameStats().renewLastSkillTime(); setStateIfNot(AIState.FIGHT); handleMoveValidate(); SkillEngine.getInstance().getSkill(getOwner(), 19375, 60, getOwner()).useNoAnimationSkill(); } deleteNpcs(getPosition().getWorldMapInstance().getNpcs(282396)); //Kuhara Bomb. } } }, 11000); } } }, 14000); } private void deleteNpcs(List<Npc> npcs) { for (Npc npc : npcs) { if (npc != null) { npc.getController().onDelete(); } } } private void spawnBombEvent() { MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(126.528755f, 274.48883f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(126.528755f, 274.48883f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(162.22261f, 263.89288f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(162.22261f, 263.89288f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(156.32321f, 235.733f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(156.32321f, 235.733f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(119.23888f, 245.8903f, 209.81859f))); MoveBombToBoss(rndSpawnInRange(282396, Rnd.get(0, 2), new Point3D(119.23888f, 245.8903f, 209.81859f))); } private void MoveBombToBoss(final Npc npc) { if (!isAlreadyDead() && !isHome.get() ) { npc.setTarget(getOwner()); npc.getMoveController().moveToTargetObject(); } } private Npc rndSpawnInRange(int npcId, float distance, Point3D position) { float direction = Rnd.get(0, 199) / 100f; float x1 = (float) (Math.cos(Math.PI * direction) * distance); float y1 = (float) (Math.sin(Math.PI * direction) * distance); return (Npc) spawn(npcId, position.getX() + x1, position.getY() + y1, position.getZ(), (byte) 0); } private void startActivEvent() { activeEventTask = ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable() { @Override public void run() { if (isAlreadyDead()) { cancelActiveEventTask(); } else { NpcShoutsService.getInstance().sendMsg(getOwner(), 1500395, getObjectId(), 0, 0); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isHome.get() && phase.equals(Phase.ACTIVE)) { SkillEngine.getInstance().getSkill(getOwner(), 19704, 60, getOwner()).useNoAnimationSkill(); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isHome.get() && phase.equals(Phase.ACTIVE)) { SkillEngine.getInstance().getSkill(getOwner(), 19705, 60, getOwner()).useNoAnimationSkill(); } } }, 3500); } } }, 1000); } } }, 8000, 14000); } @Override protected void handleDespawned() { super.handleDespawned(); cancelActiveEventTask(); cancelBarrelEventTask(); cancelBombEventTask(); } @Override protected void handleBackHome() { isHome.set(true); phase = Phase.ACTIVE; canThink = true; cancelActiveEventTask(); cancelBarrelEventTask(); cancelBombEventTask(); getPosition().getWorldMapInstance().getDoors().get(43).setOpen(false); getPosition().getWorldMapInstance().getDoors().get(150).setOpen(true); super.handleBackHome(); } @Override protected void handleDied() { cancelActiveEventTask(); cancelBarrelEventTask(); cancelBombEventTask(); final WorldPosition p = getPosition(); if (p != null) { deleteNpcs(p.getWorldMapInstance().getNpcs(282394)); //Oil Cask. deleteNpcs(p.getWorldMapInstance().getNpcs(282395)); //Spilled Oil. deleteNpcs(p.getWorldMapInstance().getNpcs(282396)); //Kuhara Bomb. spawn(236705, p.getX(), p.getY(), p.getZ(), p.getHeading()); //Infernal Kuhara Treasure Box. p.getWorldMapInstance().getDoors().get(43).setOpen(false); p.getWorldMapInstance().getDoors().get(150).setOpen(true); } super.handleDied(); AI2Actions.deleteOwner(this); } }
92398a4037ddb82659e4a89626d918616df1f616
5,016
java
Java
integration/automation-extensions/src/main/java/org/wso2/esb/integration/common/extensions/coordination/CoordinationDatabase.java
moooooooo/micro-integrator
9620bafce3b8fd01c4fe8def3f5931032fcb8706
[ "Apache-2.0" ]
null
null
null
integration/automation-extensions/src/main/java/org/wso2/esb/integration/common/extensions/coordination/CoordinationDatabase.java
moooooooo/micro-integrator
9620bafce3b8fd01c4fe8def3f5931032fcb8706
[ "Apache-2.0" ]
null
null
null
integration/automation-extensions/src/main/java/org/wso2/esb/integration/common/extensions/coordination/CoordinationDatabase.java
moooooooo/micro-integrator
9620bafce3b8fd01c4fe8def3f5931032fcb8706
[ "Apache-2.0" ]
null
null
null
35.574468
107
0.648525
998,864
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.esb.integration.common.extensions.coordination; import com.moandjiezana.toml.Toml; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.engine.extensions.ExecutionListenerExtension; import java.io.File; import java.net.URI; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CoordinationDatabase extends ExecutionListenerExtension { private static final Log logger = LogFactory.getLog(CoordinationDatabase.class); private String dbName; private String scriptPath; private static String connectionUrl; private static String pwd; private static String userName; @Override public void initiate() throws AutomationFrameworkException { logger.info("Initializing coordination database."); populateParameters(); } @Override public void onExecutionStart() throws AutomationFrameworkException { String dbUrl = connectionUrl.replace("/" + dbName, "").concat("&allowMultiQueries=true"); scriptPath = getSystemDependentPath(scriptPath); File file = new File(scriptPath); try { List<String> schema = new ArrayList<>(); schema.add("drop database if exists " + dbName + ";"); schema.add("create database " + dbName + " character set latin1;"); schema.add("use " + dbName + ";"); schema.add(FileUtils.readFileToString(file, StandardCharsets.UTF_8)); try (Connection conn = DriverManager.getConnection(dbUrl, userName, pwd); PreparedStatement preparedStatement = conn.prepareStatement(String.join("", schema))) { preparedStatement.executeUpdate(); } logger.info("Coordination database configured successfully."); } catch (Exception ex) { throw new AutomationFrameworkException(ex); } } @Override public void onExecutionFinish() { // do nothing. } private static String getSystemDependentPath(String path) { return path.replace('/', File.separatorChar); } private void populateParameters() throws AutomationFrameworkException { Map<String, String> parameters = getParameters(); for (Map.Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); switch (key) { case "toml-path": parseToml(value); break; case "script-path": scriptPath = value; break; default: logger.error("Unknown property : " + key); break; } } } private void parseToml(String filePath) throws AutomationFrameworkException { File toml = new File(filePath); if (!toml.exists()) { throw new AutomationFrameworkException("File not found in : " + filePath); } try { Toml parseToml = new Toml().read(toml); String datasourceId = parseToml.getString("datasource[0].id"); if (!"WSO2_COORDINATION_DB".equals(datasourceId)) { throw new AutomationFrameworkException( "Coordination db is not defined in toml or not added as first datasource."); } connectionUrl = parseToml.getString("datasource[0].url").replaceAll("amp;", ""); userName = parseToml.getString("datasource[0].username"); pwd = parseToml.getString("datasource[0].password"); URI uri = URI.create(connectionUrl.substring(5)); dbName = uri.getPath().replace("/", ""); } catch (Exception ex) { throw new AutomationFrameworkException(ex); } } public static String getConnectionUrl() { return connectionUrl; } public static String getUserName() { return userName; } public static String getPwd() { return pwd; } }
92398b13cb144bbd11ab5dc56070fa90e3285ed3
447
java
Java
app/src/main/java/com/shell/hacks/ui/chat/ChatViewModel.java
NilanL/ShellHacks-social-good-test
2b732da5b914f3f9760dbe016ca9f25e6f83e4d1
[ "Apache-2.0" ]
2
2021-09-25T03:44:21.000Z
2021-09-25T03:47:07.000Z
app/src/main/java/com/shell/hacks/ui/chat/ChatViewModel.java
singinzrain/ShellHacks-social-good
5e2e540374d92c8d984cd3a5e1998d933ba7678f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shell/hacks/ui/chat/ChatViewModel.java
singinzrain/ShellHacks-social-good
5e2e540374d92c8d984cd3a5e1998d933ba7678f
[ "Apache-2.0" ]
1
2021-09-27T13:46:34.000Z
2021-09-27T13:46:34.000Z
23.526316
57
0.715884
998,865
package com.shell.hacks.ui.chat; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class ChatViewModel extends ViewModel { private MutableLiveData<String> mText; public ChatViewModel() { mText = new MutableLiveData<>(); mText.setValue("This is notifications fragment"); } public LiveData<String> getText() { return mText; } }
92398ba6594661f10567f2a0890bcd0a36b478ee
627
java
Java
Src/src/utility/ExceptionUtility.java
eunhyepark/eunhye
7b4324243bf0e0d0b71675c440f7d4f61038c592
[ "Apache-2.0" ]
24
2015-01-22T02:34:50.000Z
2018-10-17T07:07:22.000Z
Src/src/utility/ExceptionUtility.java
DerekGrant/GKLDA
7a8d787e2223dde782a4e20f21f370029f65ba19
[ "Apache-2.0" ]
1
2020-05-12T16:47:42.000Z
2020-05-12T16:47:42.000Z
Src/src/utility/ExceptionUtility.java
DerekGrant/GKLDA
7a8d787e2223dde782a4e20f21f370029f65ba19
[ "Apache-2.0" ]
30
2015-01-06T08:02:22.000Z
2021-11-07T13:04:42.000Z
21.62069
74
0.720893
998,866
package utility; public class ExceptionUtility { public static void throwAndCatchException(String message) { try { throw new Exception(message); } catch (Exception ex) { ex.printStackTrace(); } } /** * Implement a customized assertion that can pop up as an exception. */ public static void assertAsException(boolean statement) { if (!statement) { ExceptionUtility .throwAndCatchException("The assertion statement is not true!"); } } public static void assertAsException(boolean statement, String message) { if (!statement) { ExceptionUtility.throwAndCatchException(message); } } }
92398c1260d58087d279d686b3bd73ab556aff78
1,525
java
Java
src/main/java/com/windypaddy/tlinker/Export.java
wdpd/tlinker
b1927cd6d8c282b91b0ed35d81ac63d7d806b499
[ "Apache-2.0" ]
null
null
null
src/main/java/com/windypaddy/tlinker/Export.java
wdpd/tlinker
b1927cd6d8c282b91b0ed35d81ac63d7d806b499
[ "Apache-2.0" ]
null
null
null
src/main/java/com/windypaddy/tlinker/Export.java
wdpd/tlinker
b1927cd6d8c282b91b0ed35d81ac63d7d806b499
[ "Apache-2.0" ]
null
null
null
32.446809
122
0.615738
998,867
package com.windypaddy.tlinker; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class Export { private final ExportParameters parameters; private final IO io; private final Torrent torrent; public Export (ExportParameters parameters_, IO io_) throws IOException { parameters = parameters_; io = io_; torrent = new Torrent(parameters.torrent, true); } public void start () throws IOException, SQLException, DatabaseException { Tree tree = new Tree(new TreeParameters(parameters.torrent, parameters.destination, false, parameters.quiet), io); tree.start(); ArrayList<Path> failedFiles = new ArrayList<>(); try (Database database = new Database(null)) { database.check(); for (TorrentFile torrentFile : torrent.files) { List<Path> paths = database.findRepo(torrent.torrentHash, torrent.files.indexOf(torrentFile)); if (!paths.isEmpty()) { Files.createSymbolicLink(parameters.destination.resolve(torrentFile.file.path), paths.get(0)); } else { failedFiles.add(torrentFile.file.path); } } } if (!failedFiles.isEmpty()) { io.failedLinks(); for (Path path : failedFiles) { io.path(path, true); } } } }
92398c20e2fe55973629ad9e330d3a35afa16401
786
java
Java
modules/platform/srs-platform-rest-module/src/main/java/org/systems/dipe/srs/platform/external/SearchProcessFacade.java
chirkovd/srs-platform
41f35c60084fc8967e289b2de9e66634e113b8cb
[ "Apache-2.0" ]
null
null
null
modules/platform/srs-platform-rest-module/src/main/java/org/systems/dipe/srs/platform/external/SearchProcessFacade.java
chirkovd/srs-platform
41f35c60084fc8967e289b2de9e66634e113b8cb
[ "Apache-2.0" ]
16
2022-02-19T05:38:31.000Z
2022-03-31T08:31:53.000Z
modules/platform/srs-platform-rest-module/src/main/java/org/systems/dipe/srs/platform/external/SearchProcessFacade.java
chirkovd/srs-platform
41f35c60084fc8967e289b2de9e66634e113b8cb
[ "Apache-2.0" ]
null
null
null
37.428571
95
0.811705
998,868
package org.systems.dipe.srs.platform.external; import org.systems.dipe.srs.platform.locations.in.CommentInDto; import org.systems.dipe.srs.platform.locations.in.PointInDto; import org.systems.dipe.srs.platform.search.SearchProcessRequest; import org.systems.dipe.srs.platform.search.out.SearchProcessOutDto; public interface SearchProcessFacade { SearchProcessOutDto search(SearchProcessRequest request); void joinSquad(String searchId, String squadId, String volunteerId); void approveSquad(String searchId, String supervisorId); void addPoint(PointInDto point, String searchId, String volunteerId); void addComment(CommentInDto comment, String searchId, String pointId, String volunteerId); void completeSearch(String searchId, String supervisorId); }
92398d9b240f6bcc812b7cbd6d78db789f8bc825
356
java
Java
MVP/MvpApp-master/app/src/main/java/com/dl7/mvp/module/base/IBasePresenter.java
weiwenqiang/GitHub
a22f3ed254a005a8c8007f677968655620ccd3b1
[ "Apache-2.0" ]
10
2017-11-27T03:18:15.000Z
2021-08-10T07:21:44.000Z
MVP/MvpApp-master/app/src/main/java/com/dl7/mvp/module/base/IBasePresenter.java
lierba64/GitHub
a22f3ed254a005a8c8007f677968655620ccd3b1
[ "Apache-2.0" ]
null
null
null
MVP/MvpApp-master/app/src/main/java/com/dl7/mvp/module/base/IBasePresenter.java
lierba64/GitHub
a22f3ed254a005a8c8007f677968655620ccd3b1
[ "Apache-2.0" ]
10
2018-04-20T08:43:59.000Z
2022-03-16T02:52:53.000Z
15.478261
65
0.587079
998,869
package com.dl7.mvp.module.base; /** * Created by long on 2016/8/23. * 基础 Presenter */ public interface IBasePresenter { /** * 获取网络数据,更新界面 */ /** * 获取网络数据,更新界面 * @param isRefresh 新增参数,用来判断是否为下拉刷新调用,下拉刷新的时候不应该再显示加载界面和异常界面 */ void getData(boolean isRefresh); /** * 加载更多数据 */ void getMoreData(); }
92398e0837da2a45677dfc198daf78e29ced6220
4,040
java
Java
aspects/om-aspects/src/main/java/org/apache/axiom/om/impl/stream/ds/PushOMDataSourceReader.java
isabella232/ws-axiom
7cc750e739d15e12daf9c7cb999f27567af47c29
[ "Apache-2.0", "BSD-3-Clause" ]
4
2019-11-01T15:26:30.000Z
2021-11-08T12:01:01.000Z
aspects/om-aspects/src/main/java/org/apache/axiom/om/impl/stream/ds/PushOMDataSourceReader.java
isabella232/ws-axiom
7cc750e739d15e12daf9c7cb999f27567af47c29
[ "Apache-2.0", "BSD-3-Clause" ]
99
2020-12-21T19:27:00.000Z
2021-09-30T03:22:37.000Z
aspects/om-aspects/src/main/java/org/apache/axiom/om/impl/stream/ds/PushOMDataSourceReader.java
isabella232/ws-axiom
7cc750e739d15e12daf9c7cb999f27567af47c29
[ "Apache-2.0", "BSD-3-Clause" ]
8
2020-04-18T08:22:38.000Z
2021-11-17T00:29:32.000Z
40.808081
112
0.686881
998,870
/* * 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.axiom.om.impl.stream.ds; import java.util.Iterator; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.axiom.core.stream.StreamException; import org.apache.axiom.core.stream.XmlHandler; import org.apache.axiom.core.stream.XmlHandlerWrapper; import org.apache.axiom.core.stream.XmlReader; import org.apache.axiom.core.stream.stax.push.XmlHandlerStreamWriter; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMDataSource; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.impl.intf.AxiomSourcedElement; import org.apache.axiom.om.impl.stream.XmlDeclarationRewriterHandler; import org.apache.axiom.om.impl.stream.stax.push.AxiomXMLStreamWriterExtensionFactory; final class PushOMDataSourceReader implements XmlReader { private final XmlHandler handler; private final AxiomSourcedElement root; private final OMDataSource dataSource; PushOMDataSourceReader(XmlHandler handler, AxiomSourcedElement root, OMDataSource dataSource) { this.handler = handler; this.root = root; this.dataSource = dataSource; } @Override public boolean proceed() throws StreamException { // TODO: we might want to unwrap the NamespaceRepairingFilter (and some other filters) here XmlHandler handler = this.handler; OMOutputFormat format = null; XmlHandler current = handler; while (current instanceof XmlHandlerWrapper) { if (current instanceof XmlDeclarationRewriterHandler) { format = ((XmlDeclarationRewriterHandler)current).getFormat(); break; } current = ((XmlHandlerWrapper)current).getParent(); } if (format == null) { // This is for the OMSourcedElement expansion case format = new OMOutputFormat(); format.setDoOptimize(true); handler = new PushOMDataSourceXOPHandler(handler); } try { XMLStreamWriter writer = new XmlHandlerStreamWriter(handler, null, AxiomXMLStreamWriterExtensionFactory.INSTANCE); // Seed the namespace context with the namespace context from the parent OMContainer parent = root.getParent(); if (parent instanceof OMElement) { for (Iterator<OMNamespace> it = ((OMElement)parent).getNamespacesInScope(); it.hasNext(); ) { OMNamespace ns = it.next(); writer.setPrefix(ns.getPrefix(), ns.getNamespaceURI()); } } handler.startFragment(); dataSource.serialize(new MTOMXMLStreamWriterImpl(new PushOMDataSourceStreamWriter(writer), format)); handler.completed(); } catch (XMLStreamException ex) { Throwable cause = ex.getCause(); if (cause instanceof StreamException) { throw (StreamException)cause; } else { throw new StreamException(ex); } } return true; } @Override public void dispose() { } }
92398f5658f466b3a13ddd9471e52cfb3ef87184
191
java
Java
src/test/java/com/my/project/spring/wsdl2java/package-info.java
yddgit/hello-cxf
b960f28ce11e4f28fd2764866b06e29bcfd096ba
[ "Apache-2.0" ]
null
null
null
src/test/java/com/my/project/spring/wsdl2java/package-info.java
yddgit/hello-cxf
b960f28ce11e4f28fd2764866b06e29bcfd096ba
[ "Apache-2.0" ]
null
null
null
src/test/java/com/my/project/spring/wsdl2java/package-info.java
yddgit/hello-cxf
b960f28ce11e4f28fd2764866b06e29bcfd096ba
[ "Apache-2.0" ]
null
null
null
63.666667
148
0.801047
998,871
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.org/calc", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.my.project.spring.wsdl2java;
92398fe9d43e084df6fd526b6ce225a41cd2983b
689
java
Java
ingest/vines/com.ibm.streamsx.health.vines/src/main/java/com/ibm/streamsx/health/vines/model/WaveformHelper.java
shusseyIBM/hcd
80e3f4b1e55aba0d5c71d3a326275248ef4e4032
[ "Apache-2.0" ]
45
2016-06-23T21:47:52.000Z
2021-09-06T02:44:51.000Z
ingest/vines/com.ibm.streamsx.health.vines/src/main/java/com/ibm/streamsx/health/vines/model/WaveformHelper.java
shusseyIBM/hcd
80e3f4b1e55aba0d5c71d3a326275248ef4e4032
[ "Apache-2.0" ]
107
2016-06-23T21:49:16.000Z
2020-07-10T13:01:28.000Z
ingest/vines/com.ibm.streamsx.health.vines/src/main/java/com/ibm/streamsx/health/vines/model/WaveformHelper.java
shusseyIBM/hcd
80e3f4b1e55aba0d5c71d3a326275248ef4e4032
[ "Apache-2.0" ]
48
2016-12-01T23:05:38.000Z
2021-12-14T17:11:56.000Z
27.56
81
0.557329
998,872
/******************************************************************************* * Copyright (C) 2017 International Business Machines Corporation * All Rights Reserved *******************************************************************************/ package com.ibm.streamsx.health.vines.model; import java.util.ArrayList; import java.util.List; public class WaveformHelper { private static final String SEP = "\\^"; public static List<Double> parseWaveform(String waveform) { List<Double> numericValues = new ArrayList<Double>(); String[] values = waveform.split(SEP); for(String v : values) { numericValues.add(Double.valueOf(v)); } return numericValues; } }
9239908fc95d4eb64e4387d9fd2ea2219f370580
945
java
Java
src/main/java/net/algorithm/answer/Interleave.java
TieJianKuDan/algorithm
8f7cb9de5ec71e4ba83cc82d3a45f405c2958987
[ "MIT" ]
null
null
null
src/main/java/net/algorithm/answer/Interleave.java
TieJianKuDan/algorithm
8f7cb9de5ec71e4ba83cc82d3a45f405c2958987
[ "MIT" ]
1
2022-03-04T05:54:00.000Z
2022-03-04T05:54:00.000Z
src/main/java/net/algorithm/answer/Interleave.java
TieJianKuDan/algorithm
8f7cb9de5ec71e4ba83cc82d3a45f405c2958987
[ "MIT" ]
null
null
null
29.53125
103
0.426455
998,873
package net.algorithm.answer; /** * @Author TieJianKuDan * @Date 2021/9/22 10:20 * @Description 97. 交错字符串 * @Since version-1.0 */ public class Interleave { public static void main(String[] args) { } public boolean isInterleave(String s1, String s2, String s3) { if (s1.length() + s2.length() != s3.length()) { return false; } boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { if (j == 0 && i == 0) { dp[i][j] = true; } else { dp[i][j] = (i > 0 && dp[i - 1][j] && (s1.charAt(i - 1) == s3.charAt(i + j - 1))) || (j > 0 && dp[i][j - 1] && (s2.charAt(j - 1) == s3.charAt(i + j - 1))); } } } return dp[s1.length()][s2.length()]; } }
923990cf521738ad366fe6fc81514fed83c9a4ed
4,271
java
Java
app/src/main/java/com/akasa/kitafit/adapter/ProgramKesehatanAdapter.java
andhikurniawan/KitaFit-MobileApp
e155bef34c06be82ff89f2851a25a650e58e5f3f
[ "MIT" ]
null
null
null
app/src/main/java/com/akasa/kitafit/adapter/ProgramKesehatanAdapter.java
andhikurniawan/KitaFit-MobileApp
e155bef34c06be82ff89f2851a25a650e58e5f3f
[ "MIT" ]
2
2020-10-10T04:04:43.000Z
2020-10-10T04:08:37.000Z
app/src/main/java/com/akasa/kitafit/adapter/ProgramKesehatanAdapter.java
andhikurniawan/KitaFit-MobileApp
e155bef34c06be82ff89f2851a25a650e58e5f3f
[ "MIT" ]
1
2021-08-01T04:59:38.000Z
2021-08-01T04:59:38.000Z
45.924731
116
0.726059
998,874
package com.akasa.kitafit.adapter; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.akasa.kitafit.R; import com.akasa.kitafit.activity.DetailProgramKesehatan; import com.akasa.kitafit.model.ProgramKesehatanData; import com.bumptech.glide.Glide; import java.util.ArrayList; public class ProgramKesehatanAdapter extends RecyclerView.Adapter<ProgramKesehatanAdapter.ViewHolder> { public static final String TAG = "ProgramKesehatanAdapter"; public static final String ID_PROGRAM_KESEHATAN = "com.akasa.kitafit.id_program_kesehatan"; public static final String GAMBAR_PROGRAM_KESEHATAN = "com.akasa.kitafit.gambar_program_kesehatan"; public static final String KALORI_PROGRAM_KESEHATAN = "com.akasa.kitafit.kalori_program_kesehatan"; public static final String NAMA_PROGRAM_KESEHATAN = "com.akasa.kitafit.nama_program_kesehatan"; public static final String DESKRIPSI_PROGRAM_KESEHATAN = "com.akasa.kitafit.deskripsi_program_kesehatan"; Context context; ArrayList<ProgramKesehatanData> list; public ProgramKesehatanAdapter(Context context, ArrayList<ProgramKesehatanData> list) { this.context = context; this.list = list; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.program_kesehatan_items, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { Glide.with(context) .load(list.get(position).getGambar_program()) .centerCrop() .into(holder.gambarProgram); holder.judulProgram.setText(list.get(position).getNama_program()); holder.totalOlahraga.setText(String.valueOf(list.get(position).getTotal_olahraga())); holder.totalKalori.setText(String.valueOf(list.get(position).getTotal_kalori())); holder.durasiProgram.setText(String.valueOf(list.get(position).getDurasi_program())); holder.detailProgram.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: Detail Program : "+list.get(position).getNama_program()); Intent intent = new Intent(context, DetailProgramKesehatan.class); intent.putExtra(ID_PROGRAM_KESEHATAN, String.valueOf(list.get(position).getId_program_kesehatan())); intent.putExtra(GAMBAR_PROGRAM_KESEHATAN, list.get(position).getGambar_program()); intent.putExtra(KALORI_PROGRAM_KESEHATAN, holder.totalKalori.getText().toString()); intent.putExtra(NAMA_PROGRAM_KESEHATAN, holder.judulProgram.getText().toString()); intent.putExtra(DESKRIPSI_PROGRAM_KESEHATAN, list.get(position).getDeskripsi()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); } @Override public int getItemCount() { return list.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView gambarProgram; TextView judulProgram, totalOlahraga, totalKalori, durasiProgram; RelativeLayout detailProgram; public ViewHolder(@NonNull View itemView) { super(itemView); gambarProgram = itemView.findViewById(R.id.foto_program_kesehatan); judulProgram = itemView.findViewById(R.id.judul_program_kesehatan); totalOlahraga = itemView.findViewById(R.id.jumlah_olahraga_program_kesehatan); totalKalori = itemView.findViewById(R.id.jumlah_kalori_program_kesehatan); durasiProgram = itemView.findViewById(R.id.jumlah_durasi_program_kesehatan); detailProgram = itemView.findViewById(R.id.program_kesehatan_relative); } } }
92399277f5cc856dc56b72fbaa9826bd6ba28d50
10,179
java
Java
src/org/seqcode/data/readdb/tools/PairedSAMToReadDB.java
seqcode/seqcode-core
db04b02e257dd460926d1dc5d499128c27ee4594
[ "MIT" ]
4
2017-05-22T18:06:22.000Z
2022-03-28T20:27:40.000Z
src/org/seqcode/data/readdb/tools/PairedSAMToReadDB.java
yztxwd/seqcode-core
51595220bc2fec4e7a2f10ced894b4b3bd8a4cda
[ "MIT" ]
null
null
null
src/org/seqcode/data/readdb/tools/PairedSAMToReadDB.java
yztxwd/seqcode-core
51595220bc2fec4e7a2f10ced894b4b3bd8a4cda
[ "MIT" ]
4
2017-05-24T18:49:49.000Z
2019-05-23T13:58:02.000Z
41.378049
130
0.523332
998,875
package org.seqcode.data.readdb.tools; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import htsjdk.samtools.util.CloseableIterator; import java.io.*; import java.util.*; import org.apache.commons.cli.*; /** * Reads two files of SAM or BAM data and produces output on stdout in the * format expected by ImportHits. Both files must be sorted in the *same order*. * Note that Bowtie (perhaps others) DOES NOT preserve input order perfectly if * it's using multiple processors, so you can only use one processor if you're * going to use this program to pair the reads up (you can however split the * input file and run a separate bowtie on each part). * * Only reads present in both files will be included in the output (on stdout). * * The matching of reads between files is done by stripping "/\d" from the end of the * read name, as reads usually end in /1 or /2. * * Usage: * java PairedSAMToReadDB --left leftreads.bam --right rightreads.bam * * * Options: --nosuboptimal (flag to only take the hits with the minimum number of mismatches) * --uniquehits (flag to only print 1:1 read to hit mappings) * * nosuboptimal is applied before uniquehits * * Output columns are * 1) left chromname * 2) left position * 3) left strand * 4) left readlen * 5) right chromname * 6) right position * 7) right strand * 8) right length * 9) weight * 10) paircode */ public class PairedSAMToReadDB { public static boolean uniqueOnly, filterSubOpt, debug; public static int chunksize = 2000; public static ArrayList<SAMRecord> leftbuffer, rightbuffer; public static CloseableIterator<SAMRecord> leftiter, rightiter; public static void dumpRecords(Collection<SAMRecord> lefts, Collection<SAMRecord> rights) { if (filterSubOpt) { lefts = filterSubOpt(filterNoChrom(lefts)); rights = filterSubOpt(filterNoChrom(rights)); } else { lefts = filterNoChrom(lefts); rights = filterNoChrom(rights); } int mapcount = lefts.size() * rights.size(); if (mapcount == 0) { return; } if (uniqueOnly && mapcount > 1) { return; } float weight = 1 / ((float)mapcount); for (SAMRecord left : lefts) { for (SAMRecord right : rights) { System.out.println(String.format("%s\t%d\t%s\t%d\t%s\t%d\t%s\t%d\t%f\t%d", left.getReferenceName(), left.getReadNegativeStrandFlag() ? left.getAlignmentEnd() : left.getAlignmentStart(), left.getReadNegativeStrandFlag() ? "-" : "+", left.getReadLength(), right.getReferenceName(), right.getReadNegativeStrandFlag() ? right.getAlignmentEnd() : right.getAlignmentStart(), right.getReadNegativeStrandFlag() ? "-" : "+", right.getReadLength(), weight, 1)); } } } public static Collection<SAMRecord> filterNoChrom(Collection<SAMRecord> input) { if (input.size() == 0) { return input; } Collection<SAMRecord> output = new ArrayList<SAMRecord>(); for (SAMRecord r : input) { if (!r.getReferenceName().equals("*")) { if(!uniqueOnly || r.getMappingQuality()!=0) //For BWA output.add(r); } } return output; } public static Collection<SAMRecord> filterSubOpt(Collection<SAMRecord> input) { if (input == null || input.size() ==0) { return input; } int maxqual = SAMRecord.NO_MAPPING_QUALITY; for (SAMRecord r : input) { if (r.getMappingQuality() > maxqual) { maxqual = r.getMappingQuality(); } } Collection<SAMRecord> output = new ArrayList<SAMRecord>(); for (SAMRecord r : input) { if (maxqual == r.getMappingQuality()) { if(!uniqueOnly || r.getMappingQuality()!=0) //For BWA output.add(r); } } return output; } public static boolean fillLeft(int n) { boolean filled = false; for (int i = 0; i < n; i++) { if (leftiter.hasNext()) { SAMRecord r = leftiter.next(); r.setReadName(r.getReadName().replaceAll("/\\d$","")); leftbuffer.add(r); filled = true; } } return filled; } public static boolean fillRight(int n) { boolean filled = false; for (int i = 0; i < n; i++) { if (rightiter.hasNext()) { SAMRecord r = rightiter.next(); r.setReadName(r.getReadName().replaceAll("/\\d$","")); rightbuffer.add(r); filled = true; } } return filled; } public static boolean fill(int n) { return fillLeft(n) && fillRight(n); } public static void makePairs() { ArrayList<SAMRecord> leftrecords = new ArrayList<SAMRecord>(); ArrayList<SAMRecord> rightrecords = new ArrayList<SAMRecord>(); while (fill(chunksize) || leftbuffer.size() > 0) { int clearL = 0, clearR = 0; int lbs = Math.min(leftbuffer.size(),10000); for (int i = 0; i < lbs; i++) { String readname = leftbuffer.get(i).getReadName(); String nextreadname = i < leftbuffer.size() - 1 ? leftbuffer.get(i+1).getReadName() : null; int j = clearR; while (j < rightbuffer.size()) { if (readname.equals(rightbuffer.get(j).getReadName())) { /* having found a match, find the rest of the reads with that ID and output */ int k = i; int l = j; /* make sure we'll be able to find all reads with this name */ while (readname.equals(leftbuffer.get(leftbuffer.size()-1).getReadName()) && fillLeft(chunksize)) { } while (readname.equals(rightbuffer.get(rightbuffer.size()-1).getReadName()) && fillRight(chunksize)) { } do { leftrecords.add(leftbuffer.get(k++)); } while (k < leftbuffer.size() && readname.equals(leftbuffer.get(k).getReadName())); do { rightrecords.add(rightbuffer.get(l++)); } while (l < rightbuffer.size() && readname.equals(rightbuffer.get(l).getReadName())); dumpRecords(leftrecords, rightrecords); leftrecords.clear(); rightrecords.clear(); clearL = k; clearR = l; i = k-1; break; } else if (nextreadname != null && nextreadname.equals(rightbuffer.get(j).getReadName())) { clearR = j; break; } j++; } } if (rightiter.hasNext()) { leftbuffer.subList(0,clearL).clear(); rightbuffer.subList(0,clearR).clear(); } else { leftbuffer.clear(); } //System.err.println(String.format("loop %d, left %d, right %d", loop++, leftbuffer.size(), rightbuffer.size())); } } public static void main(String args[]) throws IOException, ParseException { Options options = new Options(); options.addOption("l","left",true,"filename of left side of read"); options.addOption("r","right",true,"filename of right side of read"); options.addOption("u","uniquehits",false,"only output hits with a single mapping"); options.addOption("s","nosuboptimal",false,"do not include hits whose score is not equal to the best score for the read"); options.addOption("D","debug",false,"enable debugging spew?"); CommandLineParser parser = new GnuParser(); CommandLine cl = parser.parse( options, args, false ); uniqueOnly = cl.hasOption("uniquehits"); filterSubOpt = cl.hasOption("nosuboptimal"); debug = cl.hasOption("debug"); String leftfile = cl.getOptionValue("left"); String rightfile = cl.getOptionValue("right"); SamReaderFactory factory = SamReaderFactory.makeDefault() .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS, SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS) .validationStringency(ValidationStringency.SILENT); SamReader leftreader = factory.open(SamInputResource.of(new FileInputStream(leftfile))); SamReader rightreader = factory.open(SamInputResource.of(new FileInputStream(rightfile))); leftiter = leftreader.iterator(); rightiter = rightreader.iterator(); leftbuffer = new ArrayList<SAMRecord>(); rightbuffer = new ArrayList<SAMRecord>(); makePairs(); leftreader.close(); rightreader.close(); } }
92399318cdecc1f733450ade16223a04944ded1b
1,759
java
Java
src/main/java/com/destroystokyo/paper/antixray/DataBitsReader.java
Akarin-project/Paper2Srg
55798e89ed822e8d59dc55dfc6aa70cef1e47751
[ "MIT" ]
3
2018-06-22T14:09:27.000Z
2021-09-15T02:27:45.000Z
src/main/java/com/destroystokyo/paper/antixray/DataBitsReader.java
Akarin-project/AkarinModEdition
55798e89ed822e8d59dc55dfc6aa70cef1e47751
[ "MIT" ]
null
null
null
src/main/java/com/destroystokyo/paper/antixray/DataBitsReader.java
Akarin-project/AkarinModEdition
55798e89ed822e8d59dc55dfc6aa70cef1e47751
[ "MIT" ]
4
2018-06-21T09:44:06.000Z
2021-09-15T02:27:50.000Z
30.859649
79
0.543491
998,876
package com.destroystokyo.paper.antixray; public class DataBitsReader { private byte[] dataBits; private int bitsPerValue; private int mask; private int longInDataBitsIndex; private int bitInLongIndex; private long current; public void setDataBits(byte[] dataBits) { this.dataBits = dataBits; } public void setBitsPerValue(int bitsPerValue) { this.bitsPerValue = bitsPerValue; mask = (1 << bitsPerValue) - 1; } public void setIndex(int index) { this.longInDataBitsIndex = index; bitInLongIndex = 0; init(); } private void init() { if (dataBits.length > longInDataBitsIndex + 7) { current = ((((long) dataBits[longInDataBitsIndex]) << 56) | (((long) dataBits[longInDataBitsIndex + 1] & 0xff) << 48) | (((long) dataBits[longInDataBitsIndex + 2] & 0xff) << 40) | (((long) dataBits[longInDataBitsIndex + 3] & 0xff) << 32) | (((long) dataBits[longInDataBitsIndex + 4] & 0xff) << 24) | (((long) dataBits[longInDataBitsIndex + 5] & 0xff) << 16) | (((long) dataBits[longInDataBitsIndex + 6] & 0xff) << 8) | (((long) dataBits[longInDataBitsIndex + 7] & 0xff))); } } public int read() { int value = (int) (current >>> bitInLongIndex) & mask; bitInLongIndex += bitsPerValue; if (bitInLongIndex > 63) { bitInLongIndex -= 64; longInDataBitsIndex += 8; init(); if (bitInLongIndex > 0) { value |= current << bitsPerValue - bitInLongIndex & mask; } } return value; } }
923993c3e83d0d496e89167bfc5713ac43f2a6c6
205
java
Java
jcat-store-back/src/main/java/com/wzg/jcatstoreback/service/OrderHistoryService.java
WangZhenGuo12/jcat0224
479c06ca46cf04e54d72fe972e4d461fb6c9c132
[ "Apache-2.0" ]
null
null
null
jcat-store-back/src/main/java/com/wzg/jcatstoreback/service/OrderHistoryService.java
WangZhenGuo12/jcat0224
479c06ca46cf04e54d72fe972e4d461fb6c9c132
[ "Apache-2.0" ]
null
null
null
jcat-store-back/src/main/java/com/wzg/jcatstoreback/service/OrderHistoryService.java
WangZhenGuo12/jcat0224
479c06ca46cf04e54d72fe972e4d461fb6c9c132
[ "Apache-2.0" ]
null
null
null
17.083333
50
0.795122
998,877
package com.wzg.jcatstoreback.service; import com.wzg.jcatstoreback.po.OrderHistory; import java.util.List; public interface OrderHistoryService { List<OrderHistory> getByOrderId(Long orderId); }
92399455daadcf51edb5e929ef8428126471a56e
550
java
Java
app/src/test/java/com/skillmasters/server/common/EventGenerator.java
abelidze/planer-server
fa67bfc69a6f60c032619e78bd240e2539b187a6
[ "MIT" ]
5
2019-03-04T21:40:40.000Z
2019-03-27T09:53:32.000Z
app/src/test/java/com/skillmasters/server/common/EventGenerator.java
abelidze/planer-server
fa67bfc69a6f60c032619e78bd240e2539b187a6
[ "MIT" ]
6
2019-07-12T05:57:13.000Z
2019-07-19T06:30:38.000Z
app/src/test/java/com/skillmasters/server/common/EventGenerator.java
abelidze/planer-server
fa67bfc69a6f60c032619e78bd240e2539b187a6
[ "MIT" ]
null
null
null
22.916667
63
0.672727
998,878
package com.skillmasters.server.common; import com.skillmasters.server.model.Event; public class EventGenerator { public static Event genEvent(int id) { Event e = new Event(); e.setDetails("Details for event number " + id); e.setName("Name for event number " + id); e.setLocation("Location for event number " + id); e.setStatus("Statud for event number " + id); return e; } public static Event genEventWithOwner(int id, String ownerId) { Event e = genEvent(id); e.setOwnerId(ownerId); return e; } }
923994b4966cdfb707dcf5044d3f9a591aad6c94
602
java
Java
src/main/java/org/example/ArtemisProducer.java
iaptekar/spring-artemis-embedded-postgresql
5a3d9c7cea3bc52ca52112c212633e4d0a2e7b2d
[ "CC0-1.0" ]
null
null
null
src/main/java/org/example/ArtemisProducer.java
iaptekar/spring-artemis-embedded-postgresql
5a3d9c7cea3bc52ca52112c212633e4d0a2e7b2d
[ "CC0-1.0" ]
null
null
null
src/main/java/org/example/ArtemisProducer.java
iaptekar/spring-artemis-embedded-postgresql
5a3d9c7cea3bc52ca52112c212633e4d0a2e7b2d
[ "CC0-1.0" ]
null
null
null
25.083333
62
0.777409
998,879
package org.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; import javax.jms.ConnectionFactory; @Component public class ArtemisProducer { @Autowired JmsTemplate jmsTemplate; @Autowired private ConnectionFactory connectionFactory; @Value("${jms.queue.destination}") String destinationQueue; public void send(String msg) { jmsTemplate.convertAndSend(destinationQueue, msg); } }
923997071c1008ac068ddd119b749bfdd10558e3
3,585
java
Java
src/main/java/com/farmafene/commons/j2ee/tools/jca/btm/BTMTransactionSynchronizationRegistry.java
venanciolm/commons-j2ee-tools
36e76e994123c931da28d135aa8b0e70125bb8ef
[ "MIT" ]
null
null
null
src/main/java/com/farmafene/commons/j2ee/tools/jca/btm/BTMTransactionSynchronizationRegistry.java
venanciolm/commons-j2ee-tools
36e76e994123c931da28d135aa8b0e70125bb8ef
[ "MIT" ]
2
2021-09-11T14:54:44.000Z
2021-09-11T14:55:02.000Z
src/main/java/com/farmafene/commons/j2ee/tools/jca/btm/BTMTransactionSynchronizationRegistry.java
venanciolm/commons-j2ee-tools
36e76e994123c931da28d135aa8b0e70125bb8ef
[ "MIT" ]
null
null
null
31.447368
131
0.729428
998,880
/* * Copyright (c) 2009-2015 farmafene.com * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.farmafene.commons.j2ee.tools.jca.btm; import javax.transaction.Synchronization; import javax.transaction.TransactionSynchronizationRegistry; abstract class BTMTransactionSynchronizationRegistry extends BTMXAWorkAdapter implements TransactionSynchronizationRegistry { public BTMTransactionSynchronizationRegistry() { } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#getResource(java.lang.Object) */ @Override public Object getResource(final Object key) { return BTMLocator.getTransactionSynchronizationRegistry().getResource( key); } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#getRollbackOnly() */ @Override public boolean getRollbackOnly() { return BTMLocator.getTransactionSynchronizationRegistry() .getRollbackOnly(); } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#getTransactionKey() */ @Override public Object getTransactionKey() { return BTMLocator.getTransactionSynchronizationRegistry() .getTransactionKey(); } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#getTransactionStatus() */ @Override public int getTransactionStatus() { return BTMLocator.getTransactionSynchronizationRegistry() .getTransactionStatus(); } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#putResource(java.lang.Object, * java.lang.Object) */ @Override public void putResource(final Object key, final Object value) { BTMLocator.getTransactionSynchronizationRegistry().putResource(key, value); } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization(javax.transaction.Synchronization) */ @Override public void registerInterposedSynchronization(final Synchronization sync) { BTMLocator.getTransactionSynchronizationRegistry() .registerInterposedSynchronization(sync); } /** * {@inheritDoc} * * @see javax.transaction.TransactionSynchronizationRegistry#setRollbackOnly() */ @Override public void setRollbackOnly() { BTMLocator.getTransactionSynchronizationRegistry().setRollbackOnly(); } }
9239972e5df872ddbd38a6269c85669ff8622e7f
850
java
Java
blueprint/plugin/blueprint-maven-plugin-itest/src/it/simple-project/src/main/java/p1/T2.java
aguibert/aries
f8a242901ef5b43074786ef8a6a3cd5742398a96
[ "Apache-2.0" ]
75
2015-01-09T20:20:37.000Z
2022-03-22T13:22:30.000Z
blueprint/plugin/blueprint-maven-plugin-itest/src/it/simple-project/src/main/java/p1/T2.java
aguibert/aries
f8a242901ef5b43074786ef8a6a3cd5742398a96
[ "Apache-2.0" ]
77
2015-02-06T11:24:25.000Z
2022-03-18T17:41:52.000Z
blueprint/plugin/blueprint-maven-plugin-itest/src/it/simple-project/src/main/java/p1/T2.java
coheigea/aries
457551c4dda9ceca2e57572c121c605afb52db36
[ "Apache-2.0" ]
157
2015-01-12T20:43:13.000Z
2022-01-31T12:11:40.000Z
36.956522
63
0.742353
998,881
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package p1; public class T2 { }
9239992103aeed7da71617897a6630cda21975c0
299
java
Java
gmall-order/src/main/java/com/atguigu/gmall/order/feign/GmallOmsClient.java
mc1271367045/gmall-0211
fef8256cba20caa5581a1b38ac2a39327168fc42
[ "Apache-2.0" ]
null
null
null
gmall-order/src/main/java/com/atguigu/gmall/order/feign/GmallOmsClient.java
mc1271367045/gmall-0211
fef8256cba20caa5581a1b38ac2a39327168fc42
[ "Apache-2.0" ]
null
null
null
gmall-order/src/main/java/com/atguigu/gmall/order/feign/GmallOmsClient.java
mc1271367045/gmall-0211
fef8256cba20caa5581a1b38ac2a39327168fc42
[ "Apache-2.0" ]
null
null
null
21.357143
55
0.759197
998,882
package com.atguigu.gmall.order.feign; import com.atguigu.gmall.oms.api.GmallOmsApi; import org.springframework.cloud.openfeign.FeignClient; /** * @Auther: Gork_Mc * @Date: 2020/09/01/13:55 * @Description: */ @FeignClient("oms-service") public interface GmallOmsClient extends GmallOmsApi { }
92399a184cdfcd6d206c6319bfcd34f771c10c64
5,222
java
Java
diboot-iam-starter/src/main/java/com/diboot/iam/service/impl/IamAccountServiceImpl.java
dibo-software/diboo
7c80ccfb3fd274b5ecca45573a37b3bb219266ac
[ "ECL-2.0", "Apache-2.0" ]
531
2018-11-02T06:40:29.000Z
2022-03-31T16:21:15.000Z
diboot-iam-starter/src/main/java/com/diboot/iam/service/impl/IamAccountServiceImpl.java
dibo-software/diboo
7c80ccfb3fd274b5ecca45573a37b3bb219266ac
[ "ECL-2.0", "Apache-2.0" ]
17
2020-07-21T12:48:16.000Z
2022-03-08T16:06:43.000Z
diboot-iam-starter/src/main/java/com/diboot/iam/service/impl/IamAccountServiceImpl.java
dibo-software/diboo
7c80ccfb3fd274b5ecca45573a37b3bb219266ac
[ "ECL-2.0", "Apache-2.0" ]
134
2018-11-04T13:04:40.000Z
2022-03-28T13:23:57.000Z
35.013423
122
0.680659
998,883
/* * Copyright (c) 2015-2020, www.dibo.ltd (efpyi@example.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.diboot.iam.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.diboot.core.exception.BusinessException; import com.diboot.core.util.V; import com.diboot.core.vo.Status; import com.diboot.iam.auth.IamCustomize; import com.diboot.iam.config.Cons; import com.diboot.iam.dto.ChangePwdDTO; import com.diboot.iam.entity.IamAccount; import com.diboot.iam.mapper.IamAccountMapper; import com.diboot.iam.service.IamAccountService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 认证用户相关Service实现 * @author efpyi@example.com * @version 2.0 * @date 2019-12-03 */ @Service @Slf4j public class IamAccountServiceImpl extends BaseIamServiceImpl<IamAccountMapper, IamAccount> implements IamAccountService { @Autowired(required = false) private IamCustomize iamCustomize; @Override public boolean createEntity(IamAccount iamAccount) { // 生成加密盐并加密 if (V.notEmpty(iamAccount.getAuthSecret())){ iamCustomize.encryptPwd(iamAccount); } // 保存 return super.createEntity(iamAccount); } @Override @Transactional(rollbackFor = Exception.class) public boolean createEntities(List<IamAccount> accountList){ if(V.isEmpty(accountList)){ return true; } for(IamAccount account : accountList){ // 生成加密盐并加密 if (V.notEmpty(account.getAuthSecret())){ iamCustomize.encryptPwd(account); } } return super.createEntities(accountList); } @Override public boolean changePwd(ChangePwdDTO changePwdDTO, IamAccount iamAccount) throws Exception { // 验证账号信息是否存在 if (iamAccount == null){ throw new BusinessException(Status.FAIL_OPERATION, "账号信息不存在"); } // 验证当前账号登录方式 if (!Cons.DICTCODE_AUTH_TYPE.PWD.name().equals(iamAccount.getAuthType())){ throw new BusinessException(Status.FAIL_OPERATION, "该账号登录方式不支持更改密码"); } // 验证密码一致性 if (V.notEquals(changePwdDTO.getPassword(), changePwdDTO.getConfirmPassword())){ throw new BusinessException(Status.FAIL_OPERATION, "密码与确认密码不一致,请重新输入"); } // 验证旧密码是否正确 String oldAuthSecret = iamCustomize.encryptPwd(changePwdDTO.getOldPassword(), iamAccount.getSecretSalt()); if (V.notEquals(oldAuthSecret, iamAccount.getAuthSecret())){ throw new BusinessException(Status.FAIL_OPERATION, "旧密码错误,请重新输入"); } // 更改密码 iamAccount.setAuthSecret(changePwdDTO.getPassword()); iamCustomize.encryptPwd(iamAccount); boolean success = this.updateEntity(iamAccount); return success; } @Override public String getAuthAccount(String userType, Long userId) { LambdaQueryWrapper<IamAccount> queryWrapper = new QueryWrapper<IamAccount>().lambda() .select(IamAccount::getAuthAccount) .eq(IamAccount::getUserType, userType) .eq(IamAccount::getUserId, userId); IamAccount account = getSingleEntity(queryWrapper); return account!=null? account.getAuthAccount() : null; } @Override public boolean isAccountExists(IamAccount iamAccount) { LambdaQueryWrapper<IamAccount> queryWrapper = new QueryWrapper<IamAccount>().lambda() .eq(IamAccount::getAuthAccount, iamAccount.getAuthAccount()) .eq(IamAccount::getAuthType, iamAccount.getAuthType()) .eq(IamAccount::getUserType, iamAccount.getUserType()); if(iamAccount.getId() != null){ queryWrapper.ne(IamAccount::getId, iamAccount.getId()); } return exists(queryWrapper); } /** * 判断账号是否存在 * @param iamAccount * @return */ @Override protected void beforeCreateEntity(IamAccount iamAccount){ if(isAccountExists(iamAccount)){ String errorMsg = "账号 "+ iamAccount.getAuthAccount() +" 已存在,请重新设置!"; log.warn("保存账号异常: {}", errorMsg); throw new BusinessException(Status.FAIL_VALIDATION, errorMsg); } } /** * 判断账号是否存在 * @param iamAccount * @return */ @Override protected void beforeUpdateEntity(IamAccount iamAccount){ beforeCreateEntity(iamAccount); } }
92399adb24f72d701d41797867b0cd48db85bea4
373
java
Java
src/main/java/io/github/znetworkw/znpcservers/UnexpectedCallException.java
MCPfannkuchenYT/znpc-servers
166ceb979756fddb6e8f619398cf22b02b34bbc6
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/znetworkw/znpcservers/UnexpectedCallException.java
MCPfannkuchenYT/znpc-servers
166ceb979756fddb6e8f619398cf22b02b34bbc6
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/znetworkw/znpcservers/UnexpectedCallException.java
MCPfannkuchenYT/znpc-servers
166ceb979756fddb6e8f619398cf22b02b34bbc6
[ "Apache-2.0" ]
null
null
null
23.3125
68
0.705094
998,884
package io.github.znetworkw.znpcservers; import io.github.znetworkw.znpcservers.npc.NPC; /** * Exception for any errors that occur while managing a {@link NPC}. */ public class UnexpectedCallException extends RuntimeException { /** * @param cause The throwable cause. */ public UnexpectedCallException(Throwable cause) { super(cause); } }
92399b526dc7af5bd9b5aa6a8ba073e694b515ec
15,190
java
Java
src/main/java/dev/majek/pc/data/DataHandler.java
Michel3951/PartyChat
ac8c0f789fa703bce9d33ea63245919fc0a7daae
[ "MIT" ]
null
null
null
src/main/java/dev/majek/pc/data/DataHandler.java
Michel3951/PartyChat
ac8c0f789fa703bce9d33ea63245919fc0a7daae
[ "MIT" ]
null
null
null
src/main/java/dev/majek/pc/data/DataHandler.java
Michel3951/PartyChat
ac8c0f789fa703bce9d33ea63245919fc0a7daae
[ "MIT" ]
null
null
null
40.291777
114
0.612311
998,885
package dev.majek.pc.data; import dev.majek.pc.PartyChat; import dev.majek.pc.data.object.User; import dev.majek.pc.data.storage.ConfigUpdater; import dev.majek.pc.data.object.Language; import dev.majek.pc.data.storage.YAMLConfig; import dev.majek.pc.mechanic.Mechanic; import org.apache.commons.io.FileUtils; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import java.util.stream.Stream; /** * This class handles all plugin data storage, config file access, and the main config file. */ public class DataHandler extends Mechanic { public PartyChat instance; public int minecraftVersion; public MessageType messageType = null; // Data private final Map<UUID, User> userMap; // Configuration public FileConfiguration mainConfig; public FileConfiguration messages; public FileConfiguration commandConfig; public boolean debug; public boolean disableGuis; public boolean persistentParties; public boolean blockInappropriateNames; public boolean blockInappropriateChat; public List<String> censorWords; public DataHandler() { instance = PartyChat.getCore(); this.userMap = new HashMap<>(); this.censorWords = new ArrayList<>(); wipeOldPlugin(); updateMainConfig(); } /** * This will replace the old config files if they still exist. */ @SuppressWarnings("all") public void wipeOldPlugin() { File langFolder = new File(instance.getDataFolder() + "/Lang"); if (!langFolder.exists()) { instance.getLogger().log(Level.SEVERE, "PCv3 data folder found! Archiving old config files and " + "creating new data folder... "); File oldConfig = new File(instance.getDataFolder(), "config.yml"); if (oldConfig.exists()) oldConfig.renameTo(new File(instance.getDataFolder(), "config-old.yml")); File oldMessages = new File(instance.getDataFolder(), "messages.yml"); if (oldMessages.exists()) oldMessages.renameTo(new File(instance.getDataFolder(), "messages-old.yml")); File oldDatabase = new File(instance.getDataFolder(), "parties.db"); if (oldDatabase.exists()) oldDatabase.renameTo(new File(instance.getDataFolder(), "database-old.db")); } } /** * Initialize the main config file before doing anything else. */ public void updateMainConfig() { // Initialize main config PartyChat.getCore().saveDefaultConfig(); File configFile = new File(instance.getDataFolder(), "config.yml"); try { ConfigUpdater.update(instance, "config.yml", configFile, Collections.emptyList()); } catch (IOException e) { e.printStackTrace(); } PartyChat.getCore().reloadConfig(); mainConfig = PartyChat.getCore().getConfig(); } /** * Runs on plugin startup. Get config options and initialize bStats metrics. */ @Override public void onStartup() { // Minecraft version shenanigans String fullVersion = PartyChat.getCore().getServer().getClass().getPackage().getName(); String substring = fullVersion.substring(fullVersion.lastIndexOf('.') + 1); String[] versionSplit = substring.split("_"); minecraftVersion = Integer.parseInt(versionSplit[1]); // Load commands config file YAMLConfig commands = new YAMLConfig(PartyChat.getCore(), null, "commands.yml"); commands.saveDefaultConfig(); File commandsFile = new File(PartyChat.getCore().getDataFolder(), "commands.yml"); try { ConfigUpdater.update(PartyChat.getCore(), "commands.yml", commandsFile, Collections.emptyList()); } catch (IOException e) { e.printStackTrace(); } commands.reloadConfig(); commandConfig = commands.getConfig(); // Set global values defined in main config debug = getConfigBoolean(mainConfig, "debug"); disableGuis = getConfigBoolean(mainConfig, "disable-guis"); disableGuis = !(minecraftVersion >= 13); // They just don't work in 12 and below if (disableGuis) PartyChat.log("GUIs have been disabled due to the server's Minecraft version."); persistentParties = getConfigBoolean(mainConfig, "persistent-parties"); blockInappropriateNames = getConfigBoolean(mainConfig, "block-inappropriate-names"); blockInappropriateChat = getConfigBoolean(mainConfig, "block-inappropriate-names"); // Censored words stuff if (blockInappropriateNames || blockInappropriateChat) { censorWords.addAll(getConfigStringList(mainConfig, "blocked-words")); if (!(getConfigString(mainConfig, "blocked-words-file").equalsIgnoreCase(""))) { File censorFile = new File(PartyChat.getCore().getDataFolder(), getConfigString(mainConfig, "blocked-words-file")); if (!censorFile.exists()) { try { InputStream stream = PartyChat.getCore().getResource("censor-words.txt"); FileUtils.copyInputStreamToFile(stream, censorFile); } catch (IOException e) { PartyChat.error("Error creating censor-words.txt file."); e.printStackTrace(); } } try (Stream<String> stream = Files.lines(Paths.get(censorFile.toURI()), StandardCharsets.UTF_8)) { stream.forEach(word -> censorWords.add(word)); } catch (IOException e) { PartyChat.error("Error loading censor words from file: " + getConfigString(mainConfig, "blocked-words-file")); e.printStackTrace(); } } } // Plugin metrics new Metrics(PartyChat.getCore(), 7667); PartyChat.log("Finished updating config and lang files."); } public void postStartup() { // Set the message config file based on language from main config messages = PartyChat.getLanguageHandler().getLanguage().getMessagesConfig().getConfig(); } /** * Reload config files to recognize changes. This is called on /pc reload */ public void reload() { PartyChat.getCore().reloadConfig(); mainConfig = PartyChat.getCore().getConfig(); YAMLConfig commands = new YAMLConfig(PartyChat.getCore(), null, "commands.yml"); commands.saveDefaultConfig(); File commandsFile = new File(PartyChat.getCore().getDataFolder(), "commands.yml"); //createFileIfNotExists(configManager, en_US_FILE); try { ConfigUpdater.update(PartyChat.getCore(), "commands.yml", commandsFile, Collections.emptyList()); } catch (IOException e) { e.printStackTrace(); } commands.reloadConfig(); commandConfig = commands.getConfig(); // Set global values defined in main config debug = getConfigBoolean(mainConfig, "debug"); disableGuis = getConfigBoolean(mainConfig, "disable-guis"); disableGuis = !(minecraftVersion >= 13); // They just don't work in 12 and below if (disableGuis) PartyChat.log("GUIs have been disabled due to the server's Minecraft version."); persistentParties = getConfigBoolean(mainConfig, "persistent-parties"); // Update language if necessary if (!PartyChat.getLanguageHandler().getLanguage().getLangID().equals(getConfigString(mainConfig, "language"))) { setMessages(getConfigString(mainConfig, "language")); } PartyChat.getLanguageHandler().getLanguage().getMessagesConfig().reloadConfig(); messages = PartyChat.getLanguageHandler().getLanguage().getMessagesConfig().getConfig(); PartyChat.log("Config and lang files were reloaded."); } @EventHandler public void onCommandPreprocess(PlayerCommandPreprocessEvent event) { updatePerms(event.getPlayer()); } /** * Update a players staff permissions. * @param player The player to update. */ public void updatePerms(Player player) { User user = getUser(player); if (player.hasPermission("partychat.admin") && !user.isStaff()) { user.setStaff(true); user.setSpyToggle(getConfigBoolean(mainConfig, "auto-spy")); } else if (!player.hasPermission("partychat.admin")) { user.setStaff(false); user.setSpyToggle(false); } } /** * Get today's plugin log file. * @return Today's log file. */ public File getTodaysLog() { return new File(PartyChat.getCore().getDataFolder(), "Logs/" + java.time.LocalDate.now().toString() + ".txt"); } /** * Log a message to today's log file. * @param message Message to log. * @param level Log level. */ @SuppressWarnings("all") public void logToFile(String message, String level) { try { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); message = "[" + formatter.format(date) + " " + level + "] " + message; String fileName = java.time.LocalDate.now().toString(); File logDir = new File(PartyChat.getCore().getDataFolder(), "Logs/"); File logFile = new File(PartyChat.getCore().getDataFolder(), "Logs/" + fileName + ".txt"); if (!logDir.exists()) logDir.mkdirs(); if (!logFile.exists()) logFile.createNewFile(); PrintWriter writer = new PrintWriter(new FileWriter(logFile, true)); writer.println(message); writer.flush(); writer.close(); File[] logFiles = logDir.listFiles(); long oldestDate = Long.MAX_VALUE; File oldestFile = null; if (logFiles != null && logFiles.length > 7) { for (File f : logFiles) if (f.lastModified() < oldestDate) { oldestDate = f.lastModified(); oldestFile = f; } if (oldestFile != null) { oldestFile.delete(); PartyChat.log("Deleting 1 week+ old file " + oldestFile.getName()); } } } catch (IOException e) { e.printStackTrace(); } } /** * Get a boolean value from a config file. * @param config The config file to get the value from. * @param path The path to get the value from. * @return Boolean value. */ public boolean getConfigBoolean(FileConfiguration config, String path) { try { return config.getBoolean(path); } catch (NullPointerException ex) { String filepath = config == PartyChat.getCore().getConfig() ? "config.yml" : PartyChat.getLanguageHandler().getLanguage().getLangID() + ".yml"; throw new NullPointerException("Error finding value for path " + path + " in " + filepath + ", did you delete something?"); } } /** * Get a String value from a config file. * @param config The config file to get the value from. * @param path The path to get the value from. * @return String value. */ public String getConfigString(FileConfiguration config, String path) { try { return config.getString(path); } catch (NullPointerException ex) { String filepath = config == PartyChat.getCore().getConfig() ? "config.yml" : PartyChat.getLanguageHandler().getLanguage().getLangID() + ".yml"; throw new NullPointerException("Error finding value for path " + path + " in " + filepath + ", did you delete something?"); } } /** * Get an int value from a config file. * @param config The config file to get the value from. * @param path The path to get the value from. * @return Integer value. */ public int getConfigInt(FileConfiguration config, String path) { try { return config.getInt(path); } catch (NullPointerException ex) { String filepath = config == PartyChat.getCore().getConfig() ? "config.yml" : PartyChat.getLanguageHandler().getLanguage().getLangID() + ".yml"; throw new NullPointerException("Error finding value for path " + path + " in " + filepath + ", did you delete something?"); } } /** * Get a list of strings from a config file. * @param config The config file to get the value from. * @param path The path to get the value from. * @return List of strings. */ public List<String> getConfigStringList(FileConfiguration config, String path) { try { return config.getStringList(path); } catch (NullPointerException ex) { String filepath = config == PartyChat.getCore().getConfig() ? "config.yml" : PartyChat.getLanguageHandler().getLanguage().getLangID() + ".yml"; throw new NullPointerException("Error finding value for path " + path + " in " + filepath + ", did you delete something?"); } } /** * Set the {@link DataHandler#messages} config file to a different language. * If this method fails it's probably because the language ID you're trying to set * isn't present in the main config file's supported-languages section. * @param lang The language ID to set the plugin language to. */ public void setMessages(String lang) { Language language = PartyChat.getLanguageHandler().getLangMap().get(lang); if (language != null) { PartyChat.getLanguageHandler().setLanguage(language); messages = PartyChat.getLanguageHandler().getLanguage().getMessagesConfig().getConfig(); PartyChat.log("Language set to " + language.getLangID() + "."); } } public User getUser(Player player) { return userMap.get(player.getUniqueId()); } public User getUser(UUID uuid) { return userMap.get(uuid); } public Map<UUID, User> getUserMap() { return userMap; } public void addToUserMap(User user) { userMap.put(user.getPlayerID(), user); } public void removeFromUserMap(User user) { userMap.remove(user.getPlayerID()); } public enum MessageType { COMPONENT, BASECOMPONENT, RAW } }
92399cb43db4423aeae7af86dc3cd4f9222d37d4
8,809
java
Java
fx-parent/fx-core/src/test/java/org/interledger/fx/ScaledExchangeRateTest.java
hyperledger/quilt
0bc5c0293e96826fed1448be69bd9f7fa4c921c1
[ "Apache-2.0" ]
234
2017-10-22T03:19:12.000Z
2021-12-30T08:41:12.000Z
fx-parent/fx-core/src/test/java/org/interledger/fx/ScaledExchangeRateTest.java
0xcd21/quilt
0bc5c0293e96826fed1448be69bd9f7fa4c921c1
[ "Apache-2.0" ]
415
2017-10-24T10:08:57.000Z
2021-06-03T20:01:51.000Z
fx-parent/fx-core/src/test/java/org/interledger/fx/ScaledExchangeRateTest.java
0xcd21/quilt
0bc5c0293e96826fed1448be69bd9f7fa4c921c1
[ "Apache-2.0" ]
103
2017-10-19T14:06:05.000Z
2021-12-03T01:02:55.000Z
39.859729
115
0.742082
998,886
package org.interledger.fx; import static org.assertj.core.api.Assertions.assertThat; import org.interledger.core.fluent.Percentage; import org.interledger.core.fluent.Ratio; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.math.BigInteger; /** * Unit tests for {@link ScaledExchangeRate}. */ public class ScaledExchangeRateTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testWhereSourceGreaterThanDest() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.TEN)) .slippage(Slippage.ONE_PERCENT) .originalSourceScale((short) 9) .originalDestinationScale((short) 6) .build(); assertThat(scaledExchangeRate.value()) .isEqualTo(Ratio.builder().numerator(BigInteger.valueOf(100L)).denominator(BigInteger.TEN).build()); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 9); } @Test public void testWhereSourceLessThanDest() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.TEN)) .slippage(Slippage.ONE_PERCENT) .originalSourceScale((short) 6) .originalDestinationScale((short) 9) .build(); assertThat(scaledExchangeRate.value()) .isEqualTo(Ratio.builder().numerator(BigInteger.valueOf(100L)).denominator(BigInteger.TEN).build()); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 6); assertThat(scaledExchangeRate.originalDestinationScale()).isEqualTo((short) 9); } @Test public void testWhereSourceAndDestAreEqual() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.TEN)) .slippage(Slippage.ONE_PERCENT) .originalSourceScale((short) 9) .originalDestinationScale((short) 9) .build(); assertThat(scaledExchangeRate.value()) .isEqualTo(Ratio.builder().numerator(BigInteger.valueOf(100L)).denominator(BigInteger.TEN).build()); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 9); assertThat(scaledExchangeRate.originalDestinationScale()).isEqualTo((short) 9); } @Test public void testWhereSourceAndDestAreZero() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.TEN)) .slippage(Slippage.ONE_PERCENT) .originalSourceScale((short) 0) .originalDestinationScale((short) 0) .build(); assertThat(scaledExchangeRate.value()) .isEqualTo(Ratio.builder().numerator(BigInteger.valueOf(100L)).denominator(BigInteger.TEN).build()); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 0); assertThat(scaledExchangeRate.originalDestinationScale()).isEqualTo((short) 0); } @Test public void testWhereSourceIsZeroAndDestIsNonZero() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.TEN)) .slippage(Slippage.ONE_PERCENT) .originalSourceScale((short) 0) .originalDestinationScale((short) 2) .build(); assertThat(scaledExchangeRate.value()) .isEqualTo(Ratio.builder().numerator(BigInteger.valueOf(100L)).denominator(BigInteger.TEN).build()); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 0); assertThat(scaledExchangeRate.originalDestinationScale()).isEqualTo((short) 2); } @Test public void testWhereSourceIsNonZeroAndDestIsZero() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.TEN)) .slippage(Slippage.ONE_PERCENT) .originalSourceScale((short) 2) .originalDestinationScale((short) 0) .build(); assertThat(scaledExchangeRate.value()) .isEqualTo(Ratio.builder().numerator(BigInteger.valueOf(100L)).denominator(BigInteger.TEN).build()); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 2); assertThat(scaledExchangeRate.originalDestinationScale()).isEqualTo((short) 0); } @Test public void testBuildWithZero() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.ZERO)) .originalSourceScale((short) 9) .originalDestinationScale((short) 6) .build(); assertThat(scaledExchangeRate.value().toBigDecimal()).isEqualTo(BigDecimal.ZERO); assertThat(scaledExchangeRate.slippage()).isEqualTo(Slippage.ONE_PERCENT); assertThat(scaledExchangeRate.originalSourceScale()).isEqualTo((short) 9); assertThat(scaledExchangeRate.originalDestinationScale()).isEqualTo((short) 6); } @Test public void testEmptyBuild() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage( "Cannot build ScaledExchangeRate, some of required attributes are not set " + "[value, originalSourceScale, originalDestinationScale]"); ScaledExchangeRate.builder().build(); } @Test public void testToString() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.ONE)) .originalSourceScale((short) 9) .originalDestinationScale((short) 2) .build(); assertThat(scaledExchangeRate.toString()).isEqualTo("ScaledExchangeRate{value=10/10[1], " + "originalSourceScale=9, originalDestinationScale=2, slippage=Slippage{value=1%}}"); } @Test public void testCompareTo() { ScaledExchangeRate scaledExchangeRate0 = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.ZERO)) .originalSourceScale((short) 2) .originalDestinationScale((short) 2) .build(); ScaledExchangeRate scaledExchangeRate1 = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.ONE)) .originalSourceScale((short) 2) .originalDestinationScale((short) 2) .build(); assertThat(scaledExchangeRate0.compareTo(scaledExchangeRate0)).isEqualTo(0); assertThat(scaledExchangeRate0.compareTo(scaledExchangeRate1)).isEqualTo(-1); assertThat(scaledExchangeRate1.compareTo(scaledExchangeRate0)).isEqualTo(1); } @Test public void testEquals() { ScaledExchangeRate scaledExchangeRate0 = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.ZERO)) .originalSourceScale((short) 2) .originalDestinationScale((short) 2) .build(); ScaledExchangeRate scaledExchangeRate1 = ScaledExchangeRate.builder() .value(Ratio.from(BigDecimal.ONE)) .originalSourceScale((short) 2) .originalDestinationScale((short) 2) .build(); assertThat(scaledExchangeRate0.equals(scaledExchangeRate0)).isTrue(); assertThat(scaledExchangeRate0.equals(scaledExchangeRate1)).isFalse(); assertThat(scaledExchangeRate1.equals(scaledExchangeRate0)).isFalse(); } @Test public void testBounds() { ScaledExchangeRate scaledExchangeRate = ScaledExchangeRate.builder() .value(Ratio.from(new BigDecimal("86.84991150442478"))) .originalSourceScale((short) 0) .originalDestinationScale((short) 0) .slippage(Slippage.of(Percentage.of(new BigDecimal("0.00051")))) .build(); assertThat(scaledExchangeRate.slippage().value().value()).isEqualTo(new BigDecimal("0.00051")); // Lower Bound / MinRate from JS BigDecimal minimumRate = BigDecimal.ONE.subtract(scaledExchangeRate.slippage().value().value()) .multiply(scaledExchangeRate.value().toBigDecimal()); assertThat(minimumRate).isEqualTo(new BigDecimal("86.8056180495575233622")); // LowerBound final BigDecimal lowerBoundFromJS = new BigDecimal("86.8056180495575233622"); assertThat(scaledExchangeRate.lowerBound().toBigDecimal()).isEqualTo(lowerBoundFromJS); assertThat(scaledExchangeRate.lowerBound()).isEqualTo(Ratio.builder() .numerator(new BigInteger("868056180495575233622")) .denominator(new BigInteger("10000000000000000000")) .build()); // Value assertThat(scaledExchangeRate.value().toBigDecimal()).isEqualTo(new BigDecimal("86.84991150442478")); // Upper Bound assertThat(scaledExchangeRate.upperBound().toBigDecimal()).isEqualTo(new BigDecimal("86.8942049592920366378")); } }
92399cc7a38f0ddce8338d127fb7b579606f2571
4,344
java
Java
src/main/java/org/apache/aurora/scheduler/SchedulerModule.java
mohitsoni/incubator-aurora
fbbd0e3e165188c2a3a23b2295587c48f9264847
[ "Apache-2.0" ]
1
2016-05-01T20:17:24.000Z
2016-05-01T20:17:24.000Z
src/main/java/org/apache/aurora/scheduler/SchedulerModule.java
mohitsoni/incubator-aurora
fbbd0e3e165188c2a3a23b2295587c48f9264847
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/aurora/scheduler/SchedulerModule.java
mohitsoni/incubator-aurora
fbbd0e3e165188c2a3a23b2295587c48f9264847
[ "Apache-2.0" ]
null
null
null
38.442478
94
0.758517
998,887
/** * Copyright 2013 Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aurora.scheduler; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Singleton; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.PrivateModule; import com.google.inject.Provides; import com.twitter.common.args.Arg; import com.twitter.common.args.CmdLine; import com.twitter.common.quantity.Amount; import com.twitter.common.quantity.Time; import org.apache.aurora.scheduler.Driver.DriverImpl; import org.apache.aurora.scheduler.Driver.SettableDriver; import org.apache.aurora.scheduler.SchedulerLifecycle.LeadingOptions; import org.apache.aurora.scheduler.TaskIdGenerator.TaskIdGeneratorImpl; import org.apache.aurora.scheduler.events.PubsubEventModule; import org.apache.aurora.scheduler.periodic.GcExecutorLauncher; import org.apache.aurora.scheduler.periodic.GcExecutorLauncher.GcExecutorSettings; import org.apache.mesos.Scheduler; /** * Binding module for top-level scheduling logic. */ public class SchedulerModule extends AbstractModule { @CmdLine(name = "executor_gc_interval", help = "Max interval on which to run the GC executor on a host to clean up dead tasks.") private static final Arg<Amount<Long, Time>> EXECUTOR_GC_INTERVAL = Arg.create(Amount.of(1L, Time.HOURS)); @CmdLine(name = "gc_executor_path", help = "Path to the gc executor launch script.") private static final Arg<String> GC_EXECUTOR_PATH = Arg.create(null); @CmdLine(name = "max_registration_delay", help = "Max allowable delay to allow the driver to register before aborting") private static final Arg<Amount<Long, Time>> MAX_REGISTRATION_DELAY = Arg.create(Amount.of(1L, Time.MINUTES)); @CmdLine(name = "max_leading_duration", help = "After leading for this duration, the scheduler should commit suicide.") private static final Arg<Amount<Long, Time>> MAX_LEADING_DURATION = Arg.create(Amount.of(1L, Time.DAYS)); @Override protected void configure() { bind(Driver.class).to(DriverImpl.class); bind(SettableDriver.class).to(DriverImpl.class); bind(DriverImpl.class).in(Singleton.class); bind(Scheduler.class).to(MesosSchedulerImpl.class); bind(MesosSchedulerImpl.class).in(Singleton.class); bind(TaskIdGenerator.class).to(TaskIdGeneratorImpl.class); bind(GcExecutorSettings.class).toInstance(new GcExecutorSettings( EXECUTOR_GC_INTERVAL.get(), Optional.fromNullable(GC_EXECUTOR_PATH.get()))); bind(GcExecutorLauncher.class).in(Singleton.class); bind(UserTaskLauncher.class).in(Singleton.class); install(new PrivateModule() { @Override protected void configure() { bind(LeadingOptions.class).toInstance( new LeadingOptions(MAX_REGISTRATION_DELAY.get(), MAX_LEADING_DURATION.get())); final ScheduledExecutorService executor = Executors.newScheduledThreadPool( 1, new ThreadFactoryBuilder().setNameFormat("Lifecycle-%d").setDaemon(true).build()); bind(ScheduledExecutorService.class).toInstance(executor); bind(SchedulerLifecycle.class).in(Singleton.class); expose(SchedulerLifecycle.class); } }); PubsubEventModule.bindSubscriber(binder(), SchedulerLifecycle.class); PubsubEventModule.bindSubscriber(binder(), TaskVars.class); } @Provides @Singleton List<TaskLauncher> provideTaskLaunchers( GcExecutorLauncher gcLauncher, UserTaskLauncher userTaskLauncher) { return ImmutableList.of(gcLauncher, userTaskLauncher); } }
92399cce14ea73504c6718f5a362e2c3e0752598
306
java
Java
Semester 1 (ICP)/assignment 5/cw/a5q20.java
MartyMiniac/ITER-Assignment
a7b355f40cc52a337ad90bb8328e54c4a9534530
[ "MIT" ]
14
2020-11-11T08:48:58.000Z
2022-02-26T03:59:05.000Z
assignment 5/cw/a5q20.java
head-hunter25/ICP-assign
62b9b9b146f18b0a65e8f49d5ab5946b8a5c6553
[ "MIT" ]
4
2020-11-12T13:31:14.000Z
2021-06-21T05:41:34.000Z
assignment 5/cw/a5q20.java
head-hunter25/ICP-assign
62b9b9b146f18b0a65e8f49d5ab5946b8a5c6553
[ "MIT" ]
10
2020-11-07T15:09:20.000Z
2022-02-26T03:56:50.000Z
12.75
39
0.519608
998,888
import java.util.*; class a5q20 { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter a Number :"); int n=in.nextInt(); int f=2; while(n>1) { if(n%f==0) { System.out.print(f+", "); n/=f; } else { f++; } } } }
92399cf0c51d511f8e588340b4568808e4ea8b39
2,506
java
Java
src/main/java/com.cloudmine.api/rest/BaseUserLogoutRequest.java
cloudmine/CloudMineSDK-Android
c6f9313e12317c04bd44939612255cc929a7db7e
[ "MIT" ]
1
2015-09-10T06:25:20.000Z
2015-09-10T06:25:20.000Z
src/main/java/com.cloudmine.api/rest/BaseUserLogoutRequest.java
cloudmine/CloudMineSDK-Android
c6f9313e12317c04bd44939612255cc929a7db7e
[ "MIT" ]
null
null
null
src/main/java/com.cloudmine.api/rest/BaseUserLogoutRequest.java
cloudmine/CloudMineSDK-Android
c6f9313e12317c04bd44939612255cc929a7db7e
[ "MIT" ]
2
2016-06-14T11:14:05.000Z
2021-02-27T15:30:16.000Z
43.206897
254
0.77095
998,889
package com.cloudmine.api.rest; import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.cloudmine.api.CMApiCredentials; import com.cloudmine.api.CMSessionToken; import com.cloudmine.api.rest.options.CMServerFunction; import com.cloudmine.api.rest.response.CMResponse; import me.cloudmine.annotations.Expand; import me.cloudmine.annotations.Optional; import java.util.Date; /** * A Request for invalidating a session token. Note that if a user has multiple valid * session tokens, invalidating a single token will not invalidate * <br> * Copyright CloudMine, Inc. All rights reserved<br> * See LICENSE file included with SDK for details. */ public class BaseUserLogoutRequest extends CloudMineRequest<CMResponse> { public static final int REQUEST_TYPE = 413; /** * Create a BaseUserLogoutRequest which will invalidate the specified sessionToken * @param sessionToken a String representation of a sessionToken, obtained by calling {@link com.cloudmine.api.CMSessionToken#getSessionToken()} * @param serverFunction * @param successListener * @param errorListener */ @Expand public BaseUserLogoutRequest(String sessionToken, @Optional CMApiCredentials apiCredentials, @Optional CMServerFunction serverFunction, @Optional Response.Listener<CMResponse> successListener, @Optional Response.ErrorListener errorListener) { this(new CMSessionToken(sessionToken, new Date()), apiCredentials, serverFunction, successListener, errorListener); } /** * Create a BaseUserLogoutRequest which will invalidate the specified sessionToken * @param sessionToken * @param serverFunction * @param successListener * @param errorListener */ @Expand public BaseUserLogoutRequest(CMSessionToken sessionToken, @Optional CMApiCredentials apiCredentials, @Optional CMServerFunction serverFunction, @Optional Response.Listener<CMResponse> successListener, @Optional Response.ErrorListener errorListener) { super(Method.POST, "/account/logout", (String)null, sessionToken, apiCredentials, serverFunction, successListener, errorListener); } @Override protected Response<CMResponse> parseNetworkResponse(NetworkResponse networkResponse) { return Response.success(new CMResponse(new String(networkResponse.data), networkResponse.statusCode), getCacheEntry(networkResponse)); } @Override public int getRequestType() { return REQUEST_TYPE; } }
92399e2b09732d1196a44bfec15eac9c16b89e16
918
java
Java
model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/JsonImportTest.java
chendouble/midpoint
41d2be4fbd7084224b5c3f33868c11b4dbbb46d6
[ "Apache-2.0" ]
27
2017-04-27T15:15:08.000Z
2021-12-12T10:53:16.000Z
model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/JsonImportTest.java
chendouble/midpoint
41d2be4fbd7084224b5c3f33868c11b4dbbb46d6
[ "Apache-2.0" ]
2
2016-11-28T12:47:14.000Z
2016-11-30T07:42:43.000Z
model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/JsonImportTest.java
chendouble/midpoint
41d2be4fbd7084224b5c3f33868c11b4dbbb46d6
[ "Apache-2.0" ]
6
2017-04-02T15:52:32.000Z
2021-12-12T10:53:23.000Z
25.5
75
0.737473
998,890
/* * Copyright (c) 2010-2017 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.intest.importer; import com.evolveum.midpoint.prism.PrismContext; /** * @author mederly */ public class JsonImportTest extends AbstractImportTest { @Override String getSuffix() { return "json"; } @Override String getLanguage() { return PrismContext.LANG_JSON; } }
92399e7a51cd29f5beb06bad2740dc7ba979b75b
939
java
Java
app/src/main/java/me/nkkumawat/picloc_x/Models/Pictures.java
nkkumawat/PicLoc-Android
2b736ea4e50b0aa1787f0c425617dc1428327a4a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/nkkumawat/picloc_x/Models/Pictures.java
nkkumawat/PicLoc-Android
2b736ea4e50b0aa1787f0c425617dc1428327a4a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/nkkumawat/picloc_x/Models/Pictures.java
nkkumawat/PicLoc-Android
2b736ea4e50b0aa1787f0c425617dc1428327a4a
[ "Apache-2.0" ]
null
null
null
26.083333
117
0.666667
998,891
package me.nkkumawat.picloc_x.Models; import com.google.gson.annotations.SerializedName; /** * Created by sonu on 14/6/18. */ public class Pictures { @SerializedName("id") public String id; @SerializedName("user_id") public String user_id; @SerializedName("pic_url") public String pic_url; @SerializedName("pic_latitude") public String latitude; @SerializedName("pic_longitude") public String longitude; @SerializedName("pic_description") public String pic_description; @SerializedName("date_and_time") public String date_and_time; public Pictures(String id , String uid , String url , String lati , String longi , String desc , String datime) { this.id = id; this.user_id = uid; this.latitude = lati; this.longitude = longi; this.pic_url = url; this.pic_description = desc; this.date_and_time = datime; } }
92399e841e29d6c62424bccd449edfcf73360fc3
1,125
java
Java
app/src/main/java/com/smarthane/admiral/demo/mvp/model/UserModel.java
smarthane/AdmiralComponent
c93219e7fec17c5215118557625bade977bf55c3
[ "Apache-2.0" ]
1
2020-01-03T05:36:44.000Z
2020-01-03T05:36:44.000Z
app/src/main/java/com/smarthane/admiral/demo/mvp/model/UserModel.java
smarthane/AdmiralComponent
c93219e7fec17c5215118557625bade977bf55c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/smarthane/admiral/demo/mvp/model/UserModel.java
smarthane/AdmiralComponent
c93219e7fec17c5215118557625bade977bf55c3
[ "Apache-2.0" ]
1
2019-11-30T07:52:33.000Z
2019-11-30T07:52:33.000Z
30.405405
79
0.752
998,892
package com.smarthane.admiral.demo.mvp.model; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.OnLifecycleEvent; import com.smarthane.admiral.core.base.AppComponent; import com.smarthane.admiral.core.mvp.BaseModel; import com.smarthane.admiral.core.util.LogUtils; import com.smarthane.admiral.demo.mvp.contract.UserContract; import com.smarthane.admiral.demo.mvp.model.api.service.UserService; import com.smarthane.admiral.demo.mvp.model.entity.User; import java.util.List; import io.reactivex.Observable; public class UserModel extends BaseModel implements UserContract.Model { public static final int USERS_PER_PAGE = 10; public UserModel() { } @Override public Observable<List<User>> getUsers(int lastIdQueried, boolean update) { // 使用rxcache缓存,上拉刷新则不读取缓存,加载更多读取缓存 return AppComponent.get().fetchRepositoryManager() .obtainRetrofitService(UserService.class) .getUsers(lastIdQueried, USERS_PER_PAGE); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void onPause() { LogUtils.debugInfo("Release Resource"); } }
92399fa4eb0e123049045477687d02d8fdcfdfd6
2,840
java
Java
proFL-plugin-2.0.3/org/codehaus/groovy/runtime/callsite/GetEffectivePogoPropertySite.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
proFL-plugin-2.0.3/org/codehaus/groovy/runtime/callsite/GetEffectivePogoPropertySite.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
proFL-plugin-2.0.3/org/codehaus/groovy/runtime/callsite/GetEffectivePogoPropertySite.java
ycj123/Research-Project
08296e0075ba0c13204944b1bc1a96a7b8d2f023
[ "MIT" ]
null
null
null
36.883117
165
0.691549
998,893
// // Decompiled by Procyon v0.5.36 // package org.codehaus.groovy.runtime.callsite; import groovy.lang.GroovyRuntimeException; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import groovy.lang.GroovyObject; import org.codehaus.groovy.runtime.GroovyCategorySupport; import groovy.lang.MetaProperty; import groovy.lang.MetaClass; class GetEffectivePogoPropertySite extends AbstractCallSite { private final MetaClass metaClass; private final MetaProperty effective; public GetEffectivePogoPropertySite(final CallSite site, final MetaClass metaClass, final MetaProperty effective) { super(site); this.metaClass = metaClass; this.effective = effective; } @Override public final Object callGetProperty(final Object receiver) throws Throwable { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != this.metaClass) { return this.createGetPropertySite(receiver).getProperty(receiver); } try { return this.effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } @Override public final CallSite acceptGetProperty(final Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != this.metaClass) { return this.createGetPropertySite(receiver); } return this; } @Override public final Object callGroovyObjectGetProperty(final Object receiver) throws Throwable { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != this.metaClass) { return this.createGetPropertySite(receiver).getProperty(receiver); } try { return this.effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } @Override public final CallSite acceptGroovyObjectGetProperty(final Object receiver) { if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject)receiver).getMetaClass() != this.metaClass) { return this.createGroovyObjectGetPropertySite(receiver); } return this; } @Override public final Object getProperty(final Object receiver) throws Throwable { try { return this.effective.getProperty(receiver); } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } }
9239a0c56ce4217727eca62b09673502058173ca
21,699
java
Java
mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java
codejamninja/james-project
6ce8443b69e8e0d6576c42c9c14b8a0e5d54e9c1
[ "Apache-2.0" ]
634
2015-12-21T20:24:06.000Z
2022-03-24T09:57:48.000Z
mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java
codejamninja/james-project
6ce8443b69e8e0d6576c42c9c14b8a0e5d54e9c1
[ "Apache-2.0" ]
4,148
2015-09-14T15:59:06.000Z
2022-03-31T10:29:10.000Z
mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java
codejamninja/james-project
6ce8443b69e8e0d6576c42c9c14b8a0e5d54e9c1
[ "Apache-2.0" ]
392
2015-07-16T07:04:59.000Z
2022-03-28T09:37:53.000Z
42.463796
159
0.65639
998,894
/**************************************************************** * 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.james.transport.mailets; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.james.javax.MultipartUtil; import org.apache.james.mime4j.codec.DecodeMonitor; import org.apache.james.mime4j.codec.DecoderUtil; import org.apache.mailet.Attribute; import org.apache.mailet.AttributeName; import org.apache.mailet.AttributeUtils; import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.MailetException; import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.fge.lambdas.Throwing; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; /** * <p> * Remove attachments from a Message. Supports simple removal, storing to file, * or storing to mail attributes. * </p> * <p> * Configuration: * </p> * <p> * * <pre> * &lt;mailet match=&quot;All&quot; class=&quot;StripAttachment&quot; &gt; * &lt;pattern &gt;.*\.xls &lt;/pattern&gt; &lt;!-- The regular expression that must be matched -- &gt; * &lt;!-- notpattern &gt;.*\.xls &lt;/notpattern--&gt; &lt;!-- The regular expression that must be matched -- &gt; * &lt;mimeType&gt;text/calendar&lt;/mimeType&gt; &lt;!-- The matching mimeType -- &gt; * &lt;directory &gt;c:\temp\james_attach &lt;/directory&gt; &lt;!-- The directory to save to -- &gt; * &lt;remove &gt;all &lt;/remove&gt; &lt;!-- either &quot;no&quot;, &quot;matched&quot;, &quot;all&quot; -- &gt; * &lt;!-- attribute&gt;my.attribute.name&lt;/attribute --&gt; * &lt;/mailet &gt; * * At least one of pattern, notpattern and mimeType is required. * </pre> * * </p> */ public class StripAttachment extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(StripAttachment.class); @SuppressWarnings("unchecked") private static final Class<Map<String, byte[]>> MAP_STRING_BYTES_CLASS = (Class<Map<String, byte[]>>) (Object) Map.class; @SuppressWarnings("unchecked") private static final Class<List<AttributeValue<String>>> LIST_OF_STRINGS = (Class<List<AttributeValue<String>>>)(Object) List.class; private static final String MULTIPART_MIME_TYPE = "multipart/*"; public static final String PATTERN_PARAMETER_NAME = "pattern"; public static final String NOTPATTERN_PARAMETER_NAME = "notpattern"; public static final String MIMETYPE_PARAMETER_NAME = "mimeType"; public static final String ATTRIBUTE_PARAMETER_NAME = "attribute"; public static final String DIRECTORY_PARAMETER_NAME = "directory"; // Either "no", "matched", "all" public static final String REMOVE_ATTACHMENT_PARAMETER_NAME = "remove"; // Either "true", "false" public static final String DECODE_FILENAME_PARAMETER_NAME = "decodeFilename"; public static final String REPLACE_FILENAME_PATTERN_PARAMETER_NAME = "replaceFilenamePattern"; public static final String REMOVE_NONE = "no"; public static final String REMOVE_ALL = "all"; public static final String REMOVE_MATCHED = "matched"; public static final AttributeName REMOVED_ATTACHMENTS = AttributeName.of("org.apache.james.mailet.standard.mailets.StripAttachment.removed"); public static final AttributeName SAVED_ATTACHMENTS = AttributeName.of("org.apache.james.mailet.standard.mailets.StripAttachment.saved"); public static final boolean DECODE_FILENAME_DEFAULT_VALUE = false; @VisibleForTesting String removeAttachments; private String directoryName; private Optional<AttributeName> attributeName; private Pattern regExPattern; private Pattern notRegExPattern; private String mimeType; private boolean decodeFilename; private List<ReplacingPattern> filenameReplacingPatterns; /** * Checks if the mandatory parameters are present, creates the directory to * save the files in (if not present). * * @throws MailetException */ @Override public void init() throws MailetException { regExPattern = regExFromParameter(PATTERN_PARAMETER_NAME); notRegExPattern = regExFromParameter(NOTPATTERN_PARAMETER_NAME); mimeType = getInitParameter(MIMETYPE_PARAMETER_NAME); if (regExPattern == null && notRegExPattern == null && Strings.isNullOrEmpty(mimeType)) { throw new MailetException("At least one of '" + PATTERN_PARAMETER_NAME + "', '" + NOTPATTERN_PARAMETER_NAME + "' or '" + MIMETYPE_PARAMETER_NAME + "' parameter should be provided."); } directoryName = getInitParameter(DIRECTORY_PARAMETER_NAME); attributeName = getInitParameterAsOptional(ATTRIBUTE_PARAMETER_NAME).map(AttributeName::of); removeAttachments = getInitParameter(REMOVE_ATTACHMENT_PARAMETER_NAME, REMOVE_NONE).toLowerCase(Locale.US); if (!removeAttachments.equals(REMOVE_MATCHED) && !removeAttachments.equals(REMOVE_ALL) && !removeAttachments.equals(REMOVE_NONE)) { throw new MailetException(String.format("Unknown remove parameter value '%s' waiting for '%s', '%s' or '%s'.", removeAttachments, REMOVE_MATCHED, REMOVE_ALL, REMOVE_NONE)); } if (directoryName != null) { createDirectory(); } decodeFilename = getBooleanParameter(getInitParameter(DECODE_FILENAME_PARAMETER_NAME), DECODE_FILENAME_DEFAULT_VALUE); String replaceFilenamePattern = getInitParameter(REPLACE_FILENAME_PATTERN_PARAMETER_NAME); if (replaceFilenamePattern != null) { filenameReplacingPatterns = new PatternExtractor().getPatternsFromString(replaceFilenamePattern); } else { filenameReplacingPatterns = ImmutableList.of(); } logConfiguration(); } private Pattern regExFromParameter(String patternParameterName) throws MailetException { String patternString = getInitParameter(patternParameterName); try { if (patternString != null) { return Pattern.compile(patternString); } return null; } catch (Exception e) { throw new MailetException("Could not compile regex [" + patternString + "]."); } } private void createDirectory() throws MailetException { try { FileUtils.forceMkdir(new File(directoryName)); } catch (Exception e) { throw new MailetException("Could not create directory [" + directoryName + "].", e); } } private void logConfiguration() { if (LOGGER.isDebugEnabled()) { StringBuilder logMessage = new StringBuilder(); logMessage.append("StripAttachment is initialised with regex pattern ["); if (regExPattern != null) { logMessage.append(regExPattern.pattern()); } logMessage.append(" / "); if (notRegExPattern != null) { logMessage.append(notRegExPattern.pattern()); } logMessage.append(']'); if (directoryName != null) { logMessage.append(" and will save to directory ["); logMessage.append(directoryName); logMessage.append(']'); } attributeName.ifPresent(attributeName -> { logMessage.append(" and will store attachments to attribute ["); logMessage.append(attributeName.asString()); logMessage.append(']'); }); LOGGER.debug(logMessage.toString()); } } /** * Service the mail: scan it for attachments matching the pattern. * If a filename matches the pattern: * - the file is stored (using its name) in the given directory (if directoryName is given in the mailet configuration) * and the filename is stored in 'saved' mail list attribute * - the part is removed (when removeAttachments mailet configuration property is 'all' or 'matched') * and the filename is stored in 'removed' mail list attribute * - the part filename and its content is stored in mail map attribute (if attributeName is given in the mailet configuration) * * @param mail * The mail to service * @throws MailetException * Thrown when an error situation is encountered. */ @Override public void service(Mail mail) throws MailetException { MimeMessage message = getMessageFromMail(mail); if (isMultipart(message)) { processMultipartPartMessage(message, mail); } } private boolean isMultipart(Part part) throws MailetException { try { return part.isMimeType(MULTIPART_MIME_TYPE); } catch (MessagingException e) { throw new MailetException("Could not retrieve contenttype of MimePart.", e); } } private MimeMessage getMessageFromMail(Mail mail) throws MailetException { try { return mail.getMessage(); } catch (MessagingException e) { throw new MailetException("Could not retrieve message from Mail object", e); } } @Override public String getMailetInfo() { return "StripAttachment"; } /** * Checks every part in this part (if it is a Multipart) for having a * filename that matches the pattern. * If the name matches: * - the file is stored (using its name) in the given directory (if directoryName is given in the mailet configuration) * and the filename is stored in 'saved' mail list attribute * - the part is removed (when removeAttachments mailet configuration property is 'all' or 'matched') * and the filename is stored in 'removed' mail list attribute * - the part filename and its content is stored in mail map attribute (if attributeName is given in the mailet configuration) * * Note: this method is recursive. * * @param part * The part to analyse. * @param mail * @return True if one of the subpart was removed * @throws Exception */ @VisibleForTesting boolean processMultipartPartMessage(Part part, Mail mail) throws MailetException { if (!isMultipart(part)) { return false; } try { Multipart multipart = (Multipart) part.getContent(); boolean atLeastOneRemoved = false; boolean subpartHasBeenChanged = false; List<BodyPart> bodyParts = MultipartUtil.retrieveBodyParts(multipart); for (BodyPart bodyPart: bodyParts) { if (isMultipart(bodyPart)) { if (processMultipartPartMessage(bodyPart, mail)) { subpartHasBeenChanged = true; } } else { if (shouldBeRemoved(bodyPart, mail)) { multipart.removeBodyPart(bodyPart); atLeastOneRemoved = true; } } } if (atLeastOneRemoved || subpartHasBeenChanged) { updateBodyPart(part, multipart); } return atLeastOneRemoved || subpartHasBeenChanged; } catch (Exception e) { LOGGER.error("Failing while analysing part for attachments (StripAttachment mailet).", e); return false; } } private void updateBodyPart(Part part, Multipart newPartContent) throws MessagingException { part.setContent(newPartContent); if (part instanceof Message) { ((Message) part).saveChanges(); } } private boolean shouldBeRemoved(BodyPart bodyPart, Mail mail) throws MessagingException, Exception { String fileName = getFilename(bodyPart); boolean shouldRemove = removeAttachments.equals(REMOVE_ALL); String decodedName = DecoderUtil.decodeEncodedWords(fileName, DecodeMonitor.SILENT); if (isMatching(bodyPart, decodedName)) { storeBodyPartAsFile(bodyPart, mail, decodedName); storeBodyPartAsMailAttribute(bodyPart, mail, decodedName); if (removeAttachments.equals(REMOVE_MATCHED)) { shouldRemove = true; } } storeFileNameAsAttribute(mail, AttributeValue.of(fileName), shouldRemove); return shouldRemove; } private boolean isMatching(BodyPart bodyPart, String fileName) throws MessagingException { return fileNameMatches(fileName) || bodyPart.isMimeType(mimeType); } private void storeBodyPartAsFile(BodyPart bodyPart, Mail mail, String fileName) throws Exception { if (directoryName != null) { saveAttachmentToFile(bodyPart, Optional.of(fileName)).ifPresent(filename -> addFilenameToAttribute(mail, AttributeValue.of(filename), SAVED_ATTACHMENTS) ); } } private void addFilenameToAttribute(Mail mail, AttributeValue<String> attributeValue, AttributeName attributeName) { Function<List<AttributeValue<String>>, List<AttributeValue<?>>> typeWeakner = values -> values.stream().map(value -> (AttributeValue<?>) value).collect(Collectors.toList()); ImmutableList.Builder<AttributeValue<?>> attributeValues = ImmutableList.<AttributeValue<?>>builder() .addAll(AttributeUtils .getValueAndCastFromMail(mail, attributeName, LIST_OF_STRINGS) .map(typeWeakner) .orElse(new ArrayList<>())); attributeValues.add(attributeValue); mail.setAttribute(new Attribute(attributeName, AttributeValue.of(attributeValues.build()))); } private void storeBodyPartAsMailAttribute(BodyPart bodyPart, Mail mail, String fileName) throws IOException, MessagingException { attributeName.ifPresent(Throwing.<AttributeName>consumer(attributeName -> addPartContent(bodyPart, mail, fileName, attributeName)).sneakyThrow()); } private void addPartContent(BodyPart bodyPart, Mail mail, String fileName, AttributeName attributeName) throws IOException, MessagingException { ImmutableMap.Builder<String, byte[]> fileNamesToPartContent = AttributeUtils .getValueAndCastFromMail(mail, attributeName, MAP_STRING_BYTES_CLASS) .map(ImmutableMap.<String, byte[]>builder()::putAll) .orElse(ImmutableMap.builder()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bodyPart.writeTo(new BufferedOutputStream(byteArrayOutputStream)); fileNamesToPartContent.put(fileName, byteArrayOutputStream.toByteArray()); mail.setAttribute(new Attribute(attributeName, AttributeValue.ofAny(fileNamesToPartContent.build()))); } private void storeFileNameAsAttribute(Mail mail, AttributeValue<String> fileName, boolean hasToBeStored) { if (hasToBeStored) { addFilenameToAttribute(mail, fileName, REMOVED_ATTACHMENTS); } } @VisibleForTesting String getFilename(BodyPart bodyPart) { try { String fileName = bodyPart.getFileName(); if (fileName != null) { return renameWithConfigurationPattern(decodeFilename(fileName)); } } catch (Exception e) { LOGGER.warn("Unparsable filename, using a random filename instead.", e); } return randomFilename(); } private String randomFilename() { return UUID.randomUUID().toString(); } private String renameWithConfigurationPattern(String fileName) { if (filenameReplacingPatterns != null) { boolean debug = false; return new ContentReplacer(debug).applyPatterns(filenameReplacingPatterns, fileName); } return fileName; } private String decodeFilename(String fileName) throws UnsupportedEncodingException { if (decodeFilename) { return MimeUtility.decodeText(fileName); } return fileName; } /** * Checks if the given name matches the pattern. * * @param name * The name to check for a match. * @return True if a match is found, false otherwise. */ @VisibleForTesting boolean fileNameMatches(String name) { if (patternsAreEquals()) { return false; } boolean result = isMatchingPattern(name, regExPattern).orElse(false) || !isMatchingPattern(name, notRegExPattern).orElse(true); LOGGER.debug("attachment {} {}", name, result ? "matches" : "does not match"); return result; } private boolean patternsAreEquals() { return regExPattern != null && notRegExPattern != null && regExPattern.pattern().equals(notRegExPattern.pattern()); } private Optional<Boolean> isMatchingPattern(String name, Pattern pattern) { if (pattern != null) { return Optional.of(pattern.matcher(name).matches()); } return Optional.empty(); } /** * Saves the content of the part to a file in the given directory, using the * name of the part. Created files have unique names. * * @param part * The MIME part to save. * @return * @throws Exception */ @VisibleForTesting Optional<String> saveAttachmentToFile(Part part, Optional<String> fileName) throws Exception { try { File outputFile = outputFile(part, fileName); LOGGER.debug("saving content of {}...", outputFile.getName()); IOUtils.copy(part.getInputStream(), new FileOutputStream(outputFile)); return Optional.of(outputFile.getName()); } catch (Exception e) { LOGGER.error("Error while saving contents of", e); return Optional.empty(); } } private File outputFile(Part part, Optional<String> fileName) throws MessagingException, IOException { Optional<String> maybePartFileName = Optional.ofNullable(part.getFileName()); return createTempFile(fileName.orElse(maybePartFileName.orElse(null))); } private File createTempFile(String originalFileName) throws IOException { OutputFileName outputFileName = OutputFileName.from(originalFileName); return File.createTempFile(outputFileName.getPrefix(), outputFileName.getSuffix(), new File(directoryName)); } @VisibleForTesting static class OutputFileName { private static final char PAD_CHAR = '_'; private static final int MIN_LENGTH = 3; private static final String DEFAULT_SUFFIX = ".bin"; public static OutputFileName from(String originalFileName) { if (!originalFileName.contains(".")) { return new OutputFileName(prependedPrefix(originalFileName), DEFAULT_SUFFIX); } int lastDotPosition = originalFileName.lastIndexOf("."); return new OutputFileName(prependedPrefix(originalFileName.substring(0, lastDotPosition)), originalFileName.substring(lastDotPosition)); } @VisibleForTesting static String prependedPrefix(String prefix) { return Strings.padStart(prefix, MIN_LENGTH, PAD_CHAR); } private final String prefix; private final String suffix; private OutputFileName(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } public String getPrefix() { return prefix; } public String getSuffix() { return suffix; } } }
9239a1f5a252908107aec31d2a6e604fb968a030
9,164
java
Java
tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/shuffle/orderedgrouped/MapOutput.java
lucasaytt/tez-0.9.2
6191252af69ac4340cb898209e3ba5deb857a594
[ "Apache-2.0" ]
384
2015-01-13T04:17:50.000Z
2022-03-28T23:21:30.000Z
tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/shuffle/orderedgrouped/MapOutput.java
lucasaytt/tez-0.9.2
6191252af69ac4340cb898209e3ba5deb857a594
[ "Apache-2.0" ]
158
2015-06-08T05:50:17.000Z
2022-03-31T16:29:09.000Z
tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/shuffle/orderedgrouped/MapOutput.java
lucasaytt/tez-0.9.2
6191252af69ac4340cb898209e3ba5deb857a594
[ "Apache-2.0" ]
448
2015-01-05T22:18:00.000Z
2022-03-30T09:47:08.000Z
29.850163
122
0.678088
998,895
/** * 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.tez.runtime.library.common.shuffle.orderedgrouped; import java.io.IOException; import java.io.OutputStream; import java.util.Comparator; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BoundedByteArrayOutputStream; import org.apache.hadoop.io.FileChunk; import org.apache.tez.runtime.library.common.InputAttemptIdentifier; import org.apache.tez.runtime.library.common.task.local.output.TezTaskOutputFiles; abstract class MapOutput { private static final Logger LOG = LoggerFactory.getLogger(MapOutput.class); private static AtomicInteger ID = new AtomicInteger(0); public enum Type { WAIT, MEMORY, DISK, DISK_DIRECT } private final int id; private InputAttemptIdentifier attemptIdentifier; private final boolean primaryMapOutput; protected final FetchedInputAllocatorOrderedGrouped callback; private MapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, boolean primaryMapOutput) { this.id = ID.incrementAndGet(); this.attemptIdentifier = attemptIdentifier; this.callback = callback; this.primaryMapOutput = primaryMapOutput; } public static MapOutput createDiskMapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, long size, Configuration conf, int fetcher, boolean primaryMapOutput, TezTaskOutputFiles mapOutputFile) throws IOException { FileSystem fs = FileSystem.getLocal(conf).getRaw(); Path outputPath = mapOutputFile.getInputFileForWrite( attemptIdentifier.getInputIdentifier(), attemptIdentifier.getSpillEventId(), size); // Files are not clobbered due to the id being appended to the outputPath in the tmpPath, // otherwise fetches for the same task but from different attempts would clobber each other. Path tmpOutputPath = outputPath.suffix(String.valueOf(fetcher)); long offset = 0; DiskMapOutput mapOutput = new DiskMapOutput(attemptIdentifier, callback, size, outputPath, offset, primaryMapOutput, tmpOutputPath); mapOutput.disk = fs.create(tmpOutputPath); return mapOutput; } public static MapOutput createLocalDiskMapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, Path path, long offset, long size, boolean primaryMapOutput) { return new DiskDirectMapOutput(attemptIdentifier, callback, size, path, offset, primaryMapOutput); } public static MapOutput createMemoryMapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, int size, boolean primaryMapOutput) { return new InMemoryMapOutput(attemptIdentifier, callback, size, primaryMapOutput); } public static MapOutput createWaitMapOutput(InputAttemptIdentifier attemptIdentifier) { return new WaitMapOutput(attemptIdentifier); } public boolean isPrimaryMapOutput() { return primaryMapOutput; } @Override public boolean equals(Object obj) { if (obj instanceof MapOutput) { return id == ((MapOutput)obj).id; } return false; } @Override public int hashCode() { return id; } public FileChunk getOutputPath() { return null; } public byte[] getMemory() { return null; } public OutputStream getDisk() { return null; } public InputAttemptIdentifier getAttemptIdentifier() { return this.attemptIdentifier; } public abstract Type getType(); public long getSize() { return -1; } public void commit() throws IOException { } public void abort() { } public String toString() { return "MapOutput( AttemptIdentifier: " + attemptIdentifier + ", Type: " + getType() + ")"; } public static class MapOutputComparator implements Comparator<MapOutput> { public int compare(MapOutput o1, MapOutput o2) { if (o1.id == o2.id) { return 0; } if (o1.getSize() < o2.getSize()) { return -1; } else if (o1.getSize() > o2.getSize()) { return 1; } if (o1.id < o2.id) { return -1; } else { return 1; } } } private static class DiskDirectMapOutput extends MapOutput { private final FileChunk outputPath; private DiskDirectMapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, long size, Path outputPath, long offset, boolean primaryMapOutput) { super(attemptIdentifier, callback, primaryMapOutput); this.outputPath = new FileChunk(outputPath, offset, size, true, attemptIdentifier); } @Override public FileChunk getOutputPath() { return outputPath; } @Override public long getSize() { return outputPath.getLength(); } @Override public void commit() throws IOException { callback.closeOnDiskFile(outputPath); } @Override public void abort() { // nothing to do } @Override public Type getType() { return Type.DISK_DIRECT; } } private static class DiskMapOutput extends MapOutput { private final Path tmpOutputPath; private final FileChunk outputPath; private OutputStream disk; private DiskMapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, long size, Path outputPath, long offset, boolean primaryMapOutput, Path tmpOutputPath) { super(attemptIdentifier, callback, primaryMapOutput); this.tmpOutputPath = tmpOutputPath; this.disk = null; this.outputPath = new FileChunk(outputPath, offset, size, false, attemptIdentifier); } @Override public FileChunk getOutputPath() { return outputPath; } @Override public OutputStream getDisk() { return disk; } @Override public long getSize() { return outputPath.getLength(); } @Override public void commit() throws IOException { callback.getLocalFileSystem().rename(tmpOutputPath, outputPath.getPath()); callback.closeOnDiskFile(outputPath); } @Override public void abort() { try { callback.getLocalFileSystem().delete(tmpOutputPath, true); } catch (IOException ie) { LOG.info("failure to clean up " + tmpOutputPath, ie); } } @Override public Type getType() { return Type.DISK; } } private static class InMemoryMapOutput extends MapOutput { private byte[] byteArray; private InMemoryMapOutput(InputAttemptIdentifier attemptIdentifier, FetchedInputAllocatorOrderedGrouped callback, long size, boolean primaryMapOutput) { super(attemptIdentifier, callback, primaryMapOutput); this.byteArray = new byte[(int)size]; } @Override public byte[] getMemory() { return byteArray; } @Override public long getSize() { return byteArray.length; } @Override public void commit() throws IOException { callback.closeInMemoryFile(this); } @Override public void abort() { callback.unreserve(byteArray.length); } @Override public Type getType() { return Type.MEMORY; } } private static class WaitMapOutput extends MapOutput { private WaitMapOutput(InputAttemptIdentifier attemptIdentifier) { super(attemptIdentifier, null, false); } @Override public void commit() throws IOException { throw new IOException("Cannot commit MapOutput of type WAIT!"); } @Override public void abort() { throw new IllegalArgumentException("Cannot commit MapOutput of type WAIT!"); } @Override public Type getType() { return Type.WAIT; } } }
9239a293845256cb916bdd528cb22420619b3d41
3,621
java
Java
core/src/test/java/org/apache/mahout/ga/watchmaker/MahoutEvaluatorTest.java
VertiPub/mahout
da10c26f8fbf3edfc7f7ab26568a5a19bfbc39a3
[ "Apache-2.0" ]
15
2015-02-27T17:14:52.000Z
2018-03-27T10:13:24.000Z
core/src/test/java/org/apache/mahout/ga/watchmaker/MahoutEvaluatorTest.java
VertiPub/mahout
da10c26f8fbf3edfc7f7ab26568a5a19bfbc39a3
[ "Apache-2.0" ]
8
2018-11-12T11:44:53.000Z
2022-02-01T01:13:42.000Z
core/src/test/java/org/apache/mahout/ga/watchmaker/MahoutEvaluatorTest.java
iotashan/mahout
eb7b2cd1ec58e399d5cdae3cc548b605b7620baf
[ "Apache-2.0" ]
25
2015-01-07T16:00:14.000Z
2018-02-24T15:36:48.000Z
38.115789
97
0.747031
998,896
/** * 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.mahout.ga.watchmaker; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.mahout.common.MahoutTestCase; import org.apache.mahout.ga.watchmaker.utils.DummyCandidate; import org.apache.mahout.ga.watchmaker.utils.DummyEvaluator; import org.apache.mahout.common.StringUtils; import org.apache.mahout.common.iterator.FileLineIterable; import org.junit.Test; import org.uncommons.watchmaker.framework.FitnessEvaluator; import java.io.IOException; import java.util.List; public final class MahoutEvaluatorTest extends MahoutTestCase { private static final int POPULATION_SIZE = 100; @Test public void testEvaluate() throws Exception { // candidate population List<DummyCandidate> population = DummyCandidate.generatePopulation(POPULATION_SIZE); // fitness evaluator DummyEvaluator.clearEvaluations(); FitnessEvaluator<DummyCandidate> evaluator = new DummyEvaluator(); // run MahoutEvaluator List<Double> results = Lists.newArrayList(); Path input = getTestTempDirPath("input"); Path output = getTestTempDirPath("output"); MahoutEvaluator.evaluate(evaluator, population, results, input, output); // check results assertEquals("Number of evaluations", POPULATION_SIZE, results.size()); for (int index = 0; index < population.size(); index++) { DummyCandidate candidate = population.get(index); assertEquals("Evaluation of the candidate " + index, DummyEvaluator.getFitness(candidate.getIndex()), results.get(index), EPSILON); } } @Test public void testStoreLoadPopulation() throws Exception { List<DummyCandidate> population = DummyCandidate.generatePopulation(POPULATION_SIZE); Path tempPath = getTestTempFilePath("test.txt"); FileSystem fs = tempPath.getFileSystem(new Configuration()); // store the population MahoutEvaluator.storePopulation(fs, tempPath, population); // load the population List<DummyCandidate> inpop = loadPopulation(fs, tempPath); // check that the file contains the correct population assertEquals("Population size", population.size(), inpop.size()); for (int index = 0; index < population.size(); index++) { assertEquals("Bad candidate " + index, population.get(index), inpop.get(index)); } } private static List<DummyCandidate> loadPopulation(FileSystem fs, Path f) throws IOException { List<DummyCandidate> population = Lists.newArrayList(); FSDataInputStream in = fs.open(f); for (String line : new FileLineIterable(in)) { population.add(StringUtils.<DummyCandidate>fromString(line)); } return population; } }
9239a3cced90d7a17c076a4cec2411dba99420f3
1,025
java
Java
src/main/java/io/adenium/papaya/intermediate/PushInt256.java
Adenium/Adenium
d2eb9952b1c93670113e49affe482c76d4033a99
[ "MIT" ]
null
null
null
src/main/java/io/adenium/papaya/intermediate/PushInt256.java
Adenium/Adenium
d2eb9952b1c93670113e49affe482c76d4033a99
[ "MIT" ]
null
null
null
src/main/java/io/adenium/papaya/intermediate/PushInt256.java
Adenium/Adenium
d2eb9952b1c93670113e49affe482c76d4033a99
[ "MIT" ]
null
null
null
27.702703
81
0.729756
998,897
package io.adenium.papaya.intermediate; import io.adenium.exceptions.PapayaException; import io.adenium.exceptions.AdeniumException; import io.adenium.papaya.runtime.DefaultHandler; import io.adenium.papaya.runtime.PapayaNumber; import io.adenium.papaya.runtime.Scope; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; public class PushInt256 implements Opcode { private BigInteger value; public PushInt256(BigInteger value) { this.value = value; } @Override public void execute(Scope scope) throws PapayaException { scope.getStack().push(new DefaultHandler(new PapayaNumber(value, true))); } @Override public void read(InputStream stream) throws IOException, AdeniumException { byte value[] = new byte[32]; stream.read(value); this.value = new BigInteger(value); } @Override public void write(OutputStream stream) throws IOException, AdeniumException { } }
9239a493018b146214c53ddec96afd4c61aafac6
2,167
java
Java
model-basic/src/main/java/com/forcam/na/ffwebservices/model/reporting/HitListOperatingStatesMaterialEmbed.java
dalbrx-forcam/java-sdk
c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee
[ "MIT" ]
null
null
null
model-basic/src/main/java/com/forcam/na/ffwebservices/model/reporting/HitListOperatingStatesMaterialEmbed.java
dalbrx-forcam/java-sdk
c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee
[ "MIT" ]
null
null
null
model-basic/src/main/java/com/forcam/na/ffwebservices/model/reporting/HitListOperatingStatesMaterialEmbed.java
dalbrx-forcam/java-sdk
c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee
[ "MIT" ]
2
2020-11-13T18:59:10.000Z
2020-11-13T19:20:25.000Z
28.893333
89
0.413936
998,898
//////////////////////////////////////////////////////////////////////////////// // // Created by DAlbrecht on 10.12.2019. // // Copyright (c) 2006 - 2019 FORCAM GmbH. All rights reserved. //////////////////////////////////////////////////////////////////////////////// package com.forcam.na.ffwebservices.model.reporting; import java.util.ArrayList; import java.util.List; /** * Embed for hit list operating states material report. */ public class HitListOperatingStatesMaterialEmbed { // ------------------------------------------------------------------------ // constants // ------------------------------------------------------------------------ public static String MATERIALS = "materials"; public static String OPERATING_STATES = "operatingStates"; // ------------------------------------------------------------------------ // members // ------------------------------------------------------------------------ private boolean mMaterials; private boolean mOperatingStates; // ------------------------------------------------------------------------ // methods // ------------------------------------------------------------------------ public HitListOperatingStatesMaterialEmbed materials(boolean materials) { mMaterials = materials; return this; } public HitListOperatingStatesMaterialEmbed operatingStates(boolean operatingStates) { mOperatingStates = operatingStates; return this; } @Override public String toString() { final List<String> embeds = new ArrayList<>(); if (this.isMaterials()) { embeds.add(MATERIALS); } if (this.isOperatingStates()) { embeds.add(OPERATING_STATES); } return String.join(",", embeds); } // ------------------------------------------------------------------------ // getters/setters // ------------------------------------------------------------------------ public boolean isOperatingStates() { return mOperatingStates; } public boolean isMaterials() { return mMaterials; } }
9239a570f146638e2c869b884c6db5034dddc15f
1,451
java
Java
plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/controlflow/TrivialIfFixTest.java
erdi/intellij-community
dda25a8a4e6375c6d964cb0197e5c387d585ea9e
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/controlflow/TrivialIfFixTest.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/controlflow/TrivialIfFixTest.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
1
2019-07-18T16:50:52.000Z
2019-07-18T16:50:52.000Z
36.275
75
0.73122
998,899
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.fixes.controlflow; import com.siyeh.ig.IGQuickFixesTestCase; import com.siyeh.ig.controlflow.TrivialIfInspection; public class TrivialIfFixTest extends IGQuickFixesTestCase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(new TrivialIfInspection()); myRelativePath = "controlflow/trivialIf"; myDefaultHint = "Simplify 'if else'"; } public void testComments() { doTest(); } public void testCommentsInAssignment() { doTest(); } public void testNegatedConditional() { doTest(); } public void testNegatedConditional1() { doTest(); } public void testAssert1() { doTest(); } public void testAssert2() { doTest(); } public void testParentheses() { doTest(); } public void testNested() { doTest(); } public void testInCodeBlock() { doTest(); } }
9239a65dcd1d422915cd843cd3ab573b98a8d7f0
2,474
java
Java
app/src/main/java/market/dental/android/FullscreenImageActivity.java
dentalmarket/android-native
c44aafd819a081831b92a67aa92f25b255a4cc71
[ "MIT" ]
null
null
null
app/src/main/java/market/dental/android/FullscreenImageActivity.java
dentalmarket/android-native
c44aafd819a081831b92a67aa92f25b255a4cc71
[ "MIT" ]
35
2017-12-20T08:18:07.000Z
2018-10-03T13:19:58.000Z
app/src/main/java/market/dental/android/FullscreenImageActivity.java
dentalmarket/android
c44aafd819a081831b92a67aa92f25b255a4cc71
[ "MIT" ]
null
null
null
32.986667
180
0.691997
998,900
package market.dental.android; import android.content.Intent; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.github.chrisbanes.photoview.PhotoView; import com.google.gson.JsonParser; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import market.dental.adapter.ProductDetailViewPagerAdapter; public class FullscreenImageActivity extends AppCompatActivity { private ViewPager viewPager; private ProductDetailViewPagerAdapter productDetailViewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_fullscreen_image); getSupportActionBar().hide(); PhotoView photoView = (PhotoView)findViewById(R.id.fullscreen_activity_photo_view); Intent callingActivityIntent = getIntent(); if(callingActivityIntent!=null){ Picasso.with(this) .load(callingActivityIntent.getStringExtra("url")) .fit() .centerInside() .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher) .into(photoView); /* try { viewPager = (ViewPager)findViewById(R.id.activity_product_detail_view_pager); productDetailViewPagerAdapter = new ProductDetailViewPagerAdapter(getApplicationContext(), new JSONArray(callingActivityIntent.getStringExtra("imagesJsonString"))); viewPager.setAdapter(productDetailViewPagerAdapter); } catch (Exception e) { e.printStackTrace(); } */ } TextView closeTextView = (TextView) findViewById(R.id.fullscreen_activity_close); closeTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } }
9239a800706062deb0c013e54889a0276b6d7b0b
526
java
Java
src/com/jinsihou/react/snippets/ReactTemplateProvider.java
jinsihou19/ReactSnippets
3e3e2b23df54d3363909a00e573e29b01ed7f177
[ "MIT" ]
112
2017-11-01T02:19:56.000Z
2022-03-14T11:41:01.000Z
src/com/jinsihou/react/snippets/ReactTemplateProvider.java
jinsihou19/ReactSnippets
3e3e2b23df54d3363909a00e573e29b01ed7f177
[ "MIT" ]
9
2017-12-17T02:51:46.000Z
2021-08-31T06:52:42.000Z
src/com/jinsihou/react/snippets/ReactTemplateProvider.java
jinsihou19/ReactSnippets
3e3e2b23df54d3363909a00e573e29b01ed7f177
[ "MIT" ]
39
2018-03-02T12:56:31.000Z
2022-01-10T19:04:31.000Z
22.869565
76
0.726236
998,901
package com.jinsihou.react.snippets; import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider; import org.jetbrains.annotations.Nullable; /** * @author jinsihou * @date 2017/10/18 */ public class ReactTemplateProvider implements DefaultLiveTemplatesProvider { @Override public String[] getDefaultLiveTemplateFiles() { return new String[]{"liveTemplates/React"}; } @Nullable @Override public String[] getHiddenLiveTemplateFiles() { return new String[0]; } }
9239a963103eb440f4eab83ded65d8ab8bd968db
1,926
java
Java
modules/java_api/org/intel/openvino/compatibility/Blob.java
chenxy1988/openvino_contrib
56d04b546be9e3471755271f072843922cb341f3
[ "Apache-2.0" ]
null
null
null
modules/java_api/org/intel/openvino/compatibility/Blob.java
chenxy1988/openvino_contrib
56d04b546be9e3471755271f072843922cb341f3
[ "Apache-2.0" ]
null
null
null
modules/java_api/org/intel/openvino/compatibility/Blob.java
chenxy1988/openvino_contrib
56d04b546be9e3471755271f072843922cb341f3
[ "Apache-2.0" ]
null
null
null
27.514286
94
0.658879
998,902
// Copyright (C) 2020-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 package org.intel.openvino.compatibility; public class Blob extends IEWrapper { protected Blob(long addr) { super(addr); } public Blob(TensorDesc tensorDesc) { super(GetBlob(tensorDesc.getNativeObjAddr())); } public Blob(TensorDesc tensorDesc, byte[] data) { super(BlobByte(tensorDesc.getNativeObjAddr(), data)); } public Blob(TensorDesc tensorDesc, float[] data) { super(BlobFloat(tensorDesc.getNativeObjAddr(), data)); } public Blob(TensorDesc tensorDesc, int[] data) { super(BlobInt(tensorDesc.getNativeObjAddr(), data)); } public Blob(TensorDesc tensorDesc, long[] data) { super(BlobLong(tensorDesc.getNativeObjAddr(), data)); } public Blob(TensorDesc tensorDesc, long cArray) { super(BlobCArray(tensorDesc.nativeObj, cArray)); } public TensorDesc getTensorDesc() { return new TensorDesc(GetTensorDesc(nativeObj)); } public int size() { return size(nativeObj); } public LockedMemory rmap() { return new LockedMemory(rmap(nativeObj)); } /*----------------------------------- native methods -----------------------------------*/ private native long GetTensorDesc(long addr); private static native long GetBlob(long tensorDesc); private static native long BlobByte(long tensorDesc, byte[] data); private static native long BlobFloat(long tensorDesc, float[] data); private static native long BlobInt(long tensorDesc, int[] data); private static native long BlobLong(long tensorDesc, long[] data); private static native long BlobCArray(long tensorDesc, long cArray); private static native int size(long addr); private static native long rmap(long addr); @Override protected native void delete(long nativeObj); }
9239a9ab69fbc5ec1fe9c5ec4bad521cdc93f742
3,496
java
Java
src/test/java/com/bbva/hancock/sdk/config/HancockConfigTest.java
BBVA/hancock-sdk-java-android
17c620b768432c770e4ae55a9c24b645d18a789b
[ "Apache-2.0" ]
null
null
null
src/test/java/com/bbva/hancock/sdk/config/HancockConfigTest.java
BBVA/hancock-sdk-java-android
17c620b768432c770e4ae55a9c24b645d18a789b
[ "Apache-2.0" ]
null
null
null
src/test/java/com/bbva/hancock/sdk/config/HancockConfigTest.java
BBVA/hancock-sdk-java-android
17c620b768432c770e4ae55a9c24b645d18a789b
[ "Apache-2.0" ]
null
null
null
41.619048
122
0.676773
998,903
package com.bbva.hancock.sdk.config; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; @RunWith(PowerMockRunner.class) @PrepareForTest({HancockConfig.Builder.class}) public class HancockConfigTest { @Test public void testConfig() { final HancockConfig.Builder builder = new HancockConfig.Builder(); final HancockConfig config = builder.withAdapter("http://localhost", "/", 3000) .withBroker("http://localhost", "/", 3001) .withWallet("http://localhost", "/", 3002) .withEnv("dev") .withNode("http://localhost", 3003) .build(); assertTrue("Config OK", config instanceof HancockConfig); assertEquals(config.getAdapter().getPort(), 3000); assertEquals(config.getBroker().getPort(), 3001); assertEquals(config.getWallet().getPort(), 3002); assertEquals(config.getAdapter().getHost(), "http://localhost"); assertEquals(config.getBroker().getHost(), "http://localhost"); assertEquals(config.getWallet().getHost(), "http://localhost"); assertEquals(config.getEnv(), "dev"); assertEquals(config.getNode().getHost(), "http://localhost"); assertEquals(config.getNode().getPort(), 3003); } @Test public void testConfigWithoutParams() { final HancockConfig.Builder builder = new HancockConfig.Builder(); mockStatic(HancockConfig.Builder.class); PowerMockito.doReturn(mock(HancockConfig.Builder.class)).when(mock(HancockConfig.Builder.class)).fromConfigFile(); final HancockConfig config = builder.build(); assertTrue("Config OK", config instanceof HancockConfig); assertEquals(config.getAdapter().getPort(), 3000); assertEquals(config.getBroker().getPort(), 3000); assertEquals(config.getWallet().getPort(), 3000); assertEquals(config.getAdapter().getHost(), "http://localhost"); assertEquals(config.getBroker().getHost(), "ws://localhost"); assertEquals(config.getWallet().getHost(), "http://localhost"); assertEquals(config.getEnv(), "local"); assertEquals(config.getNode().getHost(), "http://localhost"); assertEquals(config.getNode().getPort(), 8545); } @Test public void testConfigBeans() { HancockConfigService service = new HancockConfigService(); Assert.assertNotNull(service); service = new HancockConfigService("host", "base", 80, null); Assert.assertEquals(service.getHost(), "host"); Assert.assertEquals(service.getPort(), 80); Assert.assertEquals(service.getBase(), "base"); } @Test public void testConfigBeans2() { final HancockConfigNode config = new HancockConfigNode("host", 80); Assert.assertEquals(config.getHost(), "host"); Assert.assertEquals(config.getPort(), 80); final HancockConfigNode newConfig = new HancockConfigNode(config); Assert.assertEquals(newConfig.getHost(), "host"); Assert.assertEquals(newConfig.getPort(), 80); } }
9239ab42fe520cbdb462bafaa132b74b06c25742
1,789
java
Java
src/main/java/net/canarymod/api/world/blocks/BlockFace.java
FlintPowered/FlintLib
26bd0a36f4c02148e1c8525d02d5af0b5438e564
[ "Unlicense" ]
19
2015-01-10T02:15:26.000Z
2020-10-06T18:45:08.000Z
src/main/java/net/canarymod/api/world/blocks/BlockFace.java
FlintPowered/FlintLib
26bd0a36f4c02148e1c8525d02d5af0b5438e564
[ "Unlicense" ]
58
2015-01-02T13:00:53.000Z
2017-12-23T14:37:24.000Z
src/main/java/net/canarymod/api/world/blocks/BlockFace.java
FlintPowered/FlintLib
26bd0a36f4c02148e1c8525d02d5af0b5438e564
[ "Unlicense" ]
31
2015-01-25T09:59:30.000Z
2021-07-04T02:07:56.000Z
21.297619
71
0.579094
998,904
package net.canarymod.api.world.blocks; /** * A BlockFace is a side of a block * * @author Chris (damagefilter) * @author Jason Jones (darkdiplomat) */ public enum BlockFace { BOTTOM(AxisDirection.NEGATIVE, Axis.Y), TOP(AxisDirection.POSITIVE, Axis.Y), NORTH(AxisDirection.NEGATIVE, Axis.Z), SOUTH(AxisDirection.POSITIVE, Axis.Z), WEST(AxisDirection.NEGATIVE, Axis.X), EAST(AxisDirection.POSITIVE, Axis.X), UNKNOWN(null, null); private final AxisDirection direction; private final Axis axis; private BlockFace(AxisDirection direction, Axis axis) { this.direction = direction; this.axis = axis; } /** * Return this faces normal direction (The byte value to this face) * * @return the face byte value */ public byte getByte() { return (byte)ordinal(); } public Axis getAxis() { return axis; } public AxisDirection getDirection() { return direction; } /** * Get a BlockFace from byte * * @param normal * the facing byte value * * @return the {@link BlockFace} */ public static BlockFace fromByte(byte normal) { if (normal >= 6 || normal <= -1) { return UNKNOWN; } return values()[normal]; } public static enum AxisDirection { POSITIVE, NEGATIVE } public static enum Axis { X(Plane.HORIZONTAL), Y(Plane.VERTICAL), Z(Plane.HORIZONTAL); private final Plane plane; private Axis(Plane plane) { this.plane = plane; } public Plane getPlane() { return plane; } } public static enum Plane { HORIZONTAL, VERTICAL } }
9239ac379012adb6bf28a125fd21a1975f9f7ce5
2,498
java
Java
opensrp-eusm/src/test/java/org/smartregister/eusm/BaseUnitTest.java
OpenSRP/opensrp-client-eusm
56ec0f71295337fbc7773e8a74a38f12771c34b1
[ "Apache-2.0" ]
null
null
null
opensrp-eusm/src/test/java/org/smartregister/eusm/BaseUnitTest.java
OpenSRP/opensrp-client-eusm
56ec0f71295337fbc7773e8a74a38f12771c34b1
[ "Apache-2.0" ]
65
2020-10-09T16:00:17.000Z
2021-04-13T08:37:21.000Z
opensrp-eusm/src/test/java/org/smartregister/eusm/BaseUnitTest.java
opensrp/opensrp-client-eusm
56ec0f71295337fbc7773e8a74a38f12771c34b1
[ "Apache-2.0" ]
1
2021-01-27T13:05:23.000Z
2021-01-27T13:05:23.000Z
46.259259
138
0.818255
998,905
package org.smartregister.eusm; import android.os.Build; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.joda.time.DateTime; import org.junit.Rule; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.smartregister.eusm.shadow.BackgroundLayerShadow; import org.smartregister.eusm.shadow.CustomFontTextViewShadow; import org.smartregister.eusm.shadow.KujakuMapViewShadow; import org.smartregister.eusm.shadow.LayerShadow; import org.smartregister.eusm.shadow.LineLayerShadow; import org.smartregister.eusm.shadow.MapViewShadow; import org.smartregister.eusm.shadow.RasterLayerShadow; import org.smartregister.eusm.shadow.RasterSourceShadow; import org.smartregister.eusm.shadow.SQLiteDatabaseShadow; import org.smartregister.eusm.shadow.SymbolLayerShadow; import org.smartregister.eusm.shadow.TaskingMapViewShadow; import org.smartregister.eusm.shadow.VectorSourceShadow; import org.smartregister.util.DateTimeTypeConverter; @RunWith(RobolectricTestRunner.class) @PowerMockRunnerDelegate(RobolectricTestRunner.class) @Config(application = TestEusmApplication.class, shadows = {SymbolLayerShadow.class, LayerShadow.class, TaskingMapViewShadow.class, KujakuMapViewShadow.class, MapViewShadow.class, SQLiteDatabaseShadow.class, CustomFontTextViewShadow.class, VectorSourceShadow.class, BackgroundLayerShadow.class, RasterLayerShadow.class, LineLayerShadow.class, RasterSourceShadow.class}, sdk = Build.VERSION_CODES.P) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public abstract class BaseUnitTest { protected static final String DUMMY_USERNAME = "myusername"; protected static final char[] DUMMY_PASSWORD = "mypassword".toCharArray(); protected static Gson taskGson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter("yyyy-MM-dd'T'HHmm")) .serializeNulls().create(); protected final int ASYNC_TIMEOUT = 2000; @Rule public MockitoRule rule = MockitoJUnit.rule(); protected static String getString(int stringResourceId) { return RuntimeEnvironment.application.getResources().getString(stringResourceId); } }
9239ac3ef714095073d8aca16503ce944418fb19
1,416
java
Java
service/src/main/java/pl/edu/agh/io/wishlist/service/IUserService.java
lgajewski/AGH-WishList-v2
564ba6a74bfc03276b7e7760ccf54528cd02b249
[ "Apache-2.0" ]
null
null
null
service/src/main/java/pl/edu/agh/io/wishlist/service/IUserService.java
lgajewski/AGH-WishList-v2
564ba6a74bfc03276b7e7760ccf54528cd02b249
[ "Apache-2.0" ]
null
null
null
service/src/main/java/pl/edu/agh/io/wishlist/service/IUserService.java
lgajewski/AGH-WishList-v2
564ba6a74bfc03276b7e7760ccf54528cd02b249
[ "Apache-2.0" ]
null
null
null
27.764706
80
0.791667
998,906
package pl.edu.agh.io.wishlist.service; import pl.edu.agh.io.wishlist.domain.PasswordResetToken; import pl.edu.agh.io.wishlist.domain.User; import pl.edu.agh.io.wishlist.domain.VerificationToken; import pl.edu.agh.io.wishlist.domain.validation.EmailExistsException; import pl.edu.agh.io.wishlist.service.exceptions.UserNotFoundException; import pl.edu.agh.io.wishlist.domain.UserDto; import java.util.Collection; public interface IUserService { Collection<User> getUsers(); void update(User user) throws UserNotFoundException; User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; User getUser(String verificationToken); User getUserByEmail(String email); User getUserByUsername(String username); void saveRegisteredUser(User user); void deleteUser(User user); void createVerificationTokenForUser(User user, String token); VerificationToken getVerificationToken(String VerificationToken); VerificationToken generateNewVerificationToken(String token); void createPasswordResetTokenForUser(User user, String token); User findUserByEmail(String email); PasswordResetToken getPasswordResetToken(String token); User getUserByPasswordResetToken(String token); User getUserByID(String id); void changeUserPassword(User user, String password); boolean checkIfValidOldPassword(User user, String password); }
9239ac9dfa1f29409801ca0111d0ffc024c554ed
656
java
Java
src/main/java/tech/yuwang/function/Defaultable.java
talywy/java8
4db535a0f3f148407ed95ce1a9c5b1357575fc5e
[ "MIT" ]
null
null
null
src/main/java/tech/yuwang/function/Defaultable.java
talywy/java8
4db535a0f3f148407ed95ce1a9c5b1357575fc5e
[ "MIT" ]
null
null
null
src/main/java/tech/yuwang/function/Defaultable.java
talywy/java8
4db535a0f3f148407ed95ce1a9c5b1357575fc5e
[ "MIT" ]
null
null
null
15.642857
66
0.52968
998,907
package tech.yuwang.function; import tech.yuwang.State; import java.util.Random; /** * @author: nnheo@example.com * @date: 2018/1/21 20:59 */ public interface Defaultable { /** * normal method define */ void method(); /** * 获取状态 * @return */ State getState(); /** * default method define */ default void defaultMethod(){ System.out.println("default method has been executed..."); } /** * 获取数字 * * @return */ default int getNum() { Integer i = new Random().nextInt(10); System.out.println("num is:" + i); return i; } }
9239acb021b9f71b2f39e99c0076cfde425ac032
2,502
java
Java
test/integration/src/test/java/com/liferay/faces/test/showcase/portlet/NamespaceGeneralTester.java
jgorny/liferay-faces-bridge-impl
4b3523626f2390401eaf96dbf5f75cdfe3c3baaf
[ "Apache-2.0" ]
11
2015-09-09T13:19:15.000Z
2022-03-15T09:15:31.000Z
test/integration/src/test/java/com/liferay/faces/test/showcase/portlet/NamespaceGeneralTester.java
jgorny/liferay-faces-bridge-impl
4b3523626f2390401eaf96dbf5f75cdfe3c3baaf
[ "Apache-2.0" ]
333
2015-09-30T19:39:31.000Z
2022-01-28T03:37:19.000Z
test/integration/src/test/java/com/liferay/faces/test/showcase/portlet/NamespaceGeneralTester.java
jgorny/liferay-faces-bridge-impl
4b3523626f2390401eaf96dbf5f75cdfe3c3baaf
[ "Apache-2.0" ]
60
2015-09-04T17:35:57.000Z
2022-03-09T17:00:08.000Z
39.714286
130
0.776579
998,908
/** * Copyright (c) 2000-2021 Liferay, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liferay.faces.test.showcase.portlet; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.WebElement; import com.liferay.faces.test.selenium.browser.BrowserDriver; import com.liferay.faces.test.selenium.browser.WaitingAsserter; import com.liferay.faces.test.showcase.TesterBase; /** * @author Kyle Stiemann * @author Philip White */ public class NamespaceGeneralTester extends TesterBase { // Private Constants private static final String PORTLET_NAMESPACE_EQUALS = "portletNamespace="; @Test public void runPortletNamespaceGeneralTest() { BrowserDriver browserDriver = getBrowserDriver(); navigateToUseCase(browserDriver, "portlet", "namespace", "general"); // Test that the portlet namespace is rendered for both examples on the page. WaitingAsserter waitingAsserter = getWaitingAsserter(); WebElement liferayFacesBridgeBody = browserDriver.findElementByXpath( "//div[contains(@class,'liferay-faces-bridge-body')]"); String portletNamespace = liferayFacesBridgeBody.getAttribute("id"); testPortletNamespaceRendered(browserDriver, waitingAsserter, portletNamespace, "//label[contains(.,'Example')][contains(.,'Introducing a var into the EL')]/ancestor::div[@class='showcase-example']//pre"); testPortletNamespaceRendered(browserDriver, waitingAsserter, portletNamespace, "//label[contains(.,'Example')][contains(.,'Output directly to the response')]/ancestor::div[@class='showcase-example']//pre"); } private void testPortletNamespaceRendered(BrowserDriver browserDriver, WaitingAsserter waitingAsserter, String portletNamespace, String preXpath) { waitingAsserter.assertTextPresentInElement(PORTLET_NAMESPACE_EQUALS, preXpath); WebElement pre = browserDriver.findElementByXpath(preXpath); Assert.assertEquals(PORTLET_NAMESPACE_EQUALS + portletNamespace, pre.getText().trim()); } }
9239ae157a8a1b635fe36a1c8cbc1d78537ad90d
1,614
java
Java
s4e-backend/src/main/java/pl/cyfronet/s4e/controller/response/SceneResponse.java
BuildJet/sat4envi
e9f9d322c67bd3f39c4cb299138e15e297b6088b
[ "Apache-2.0" ]
2
2019-10-16T12:35:07.000Z
2020-09-11T12:31:05.000Z
s4e-backend/src/main/java/pl/cyfronet/s4e/controller/response/SceneResponse.java
BuildJet/sat4envi
e9f9d322c67bd3f39c4cb299138e15e297b6088b
[ "Apache-2.0" ]
772
2018-09-19T09:47:48.000Z
2021-12-30T11:48:18.000Z
s4e-backend/src/main/java/pl/cyfronet/s4e/controller/response/SceneResponse.java
BuildJet/sat4envi
e9f9d322c67bd3f39c4cb299138e15e297b6088b
[ "Apache-2.0" ]
2
2021-09-13T17:08:53.000Z
2022-01-13T15:51:43.000Z
29.345455
75
0.740397
998,909
/* * Copyright 2021 ACC Cyfronet AGH * * 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. * */ package pl.cyfronet.s4e.controller.response; import com.fasterxml.jackson.databind.JsonNode; import lombok.Builder; import lombok.Data; import org.locationtech.jts.geom.Geometry; import pl.cyfronet.s4e.bean.Legend; import pl.cyfronet.s4e.data.repository.projection.ProjectionWithId; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Set; @Data @Builder public class SceneResponse { public interface Projection extends ProjectionWithId { ProjectionWithId getProduct(); String getSceneKey(); LocalDateTime getTimestamp(); Geometry getFootprint(); Legend getLegend(); JsonNode getSceneContent(); JsonNode getMetadataContent(); } private Long id; private Long productId; private String sceneKey; private ZonedDateTime timestamp; private String footprint; private Legend legend; private Set<String> artifacts; private JsonNode metadataContent; private boolean hasZipArtifact; }
9239afc9445bdf8c9f0b1fad34b0732ab7ab6e35
289
java
Java
src/test/java/models/NewsTest.java
edwinmuriithi/Organisational-News-Portal
85a2cc7ab228d5cb6fc28aa9b258db753114102e
[ "MIT" ]
null
null
null
src/test/java/models/NewsTest.java
edwinmuriithi/Organisational-News-Portal
85a2cc7ab228d5cb6fc28aa9b258db753114102e
[ "MIT" ]
null
null
null
src/test/java/models/NewsTest.java
edwinmuriithi/Organisational-News-Portal
85a2cc7ab228d5cb6fc28aa9b258db753114102e
[ "MIT" ]
null
null
null
12.041667
49
0.584775
998,910
package models; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class NewsTest { @Test void getId() { } @Test void getUser_id() { } @Test void getNews_type() { } @Test void getDepartment_id() { } }
9239b091d24e5cf61c26455574a5ad657473a143
150
java
Java
intellij-plugin-verifier/verifier-test/before-idea/src/main/java/services/IdeProjectService.java
IvanPashchenko/intellij-plugin-verifier
d18bdd19b894a1c91f9ba7e9ac46473d18c9d444
[ "Apache-2.0" ]
1
2020-06-13T22:41:20.000Z
2020-06-13T22:41:20.000Z
intellij-plugin-verifier/verifier-test/before-idea/src/main/java/services/IdeProjectService.java
IvanPashchenko/intellij-plugin-verifier
d18bdd19b894a1c91f9ba7e9ac46473d18c9d444
[ "Apache-2.0" ]
1
2022-03-18T13:56:38.000Z
2022-03-18T13:56:38.000Z
intellij-plugin-verifier/verifier-test/before-idea/src/main/java/services/IdeProjectService.java
isabella232/intellij-plugin-verifier
d41da914cad04a327298fa467b89c3a688bce261
[ "Apache-2.0" ]
1
2020-06-13T22:41:26.000Z
2020-06-13T22:41:26.000Z
16.666667
45
0.786667
998,911
package services; import com.intellij.openapi.project.Project; public class IdeProjectService { public IdeProjectService(Project project) { } }
9239b0940dafc0d5440bc91fc0ce4ee23874b5c3
9,101
java
Java
src/controladorDB/ManejadorMartilloBD.java
DanielEcheverry96/Proyecto-Almacen
371b73e38d9d5c235d7aa86cc3dddd1f0dab644f
[ "MIT" ]
null
null
null
src/controladorDB/ManejadorMartilloBD.java
DanielEcheverry96/Proyecto-Almacen
371b73e38d9d5c235d7aa86cc3dddd1f0dab644f
[ "MIT" ]
null
null
null
src/controladorDB/ManejadorMartilloBD.java
DanielEcheverry96/Proyecto-Almacen
371b73e38d9d5c235d7aa86cc3dddd1f0dab644f
[ "MIT" ]
null
null
null
43.338095
350
0.5673
998,912
/* * 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 controladorDB; import controlador.ICRUD; import controlador.ICRUDDB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import modelo.CategoriaHerramientas; import modelo.Marca; import modelo.Martillos; /** * * @author danie */ public class ManejadorMartilloBD implements ICRUDDB { Connection conpost; int idcategoria = 5050; CategoriaHerramientas cateh = new CategoriaHerramientas(); @Override public boolean insertar(Object obj) { ConexionDB connDB = new ConexionDB(); conpost = connDB.posgresConn(); boolean insertado = false; Statement stmt; if (obj instanceof Martillos) { Martillos temp = new Martillos(); temp = (Martillos) obj; try { stmt = conpost.createStatement(); String sql = "insert into articulo(idarticulo, nombrearticulo,cantidad,color,precio,imagen,idmarca,idcategoria) values(" + temp.getIdArticulo() + "," + "'" + temp.getNombre() + "'" + "," + temp.getCantidad() + "," + "'" + temp.getColor() + "'" + "," + temp.getPrecio() + "," + "'" + temp.getImagen() + "'" + "," + temp.getMar().getId() + "," + idcategoria + ");"; stmt.executeUpdate(sql); sql = "insert into martillo(idarticulo,tipo_marti,material_mango_marti,material_cabezal_marti,peso_marti,tamaño_marti) values(" + temp.getIdArticulo() + "," + "'" + temp.getTipo() + "'" + "," + "'" + temp.getMatmango() + "'" + "," + "'" + temp.getMatcabezal() + "'" + "," + temp.getPeso() + "," + "'" + temp.getTamaño() + "'" + ");"; stmt.executeUpdate(sql); insertado = true; conpost.close(); stmt.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); return insertado; } } return insertado; } @Override public boolean modificar(int id, Object obj) { ConexionDB connDB = new ConexionDB(); conpost = connDB.posgresConn(); PreparedStatement stmt = null; Martillos temp = (Martillos) obj; try { String sql = "update articulo set nombrearticulo = ?, cantidad = ?, color = ?, " + "precio = ?, imagen = ?, idcategoria = ? where idarticulo = " + id + ""; stmt = conpost.prepareStatement(sql); // stmt.setInt(1, temp.getIdArticulo()); stmt.setString(1, temp.getNombre()); stmt.setInt(2, temp.getCantidad()); stmt.setString(3, temp.getColor()); stmt.setFloat(4, temp.getPrecio()); stmt.setString(5, temp.getImagen()); //stmt.setInt(6, temp.getMar().getId()); stmt.setInt(6, idcategoria); stmt.executeUpdate(); stmt = null; sql = "update martillo set tipo_marti = ?,material_mango_marti = ?,material_cabezal_marti = ?,peso_marti= ?,tamaño_marti= ? where idarticulo = " + id + ""; stmt = conpost.prepareStatement(sql); // stmt.setInt(1, temp.getIdArticulo()); stmt.setString(2, temp.getMatmango()); stmt.setString(3, temp.getMatcabezal()); stmt.setInt(4, temp.getPeso()); stmt.setString(5, temp.getTamaño()); stmt.setString(1, temp.getTipo()); stmt.executeUpdate(); conpost.close(); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage()); return false; } return true; } @Override public int busquedaBinaria(int id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Object consultarId(int id) { Martillos temp = null; Marca mar = null; ConexionDB connDB = new ConexionDB(); conpost = connDB.posgresConn(); Statement stmt; try { //SELECT * //FROM producto INNER JOIN factura_producto ON (producto.referencia_producto = factura_producto.referencia_producto) AND (producto.referencia_producto=1023) INNER JOIN factura ON factura.numero_factura = factura_producto.numero_factura; stmt = conpost.createStatement(); String sql = "select * from articulo inner join martillo on (articulo.idarticulo = martillo.idarticulo) AND (articulo.idarticulo = " + id + ") inner join marca on marca.idmarca = articulo.idmarca;"; ResultSet resultado = stmt.executeQuery(sql); if (resultado.next()) { temp = new Martillos(); mar = new Marca(); temp.setIdArticulo(resultado.getInt("idarticulo")); mar.setId(resultado.getInt("idmarca")); mar.setDescripcion(resultado.getString("descripcion")); temp.setMar(mar); temp.setNombre(resultado.getString("nombrearticulo")); temp.setCantidad(resultado.getInt("cantidad")); temp.setPrecio(resultado.getFloat("precio")); temp.setColor(resultado.getString("color")); temp.setImagen(resultado.getString("imagen")); temp.setMatmango(resultado.getString("material_mango_marti")); temp.setMatcabezal(resultado.getString("material_cabezal_marti")); temp.setPeso(resultado.getInt("peso_marti")); temp.setTamaño(resultado.getString("tamaño_marti")); temp.setTipo(resultado.getString("tipo_marti")); } stmt.close(); conpost.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } return temp; } @Override public boolean borrar(int id) { ConexionDB connDB = new ConexionDB(); conpost = connDB.posgresConn(); PreparedStatement stmt; try { String sql = "delete from articulo where idarticulo = ?"; stmt = conpost.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); stmt.close(); conpost.close(); } catch (SQLException e) { System.out.println(e.getMessage()); return false; } return true; } @Override public boolean borrarTodo() { ConexionDB connDB = new ConexionDB(); conpost = connDB.posgresConn(); PreparedStatement stmt; try { String sql = "truncate table martillo"; stmt = conpost.prepareStatement(sql); stmt.executeUpdate(); stmt.close(); conpost.close(); } catch (SQLException e) { System.out.println(e.getMessage()); return false; } return true; } @Override public void consultarTodos() { ConexionDB connDB = new ConexionDB(); conpost = connDB.posgresConn(); Statement stmt; try { stmt = conpost.createStatement(); ResultSet resultado = stmt.executeQuery("select * from articulo inner join martillo on (articulo.idarticulo = martillo.idarticulo) inner join marca on marca.idmarca = articulo.idmarca"); cateh.arreglomartillos.clear(); while (resultado.next()) { Martillos temp = new Martillos(); Marca mar = new Marca(); temp.setIdArticulo(resultado.getInt("idarticulo")); mar.setId(resultado.getInt("idmarca")); mar.setDescripcion(resultado.getString("descripcion")); temp.setMar(mar); temp.setNombre(resultado.getString("nombrearticulo")); temp.setCantidad(resultado.getInt("cantidad")); temp.setPrecio(resultado.getFloat("precio")); temp.setColor(resultado.getString("color")); temp.setImagen(resultado.getString("imagen")); temp.setMatmango(resultado.getString("material_mango_marti")); temp.setMatcabezal(resultado.getString("material_cabezal_marti")); temp.setPeso(resultado.getInt("peso_marti")); temp.setTamaño(resultado.getString("tamaño_marti")); temp.setTipo(resultado.getString("tipo_marti")); cateh.arreglomartillos.add(temp); } } catch (Exception e) { System.out.println(e.getMessage()); } } }
9239b1cf30ec1be58125b8ebf5b9df7f55b5c733
133
java
Java
Semana15/app/src/main/java/edu/idat/eventosvirtuales/api/DocumentoAlmacenadoApi.java
adiazval20/IDAT-DAM2
225e10759fbcc2a8de8353623f5979153ee21ba4
[ "MIT" ]
null
null
null
Semana15/app/src/main/java/edu/idat/eventosvirtuales/api/DocumentoAlmacenadoApi.java
adiazval20/IDAT-DAM2
225e10759fbcc2a8de8353623f5979153ee21ba4
[ "MIT" ]
null
null
null
Semana15/app/src/main/java/edu/idat/eventosvirtuales/api/DocumentoAlmacenadoApi.java
adiazval20/IDAT-DAM2
225e10759fbcc2a8de8353623f5979153ee21ba4
[ "MIT" ]
null
null
null
22.166667
48
0.781955
998,913
package edu.idat.eventosvirtuales.api; public interface DocumentoAlmacenadoApi { String prefix = "/api/documento-almacenado"; }
9239b20869b0a636914614a9c6f7982c2d1414a9
1,425
java
Java
src/main/com/beetle/framework/persistence/dao/DaoFactory.java
HeYuanFeng/BJAF3.x
c17eaee449dd0af19bf767ad2bc389e9755bec10
[ "Apache-2.0" ]
13
2016-05-06T13:19:43.000Z
2020-01-10T09:07:42.000Z
src/main/com/beetle/framework/persistence/dao/DaoFactory.java
HeYuanFeng/BJAF3.x
c17eaee449dd0af19bf767ad2bc389e9755bec10
[ "Apache-2.0" ]
2
2018-05-11T10:50:03.000Z
2018-06-09T12:47:38.000Z
src/main/com/beetle/framework/persistence/dao/DaoFactory.java
feishaozhang/BJAF3.x
a0e3931ab5c1dfac724f4b80bea003d43780af94
[ "Apache-2.0" ]
6
2017-03-13T09:18:53.000Z
2018-10-15T05:58:32.000Z
19.256757
63
0.632982
998,914
/* * BJAF - Beetle J2EE Application Framework * 甲壳虫J2EE企业应用开发框架 * 版权所有2003-2015 余浩东 (www.beetlesoft.net) * * 这是一个免费开源的软件,您必须在 *<http://www.apache.org/licenses/LICENSE-2.0> *协议下合法使用、修改或重新发布。 * * 感谢您使用、推广本框架,若有建议或问题,欢迎您和我联系。 * 邮件: <yuhaodong@gmail.com/>. */ package com.beetle.framework.persistence.dao; import com.beetle.framework.resource.dic.DIContainer; /** * <p> * Title: 框架设计 * </p> * <p> * Description: DAO对象工厂 * </p> * <p> * Copyright: Copyright (c) 2003 * </p> * <p> * Company: 甲壳虫科技 * </p> * * @author 余浩东 * * @version 1.0 */ public class DaoFactory { private DaoFactory() { } public static void initialize() { // 暂不支持初始化 } /** * 直接通过DAO接口或其实现类来获取一个DAO接口实现对象<br> * * @param daoFaceOrImpClass * Dao接口或其实现类 * * @return Object * @throws DaoFactoryException */ public static <T> T getDaoObject(Class<T> daoFace) throws DaoFactoryException { return DIContainer.getInstance().retrieve(daoFace); } /* * 根据接口名称获取对象,为了兼容保留的方法,不推荐使用,请使用‘<T> T getDaoObject(Class<T> * daofaceClass)’方法代替 */ @Deprecated public static Object getDaoObject(String interFaceName) throws DaoFactoryException { try { return DIContainer.getInstance().retrieve( Class.forName(interFaceName)); } catch (ClassNotFoundException e) { throw new DaoFactoryException(e); } } }
9239b2f5e5282fa691b448def251956acaffd658
1,299
java
Java
servlets/manager/req/GetEmployeeServlet.java
Bob147/Expense-Reimbursement
9ec607f3f8d520e72fef0990966a1f618d0f4bff
[ "Apache-2.0" ]
2
2019-06-25T14:06:07.000Z
2021-05-03T02:02:47.000Z
servlets/manager/req/GetEmployeeServlet.java
Bob147/Expense-Reimbursement
9ec607f3f8d520e72fef0990966a1f618d0f4bff
[ "Apache-2.0" ]
4
2020-04-23T17:54:47.000Z
2021-12-09T21:00:26.000Z
servlets/manager/req/GetEmployeeServlet.java
Bob147/Expense-Reimbursement
9ec607f3f8d520e72fef0990966a1f618d0f4bff
[ "Apache-2.0" ]
null
null
null
30.928571
121
0.756736
998,915
package com.proj.servlets.manager.req; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; import com.proj.dao.EmployeeDao; import com.proj.dao.EmployeeDaoImpl; import com.proj.model.Employee; import com.proj.servlets.utility.User; public class GetEmployeeServlet extends HttpServlet { private static final long serialVersionUID = 1L; public GetEmployeeServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!User.isManagerNull() && !User.isEmployee()) { EmployeeDao ed = new EmployeeDaoImpl(); ObjectMapper om = new ObjectMapper(); PrintWriter pw = response.getWriter(); List<Employee> employees = ed.getEmployees(); String requestString = om.writeValueAsString(employees); requestString = "{\"requests\":"+requestString+"}"; pw.print(requestString); } else { request.getRequestDispatcher("Views/Login.html").forward(request, response); } } }
9239b304977e124b78cc03bde782ec69573584ed
5,646
java
Java
google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/models/RowMutationEntry.java
tc-dc/java-bigtable
aed1d10fe4351ce4f0a3d901bd6bb3602eec0a11
[ "Apache-2.0" ]
40
2019-10-30T18:47:00.000Z
2022-03-06T02:46:03.000Z
google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/models/RowMutationEntry.java
tc-dc/java-bigtable
aed1d10fe4351ce4f0a3d901bd6bb3602eec0a11
[ "Apache-2.0" ]
842
2019-09-30T16:28:01.000Z
2022-03-30T14:10:49.000Z
google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/models/RowMutationEntry.java
tc-dc/java-bigtable
aed1d10fe4351ce4f0a3d901bd6bb3602eec0a11
[ "Apache-2.0" ]
58
2019-09-26T20:46:13.000Z
2022-03-21T17:06:22.000Z
31.19337
99
0.722635
998,916
/* * Copyright 2019 Google LLC * * 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. */ package com.google.cloud.bigtable.data.v2.models; import com.google.api.core.InternalApi; import com.google.bigtable.v2.MutateRowsRequest; import com.google.common.base.Preconditions; import com.google.protobuf.ByteString; import java.io.Serializable; import javax.annotation.Nonnull; /** * Represents a list of mutations targeted at a single row. It is meant to be used as an parameter * for {@link com.google.cloud.bigtable.data.v2.BigtableDataClient#newBulkMutationBatcher(String)}. * * <p>Note: The changes in the mutation will be applied atomically but the ordering between * different RowMutationEntry instances is not guaranteed. */ public class RowMutationEntry implements MutationApi<RowMutationEntry>, Serializable { private static final long serialVersionUID = 1974738836742298192L; private final ByteString key; private final Mutation mutation; private RowMutationEntry(@Nonnull ByteString key, @Nonnull Mutation mutation) { Preconditions.checkNotNull(key, "Row key can't be null"); Preconditions.checkNotNull(mutation, "Row mutation can't be null"); this.key = key; this.mutation = mutation; } /** Creates a new instance of the mutation builder. */ public static RowMutationEntry create(@Nonnull String key) { Preconditions.checkNotNull(key, "Row key can't be null"); return create(ByteString.copyFromUtf8(key)); } /** Creates a new instance of the mutation builder. */ public static RowMutationEntry create(@Nonnull ByteString key) { return new RowMutationEntry(key, Mutation.create()); } /** * Creates new instance of mutation builder which allows server timestamp for setCell operations. * * <p>NOTE: This functionality is intended for advanced usage. * * @see Mutation#createUnsafe() for more explanation. */ @InternalApi("For internal usage only") public static RowMutationEntry createUnsafe(@Nonnull ByteString key) { return new RowMutationEntry(key, Mutation.createUnsafe()); } /** {@inheritDoc} */ @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull String qualifier, @Nonnull String value) { mutation.setCell(familyName, qualifier, value); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull String qualifier, long timestamp, @Nonnull String value) { mutation.setCell(familyName, qualifier, timestamp, value); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull ByteString qualifier, @Nonnull ByteString value) { mutation.setCell(familyName, qualifier, value); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull ByteString qualifier, long timestamp, @Nonnull ByteString value) { mutation.setCell(familyName, qualifier, timestamp, value); return this; } @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull String qualifier, long value) { mutation.setCell(familyName, qualifier, value); return this; } @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull String qualifier, long timestamp, long value) { mutation.setCell(familyName, qualifier, timestamp, value); return this; } @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull ByteString qualifier, long value) { mutation.setCell(familyName, qualifier, value); return this; } @Override public RowMutationEntry setCell( @Nonnull String familyName, @Nonnull ByteString qualifier, long timestamp, long value) { mutation.setCell(familyName, qualifier, timestamp, value); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry deleteCells(@Nonnull String familyName, @Nonnull String qualifier) { mutation.deleteCells(familyName, qualifier); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry deleteCells(@Nonnull String familyName, @Nonnull ByteString qualifier) { mutation.deleteCells(familyName, qualifier); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry deleteCells( @Nonnull String familyName, @Nonnull ByteString qualifier, @Nonnull Range.TimestampRange timestampRange) { mutation.deleteCells(familyName, qualifier, timestampRange); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry deleteFamily(@Nonnull String familyName) { mutation.deleteFamily(familyName); return this; } /** {@inheritDoc} */ @Override public RowMutationEntry deleteRow() { mutation.deleteRow(); return this; } @InternalApi public MutateRowsRequest.Entry toProto() { return MutateRowsRequest.Entry.newBuilder() .setRowKey(key) .addAllMutations(mutation.getMutations()) .build(); } }
9239b36130af65f2e80c62d9878ba9895456cea3
2,094
java
Java
Application/app/src/main/java/de/grocery_scanner/api/EanDatabase.java
martenjostmann/grocery_scanner
e3a5c57325323451ed02ebf2371e938e4fa79a94
[ "MIT" ]
1
2021-04-25T19:07:44.000Z
2021-04-25T19:07:44.000Z
Application/app/src/main/java/de/grocery_scanner/api/EanDatabase.java
martenjostmann/grocery_scanner
e3a5c57325323451ed02ebf2371e938e4fa79a94
[ "MIT" ]
null
null
null
Application/app/src/main/java/de/grocery_scanner/api/EanDatabase.java
martenjostmann/grocery_scanner
e3a5c57325323451ed02ebf2371e938e4fa79a94
[ "MIT" ]
null
null
null
23.795455
169
0.624642
998,917
package de.grocery_scanner.api; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; public class EanDatabase { private String ean; private String queryId = "400000000"; private String URL; private Context context; private String result; public EanDatabase(String ean, String URL, Context context) { this.ean = ean; this.URL = URL; this.context = context; } public String getEan() { return ean; } public String getQueryId() { return queryId; } public void setEan(String barCode) { this.ean = barCode; } public void setQueryId(String queryId) { this.queryId = queryId; } public String getResult() { return result; } public void getProduct(final VolleyCallback callback) { RequestQueue requestQueue = Volley.newRequestQueue(context); StringRequest req = new StringRequest(Request.Method.GET, this.URL + "?ean=" + this.ean + "&cmd=query&queryid=" + this.queryId, new Response.Listener<String>() { @Override public void onResponse(String response) { result = transformText(response); callback.onSuccessResponse(result); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onErrorResponse(error); } }); requestQueue.add(req); } private String transformText(String text){ String[] lines = text.split(System.getProperty("line.separator")); for(String x : lines){ if (x.contains("name=")){ return x.substring(5); } } return null; } }
9239b366f37cfff5982714ca3ffd5f868398e682
1,672
java
Java
grib/src/main/java/ucar/nc2/grib/grib2/Grib2SectionData.java
JMdoubleU/netcdf-java
b2039bd2cd7e5e1b01dff7135834f5706b8eaa1d
[ "BSD-3-Clause" ]
83
2019-07-04T13:40:24.000Z
2022-03-03T02:25:16.000Z
grib/src/main/java/ucar/nc2/grib/grib2/Grib2SectionData.java
JMdoubleU/netcdf-java
b2039bd2cd7e5e1b01dff7135834f5706b8eaa1d
[ "BSD-3-Clause" ]
655
2019-06-28T15:08:16.000Z
2022-03-29T17:12:46.000Z
grib/src/main/java/ucar/nc2/grib/grib2/Grib2SectionData.java
JMdoubleU/netcdf-java
b2039bd2cd7e5e1b01dff7135834f5706b8eaa1d
[ "BSD-3-Clause" ]
87
2019-07-03T18:17:49.000Z
2022-03-30T01:53:16.000Z
24.231884
107
0.708732
998,918
/* * Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.grib.grib2; import ucar.nc2.grib.GribNumbers; import ucar.unidata.io.RandomAccessFile; import javax.annotation.concurrent.Immutable; import java.io.IOException; /** * The Data section 7 for GRIB-2 files * * @author caron * @since 3/29/11 */ @Immutable public class Grib2SectionData { private final long startingPosition; private final int msgLength; public Grib2SectionData(RandomAccessFile raf) throws IOException { startingPosition = raf.getFilePointer(); // octets 1-4 (Length of section) msgLength = GribNumbers.int4(raf); // octet 5 int section = raf.read(); if (section != 7) throw new IllegalStateException("Not a Grib2SectionData (section 7)"); // skip to end of the data section raf.seek(startingPosition + msgLength); } Grib2SectionData(long startingPosition, int msgLength) { this.startingPosition = startingPosition; this.msgLength = msgLength; } public long getStartingPosition() { return startingPosition; } public long getEndingPosition() { return startingPosition + msgLength; } public int getMsgLength() { return msgLength; } public byte[] getBytes(RandomAccessFile raf) throws IOException { raf.seek(startingPosition); // go to the data section byte[] data = new byte[msgLength]; raf.readFully(data); return data; } @Override public String toString() { return "Grib2SectionData{" + "startingPosition=" + startingPosition + ", msgLength=" + msgLength + '}'; } }
9239b4d2b1592f116e4e984c0db6bc7c02176bdd
1,301
java
Java
utility/src/test/java/com/dua3/utility/lang/StopwatchTest.java
xzel23/utility
d9f08c287e8982048a0456f767f93db89b713549
[ "MIT" ]
null
null
null
utility/src/test/java/com/dua3/utility/lang/StopwatchTest.java
xzel23/utility
d9f08c287e8982048a0456f767f93db89b713549
[ "MIT" ]
2
2017-11-22T21:43:51.000Z
2018-01-12T08:26:19.000Z
utility/src/test/java/com/dua3/utility/lang/StopwatchTest.java
xzel23/utility
d9f08c287e8982048a0456f767f93db89b713549
[ "MIT" ]
null
null
null
36.138889
148
0.621061
998,919
package com.dua3.utility.lang; import org.junit.jupiter.api.Test; import java.time.Duration; import static org.junit.jupiter.api.Assertions.*; class StopwatchTest { @Test void testStopwatch() throws InterruptedException { Stopwatch s = new Stopwatch("StopwatchTest"); Thread.sleep(1000); Duration t1 = s.elapsed(); Thread.sleep(1000); Duration t2 = s.elapsedSplit(false); Thread.sleep(1000); Duration t3 = s.elapsedSplit(true); Thread.sleep(1000); Duration t4 = s.elapsed(); Duration t5 = s.elapsedSplit(false); Thread.sleep(1000); Duration t6 = s.elapsed(); Thread.sleep(1000); String st = s.toString(); assertTrue(t1.getSeconds()==1 && t1.getNano()<500_000_000L); assertTrue(t2.getSeconds()==2 && t2.getNano()<500_000_000L); assertTrue(t3.getSeconds()==3 && t3.getNano()<500_000_000L); assertTrue(t4.getSeconds()==4 && t4.getNano()<500_000_000L); assertTrue(t5.getSeconds()==1 && t4.getNano()<500_000_000L); assertTrue(t6.getSeconds()==5 && t5.getNano()<500_000_000L); assertTrue(st.matches("\\[StopwatchTest\\] current split: 0:00:03[.,][01][0-9]{2} total: 0:00:06[.,][01][0-9]{2}"), "format mismatch: "+st); } }
9239b5386b22cb1bc49bdab3f9f71d7230cfbab3
5,428
java
Java
samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java
joaocmendes/openapi-generator
13430247866cdb06ddedfb03ef02eebb1726fe78
[ "Apache-2.0" ]
11,868
2018-05-12T02:58:07.000Z
2022-03-31T21:19:39.000Z
samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java
joaocmendes/openapi-generator
13430247866cdb06ddedfb03ef02eebb1726fe78
[ "Apache-2.0" ]
9,672
2018-05-12T14:25:43.000Z
2022-03-31T23:59:30.000Z
samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java
joaocmendes/openapi-generator
13430247866cdb06ddedfb03ef02eebb1726fe78
[ "Apache-2.0" ]
4,776
2018-05-12T12:06:08.000Z
2022-03-31T19:52:51.000Z
42.740157
249
0.686441
998,920
package org.openapitools.client; import org.openapitools.client.auth.Authentication; import org.openapitools.client.auth.HttpSignatureAuth; import org.openapitools.client.model.*; import org.openapitools.client.ApiClient; import java.lang.Exception; import java.security.spec.AlgorithmParameterSpec; import java.util.*; import java.net.URI; import org.junit.*; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.tomitribe.auth.signatures.Algorithm; import org.tomitribe.auth.signatures.Signer; import org.tomitribe.auth.signatures.SigningAlgorithm; import java.security.spec.PSSParameterSpec; import java.security.spec.MGF1ParameterSpec; import org.tomitribe.auth.signatures.*; import java.io.ByteArrayInputStream; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.PrivateKey; import static org.junit.Assert.*; public class ApiClientTest { ApiClient apiClient = null; Pet pet = null; PrivateKey privateKey = null; PublicKey publicKey = null; @Before public void setup() { apiClient = new ApiClient(); pet = new Pet(); try { KeyPair keypair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); privateKey = keypair.getPrivate(); publicKey = keypair.getPublic(); } catch(NoSuchAlgorithmException e) { fail("No such algorithm: " + e.toString()); } } @Test public void testClientConfig() { ApiClient testClient = new ApiClient(); ClientConfig config = testClient.getDefaultClientConfig(); config.connectorProvider(new ApacheConnectorProvider()); config.property(ClientProperties.PROXY_URI, "http://localhost:8080"); config.property(ClientProperties.PROXY_USERNAME,"proxy_user"); config.property(ClientProperties.PROXY_PASSWORD,"proxy_password"); testClient.setClientConfig(config); } @Test public void testUpdateParamsForAuth() throws Exception { Map<String, String> headerParams = new HashMap<String, String>(); List<Pair> queryParams = new ArrayList<>(); URI uri = new URI("/api/v1/telemetry/TimeSeries"); // auth name String[] authNames = {"http_signature_test"}; HashMap<String, Authentication> authMap = new HashMap<String, Authentication>(); HttpSignatureAuth signatureAuth = new HttpSignatureAuth("some-key-1", SigningAlgorithm.HS2019, Algorithm.RSA_SHA512, null, null, Arrays.asList(new String[] { "(request-target)" }), 128L); signatureAuth.setPrivateKey(privateKey); authMap.put("http_signature_test", signatureAuth); ApiClient client = new ApiClient(authMap); client.updateParamsForAuth(authNames, queryParams, headerParams, null, null, "post", uri); Signature requestSignature = Signature.fromString(headerParams.get("Authorization"), Algorithm.RSA_SHA512); Verifier verify = new Verifier(publicKey, requestSignature); assert verify.verify("post", uri.toString(), headerParams); } @Test public void testSerializeToString() throws Exception { Long petId = 4321L; pet.setId(petId); pet.setName("jersey2 java8 pet"); Category category = new Category(); category.setId(petId); category.setName("jersey2 java8 category"); pet.setCategory(category); pet.setStatus(Pet.StatusEnum.AVAILABLE); pet.setPhotoUrls(Arrays.asList("A", "B", "C")); Tag tag = new Tag(); tag.setId(petId); tag.setName("jersey2 java8 tag"); pet.setTags(Arrays.asList(tag)); String result = "{\"id\":4321,\"category\":{\"id\":4321,\"name\":\"jersey2 java8 category\"},\"name\":\"jersey2 java8 pet\",\"photoUrls\":[\"A\",\"B\",\"C\"],\"tags\":[{\"id\":4321,\"name\":\"jersey2 java8 tag\"}],\"status\":\"available\"}"; assertEquals(result, apiClient.serializeToString(pet, null, "application/json", false)); // nulllable and there should be no diffencne as the payload is not null assertEquals(result, apiClient.serializeToString(pet, null, "application/json", true)); // non-nullable null object should be converted to "" (empty body) assertEquals("", apiClient.serializeToString(null, null, "application/json", false)); // nullable null object should be converted to "null" assertEquals("null", apiClient.serializeToString(null, null, "application/json", true)); // non-nullable empty string should be converted to "\"\"" (empty json string) assertEquals("\"\"", apiClient.serializeToString("", null, "application/json", false)); // nullable empty string should be converted to "\"\"" (empty json string) assertEquals("\"\"", apiClient.serializeToString("", null, "application/json", true)); // non-nullable string "null" should be converted to "\"null\"" assertEquals("\"null\"", apiClient.serializeToString("null", null, "application/json", false)); // nullable string "null" should be converted to "\"null\"" assertEquals("\"null\"", apiClient.serializeToString("null", null, "application/json", true)); } }
9239b80d6a0c65a67c9d8a9f97181304d92ed8bd
9,567
java
Java
src/org/sosy_lab/common/Appenders.java
MartinSpiessl/java-common-lib
ce1bc76b032bd651ea9cf9c130cb089681093446
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/org/sosy_lab/common/Appenders.java
MartinSpiessl/java-common-lib
ce1bc76b032bd651ea9cf9c130cb089681093446
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/org/sosy_lab/common/Appenders.java
MartinSpiessl/java-common-lib
ce1bc76b032bd651ea9cf9c130cb089681093446
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
35.172794
100
0.674506
998,921
/* * SoSy-Lab Common is a library of useful utilities. * This file is part of SoSy-Lab Common. * * Copyright (C) 2007-2015 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sosy_lab.common; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import java.io.IOException; import java.util.Map; import java.util.Objects; import org.checkerframework.checker.nullness.qual.Nullable; /** Utility class providing {@link Appender}s for various cases. */ public class Appenders { private Appenders() {} /** * Return an {@link Appender} for the given object. If the object is an {@link Appender} itself, * it is returned. Otherwise an appender that calls {@link Object#toString()} is returned (c.f. * {@link #fromToStringMethod(Object)}. * * @param o The object which will be dumped, may be null. * @return an {@link Appender} instance */ public static Appender createAppender(@Nullable Object o) { if (o instanceof Appender) { return (Appender) o; } else { return fromToStringMethod(o); } } /** * Write the given object into the given output. If the object is an {@link Appender}, its {@link * Appender#appendTo(Appendable)} method is called, otherwise the {@link Object#toString()} method * is called. The object may be {@code null}, in this case {@code "null"} is written. * * @param output The appendable to write into. * @param o The object which will be dumped, may be null. * @throws IOException If the appendable throws an IOException */ public static void appendTo(Appendable output, @Nullable Object o) throws IOException { if (o instanceof Appender) { ((Appender) o).appendTo(output); } else { output.append(Objects.toString(o)); } } /** * Let an {@link Appender} dump itself into a {@link StringBuilder}. This method is similar to * passing the {@link StringBuilder} to the {@link Appender#appendTo(Appendable)} method, just * without the checked exception. * * @param sb The StringBuilder that will receive the content. * @param a The Appender to dump into the StringBuilder. * @return The passed StringBuilder to allow for method chaining. */ public static StringBuilder appendTo(StringBuilder sb, Appender a) { checkNotNull(sb); try { a.appendTo(sb); } catch (IOException e) { throw new AssertionError("StringBuilder threw IOException", e); } return sb; } /** * Return an {@link Appender} that writes an {@link Iterable} into the output using a given {@link * Joiner}. * * @param joiner The joiner that will be used to create a string representation of the iterable. * @param it The iterable which will be dumped. * @return an {@link Appender} instance */ public static Appender forIterable(Joiner joiner, Iterable<?> it) { checkNotNull(joiner); checkNotNull(it); return new AbstractAppender() { @Override public void appendTo(Appendable appendable) throws IOException { joiner.appendTo(appendable, it); } }; } /** * Return an {@link Appender} that writes a {@link Map} into the output using a given {@link * Joiner}. * * @param joiner The joiner that will be used to create a string representation of the map. * @param map The map which will be dumped. * @return an {@link Appender} instance */ public static Appender forMap(Joiner.MapJoiner joiner, Map<?, ?> map) { checkNotNull(joiner); checkNotNull(map); return new AbstractAppender() { @Override public void appendTo(Appendable appendable) throws IOException { joiner.appendTo(appendable, map); } }; } /** * Return an {@link Appender} that writes the result of the {@link Object#toString()} method of an * object into the output. * * <p>This will not give the performance benefit that is expected from the use of appenders, and * should only be used to adapt classes not implementing this interface themselves. * * <p>If {@code null} is passed, the resulting appender will write {@code "null"}. If an object is * passed, the appender will call the {@link Object#toString()} method once each time it is used * (no caching is done). * * @param o The object which will be dumped, may be null. * @return an {@link Appender} instance */ public static Appender fromToStringMethod(@Nullable Object o) { return new AbstractAppender() { @Override public void appendTo(Appendable appendable) throws IOException { appendable.append(Objects.toString(o)); } }; } /** * Create a new {@link Appender} that consists of the sequential concatenation of multiple * appenders. The given iterable is traversed once each time the resulting appender's {@link * Appender#appendTo(Appendable)} method is called. The iterable may not contain nulls or be null * itself.. */ public static Appender concat(Iterable<Appender> pAppenders) { checkNotNull(pAppenders); return new AbstractAppender() { @Override public void appendTo(Appendable pAppendable) throws IOException { for (Appender appender : pAppenders) { appender.appendTo(pAppendable); } } }; } /** * Create a new {@link Appender} that consists of the sequential concatenation of multiple * appenders. * * @throws NullPointerException if any of the provided appendables is null */ public static Appender concat(Appender... pAppenders) { return concat(ImmutableList.copyOf(pAppenders)); } /** * Convert an {@link Appender} into a string by calling it's {@link Appender#appendTo(Appendable)} * method. * * <p>Note that the contract of {@link Appender} specifies that you should be able to call {@link * Object#toString()} on the object and get the same result, thus it should not be necessary to * call this method from client code. * * <p>However, it may be practical to implement the {@link Object#toString()} method of an {@link * Appender} by delegating to this method. * * @param a The {@link Appender} to convert into a string. * @return a string representation of the passed object. */ public static String toString(Appender a) { return appendTo(new StringBuilder(), a).toString(); } private static class SizeLimitReachedException extends IOException { private static final long serialVersionUID = 1855247676627224183L; } /** * Convert an {@link Appender} into a string by calling it's {@link Appender#appendTo(Appendable)} * method. * * <p>This method truncates the returned string at a given length, and tries to be more efficient * than generating the full string and truncating it at the end (though no guarantees are made). * * @param a The {@link Appender} to convert into a string. * @param truncateAt The maximum size of the returned string {@code (>= 0)} * @return a string representation of the passed object, with a maximum size of <code>truncateAt * </code> */ public static String toStringWithTruncation(Appender a, int truncateAt) { checkArgument(truncateAt >= 0, "Maximum size of String cannot be negative"); StringBuilder sb = new StringBuilder(); Appendable limiter = new Appendable() { private void checkSize() throws SizeLimitReachedException { if (sb.length() >= truncateAt) { throw new SizeLimitReachedException(); } } @Override public Appendable append(CharSequence pCsq, int pStart, int pEnd) throws IOException { sb.append(pCsq, pStart, pEnd); checkSize(); return this; } @Override public Appendable append(char pC) throws IOException { sb.append(pC); checkSize(); return this; } @Override public Appendable append(CharSequence pCsq) throws IOException { sb.append(pCsq); checkSize(); return this; } }; try { a.appendTo(limiter); } catch (SizeLimitReachedException e) { assert sb.length() >= truncateAt; sb.setLength(truncateAt); } catch (IOException e) { throw new AssertionError("StringBuilder threw IOException", e); } return sb.toString(); } /** * Base implementation of {@link Appender} that ensures that the {@link #toString()} method * returns the same result that {@link #appendTo(Appendable)} produces in order to ensure that the * contract of {@link Appender} is fulfilled. */ public abstract static class AbstractAppender implements Appender { @Override public String toString() { return Appenders.toString(this); } } }
9239b84750a6c953d20d1bd25f35d8d9c10ab0f9
1,580
java
Java
src/main/java/top/maplefix/utils/Md5Utils.java
maplefix/maple-blog
b4e06dfb831b2f8527971709003f5d51f8e53722
[ "MIT" ]
2
2019-12-12T01:50:13.000Z
2019-12-21T14:06:49.000Z
src/main/java/top/maplefix/utils/Md5Utils.java
maplefix/MBlog
b4e06dfb831b2f8527971709003f5d51f8e53722
[ "MIT" ]
5
2019-12-11T06:48:58.000Z
2019-12-11T06:48:59.000Z
src/main/java/top/maplefix/utils/Md5Utils.java
maplefix/MBlog
b4e06dfb831b2f8527971709003f5d51f8e53722
[ "MIT" ]
null
null
null
27.719298
84
0.543671
998,922
package top.maplefix.utils; import lombok.extern.slf4j.Slf4j; import java.security.MessageDigest; /** * @author : Maple * @description : MD5加密方法 * @date : 2020/1/18 15:18 */ @Slf4j public class Md5Utils { private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}; private static String byteArrayToHexString(byte b[]) { StringBuffer resultSb = new StringBuffer(); for (byte value : b) { resultSb.append(byteToHexString(value)); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) { n += 256; } int d1 = n / 16; int d2 = n % 16; return HEX_DIGITS[d1] + HEX_DIGITS[d2]; } public static String MD5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)) { resultString = byteArrayToHexString(md.digest(resultString .getBytes())); } else { resultString = byteArrayToHexString(md.digest(resultString .getBytes(charsetname))); } } catch (Exception exception) { log.error("md5加密异常,异常信息为:{},异常堆栈为:{}",exception.getMessage(),exception); } return resultString; } }
9239b84ae80bb1dfaffcdbaf3f65a7848e430523
805
java
Java
Lab6/src/Calculator.java
jakougr/UoS-Programming-I-Labs
e81d4e8cd949b01be69e4388c38025038421dbd9
[ "MIT" ]
null
null
null
Lab6/src/Calculator.java
jakougr/UoS-Programming-I-Labs
e81d4e8cd949b01be69e4388c38025038421dbd9
[ "MIT" ]
null
null
null
Lab6/src/Calculator.java
jakougr/UoS-Programming-I-Labs
e81d4e8cd949b01be69e4388c38025038421dbd9
[ "MIT" ]
1
2018-11-27T22:44:44.000Z
2018-11-27T22:44:44.000Z
27.758621
93
0.515528
998,923
public class Calculator { Double x; /* * Chops up input on ' ' then decides whether to add or multiply. * If the string does not contain a valid format returns null. */ public Double x(String x){ return new Double(0); } /* * Adds the parameter x to the instance variable x and returns the answer as a Double. */ public Double x(Double x){ System.out.println("== Adding =="); return new Double(0); } /* * Multiplies the parameter x by instance variable x and return the value as a Double. */ public Double x(double x){ System.out.println("== Multiplying =="); return new Double(0); } }
9239b8852835e5098415bd1b9887e2b0a3a09b26
1,723
java
Java
Source Files/RemoteBankServer.java
suhaib-saqib/Bank-RMI
95b7a669b9fc0b37c8cc209afd037dd38706cd08
[ "MIT" ]
null
null
null
Source Files/RemoteBankServer.java
suhaib-saqib/Bank-RMI
95b7a669b9fc0b37c8cc209afd037dd38706cd08
[ "MIT" ]
null
null
null
Source Files/RemoteBankServer.java
suhaib-saqib/Bank-RMI
95b7a669b9fc0b37c8cc209afd037dd38706cd08
[ "MIT" ]
2
2018-10-14T22:47:06.000Z
2019-07-22T00:51:36.000Z
33.134615
83
0.602438
998,924
package edu.btp400.w2017.server; import java.rmi.*; import java.rmi.server.*; import com.java.accounts.Chequing; import com.java.accounts.GIC; import com.java.accounts.Savings; public class RemoteBankServer { public static void main(String[] args) { try { System.out.println( "Starting a server..." ); RemoteBankImpl SY = new RemoteBankImpl(); SY.addAccount(new Savings("Ryan, Mary","A123456", 450000.00, 0.15)); SY.addAccount(new Savings("Doe, John","B723416", 250.00, 0.25)); SY.addAccount(new Chequing("Ryan, Mary","C127652", 74000.00, 1.50, 500)); SY.addAccount(new Chequing("Doe, John","D726354", 9400.00, 2.50, 10)); SY.addAccount(new GIC("Ryan, Mary","E653251", 6000.00, 2, 1.50)); SY.addAccount(new GIC("Doe, John","F433251", 15000.00, 4, 2.50)); System.out.println( "Binding remote objects to rmi registry" ); /* // use of rmi URL Naming.rebind( "rmi://localhost:6666/toaster", p1 ); // <name, reference> // e.g.("toaster",p1) Naming.rebind( "rmi://localhost:6666/microwave", p2 ); */ // for localhost only java.rmi.registry.Registry registry = java.rmi.registry.LocateRegistry.createRegistry(5678); registry.rebind( "SenecaYork", SY ); System.out.println( "These remote objects are waiting for clients..." ); } catch( Exception e ) { System.out.println( "Error: " + e ); } System.out.println( "... bye bye" ); System.out.println( "... the main thread is put into a wait state!!!" ); /* a separate thread is started after a remote object has been created */ } }
9239b93aa534683bd2a97d7cf0cce43db9794d51
571
java
Java
mdw-common/src/com/centurylink/mdw/auth/Authenticator.java
oakesville/mdw
f0e453ddc40a72b04de25d3df99e8d919dca4ad5
[ "MIT" ]
49
2017-04-08T22:41:22.000Z
2021-11-13T10:42:04.000Z
mdw-common/src/com/centurylink/mdw/auth/Authenticator.java
oakesville/mdw
f0e453ddc40a72b04de25d3df99e8d919dca4ad5
[ "MIT" ]
727
2017-04-05T21:13:36.000Z
2020-11-03T07:23:14.000Z
mdw-common/src/com/centurylink/mdw/auth/Authenticator.java
oakesville/mdw
f0e453ddc40a72b04de25d3df99e8d919dca4ad5
[ "MIT" ]
9
2017-05-02T09:35:53.000Z
2020-10-20T21:41:30.000Z
28.55
102
0.718039
998,925
package com.centurylink.mdw.auth; /** * Authentication API. */ public interface Authenticator { /** * AuthenticationException indicates bad credentials, whereas general MdwSecurityException * indicates some other type of error. */ void authenticate(String user, String password) throws MdwSecurityException; /** * @return Identifies this authenticator versus others of the same type to allow clients * to avoid re-prompting for credentials when the user has already logged in to the same location. */ String getKey(); }
9239b94368d8af15eef04647a4308afe45936cdb
4,173
java
Java
src/com/mrh0/arclang/type/var/Var.java
mrh0/arclang
d439191c6a70701c3e77c39b4a4ef938c39f7351
[ "MIT" ]
null
null
null
src/com/mrh0/arclang/type/var/Var.java
mrh0/arclang
d439191c6a70701c3e77c39b4a4ef938c39f7351
[ "MIT" ]
null
null
null
src/com/mrh0/arclang/type/var/Var.java
mrh0/arclang
d439191c6a70701c3e77c39b4a4ef938c39f7351
[ "MIT" ]
null
null
null
20.356098
78
0.67793
998,926
package com.mrh0.arclang.type.var; import com.mrh0.arclang.exception.ArcException; import com.mrh0.arclang.exception.ExpectationException; import com.mrh0.arclang.exception.UnexpectedSymbolException; import com.mrh0.arclang.type.IVal; import com.mrh0.arclang.type.TUndefined; import com.mrh0.arclang.vm.Context; import com.mrh0.arclang.vm.VM; import com.mrh0.arclang.vm.Variables; public class Var implements IVal { private IVal value; private final String name; public Var(String name) { this.name = name; value = TUndefined.getInstance(); } public Var(String name, IVal value) { this.name = name; this.value = IVal.get(value); } public String getName() { return name; } public IVal getValue() { return value; } @Override public String getTypeName() { return value.getTypeName(); } public boolean isUndefined() { return value.isUndefined(); } public boolean isNumber() { return value.isNumber(); } public boolean isString() { return value.isString(); } public boolean isObject() { return value.isObject(); } public boolean isList() { return value.isList(); } public boolean isFunction() { return value.isFunction(); } @Override public IVal add(IVal v) throws ArcException { return value.add(v); } @Override public IVal sub(IVal v) throws ArcException { return value.sub(v); } @Override public IVal mul(IVal v) throws ArcException { return value.mul(v); } @Override public IVal div(IVal v) throws ArcException { return value.div(v); } @Override public IVal mod(IVal v) throws ArcException { return value.mod(v); } @Override public IVal pow(IVal v) throws ArcException { return value.pow(v); } @Override public IVal as(IVal v) throws ArcException { return value.as(v); } @Override public IVal is(IVal v) throws ArcException { return value.is(v); } @Override public IVal equals(IVal v) throws ArcException { return value.equals(v); } @Override public IVal notEquals(IVal v) throws ArcException { return value.notEquals(v); } @Override public IVal greaterThan(IVal v) throws ArcException { return value.greaterThan(v); } @Override public IVal lessThan(IVal v) throws ArcException { return value.lessThan(v); } @Override public IVal greaterThanOrEquals(IVal v) throws ArcException { return value.greaterThanOrEquals(v); } @Override public IVal lessThanOrEquals(IVal v) throws ArcException { return value.lessThanOrEquals(v); } @Override public double getComparableValue() { return value.getComparableValue(); } @Override public IVal logicalAnd(IVal v) throws ArcException { return value.logicalAnd(v); } @Override public IVal logicalOr(IVal v) throws ArcException { return value.logicalOr(v); } @Override public IVal logicalXor(IVal v) throws ArcException { return value.logicalXor(v); } @Override public IVal logicalNot() throws ArcException { return value.logicalNot(); } @Override public IVal accessor(IVal key, VM vm, Context context) throws ArcException { return value.accessor(key, vm, context); } @Override public IVal assign(IVal v, Variables vars) throws ArcException { set(v); //vars.set(this); return this; } @Override public IVal walrusAssign(IVal v, Variables vars) throws ArcException { vars.set(set(v)); return this; } public Var set(IVal value) { this.value = IVal.get(value); return this; } @Override public String toString() { return value.toString(); } @Override public boolean booleanValue() { return value.booleanValue(); } public static Var from(IVal val) throws ExpectationException { if(val instanceof Var) return (Var)val; throw new ExpectationException("variable"); } public static Var nonConstantFrom(IVal val) throws ExpectationException { if((val instanceof Var) && !(val instanceof Constant)) { return (Var)val; } throw new ExpectationException("variable"); } }
9239b9c74984d52267db3f4da16cc31051e7dfe6
15,174
java
Java
mobi.chouette.exchange.neptune/src/test/java/mobi/chouette/exchange/neptune/importer/NeptuneImportTests.java
AF83/chouette-iev
151e95b8b48043018f6c7facc528df700d093804
[ "CECILL-B" ]
null
null
null
mobi.chouette.exchange.neptune/src/test/java/mobi/chouette/exchange/neptune/importer/NeptuneImportTests.java
AF83/chouette-iev
151e95b8b48043018f6c7facc528df700d093804
[ "CECILL-B" ]
null
null
null
mobi.chouette.exchange.neptune/src/test/java/mobi/chouette/exchange/neptune/importer/NeptuneImportTests.java
AF83/chouette-iev
151e95b8b48043018f6c7facc528df700d093804
[ "CECILL-B" ]
null
null
null
40.90027
120
0.755964
998,927
package mobi.chouette.exchange.neptune.importer; import java.io.File; import java.io.IOException; import java.util.Locale; import javax.ejb.EJB; import javax.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.UserTransaction; import lombok.extern.log4j.Log4j; import mobi.chouette.common.Context; import mobi.chouette.common.chain.CommandFactory; import mobi.chouette.dao.LineDAO; import mobi.chouette.dao.VehicleJourneyDAO; import mobi.chouette.exchange.neptune.Constant; import mobi.chouette.exchange.neptune.JobDataTest; import mobi.chouette.exchange.neptune.NeptuneTestsUtils; import mobi.chouette.exchange.report.ActionReport; import mobi.chouette.exchange.report.FileInfo.FILE_STATE; import mobi.chouette.exchange.report.LineInfo; import mobi.chouette.exchange.report.LineInfo.LINE_STATE; import mobi.chouette.exchange.report.ReportConstant; import mobi.chouette.exchange.validation.report.ValidationReport; import mobi.chouette.model.Line; import mobi.chouette.model.StopArea; import mobi.chouette.model.type.ChouetteAreaEnum; import mobi.chouette.model.util.Referential; import mobi.chouette.persistence.hibernate.ContextHolder; import org.apache.commons.io.FileUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.Test; @Log4j public class NeptuneImportTests extends Arquillian implements Constant, ReportConstant { @EJB LineDAO lineDao; @EJB VehicleJourneyDAO vjDao; @PersistenceContext(unitName = "referential") EntityManager em; @Inject UserTransaction utx; @Deployment public static WebArchive createDeployment() { WebArchive result; File[] files = Maven.resolver().loadPomFromFile("pom.xml") .resolve("mobi.chouette:mobi.chouette.exchange.neptune").withTransitivity().asFile(); result = ShrinkWrap.create(WebArchive.class, "test.war") .addAsWebInfResource("postgres-ds.xml") .addAsLibraries(files) .addClass(NeptuneTestsUtils.class) .addClass(JobDataTest.class) .addAsResource(EmptyAsset.INSTANCE, "beans.xml"); return result; } protected static InitialContext initialContext; protected void init() { Locale.setDefault(Locale.ENGLISH); if (initialContext == null) { try { initialContext = new InitialContext(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected Context initImportContext() { init(); ContextHolder.setContext("chouette_gui"); // set tenant schema Context context = new Context(); context.put(INITIAL_CONTEXT, initialContext); context.put(REPORT, new ActionReport()); context.put(MAIN_VALIDATION_REPORT, new ValidationReport()); NeptuneImportParameters configuration = new NeptuneImportParameters(); context.put(CONFIGURATION, configuration); configuration.setName("name"); configuration.setUserName("userName"); configuration.setNoSave(true); configuration.setCleanRepository(true); configuration.setOrganisationName("organisation"); configuration.setReferentialName("test"); JobDataTest jobData = new JobDataTest(); context.put(JOB_DATA,jobData); jobData.setPathName("target/referential/test"); File f = new File("target/referential/test"); if (f.exists()) try { FileUtils.deleteDirectory(f); } catch (IOException e) { e.printStackTrace(); } f.mkdirs(); jobData.setReferential("chouette_gui"); jobData.setAction(IMPORTER); jobData.setType( "neptune"); context.put("testng", "true"); context.put(OPTIMIZED, Boolean.FALSE); return context; } // @Test(groups = { "CheckParameters" }, description = "Import Plugin should reject file not found") public void verifyCheckInputFileExists() throws Exception { // TODO test à passer aussi sur la commande uncompress du module // mobi.chouette.exchange Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_ERROR, "result"); Assert.assertTrue(report.getFailure().getDescription().startsWith("Missing"), "error message " + report.getFailure()); System.out.println("error message = " + report.getFailure()); } // @Test(groups = { "ImportLineUtf8" }, description = "Import Plugin should detect file encoding") public void verifyCheckGoodEncoding() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("C_NEPTUNE_1_utf8.xml"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("C_NEPTUNE_1_utf8.xml"); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_OK, "result"); Assert.assertEquals(report.getFiles().size(), 1, "file reported"); Assert.assertEquals(report.getLines().size(), 1, "line reported"); Assert.assertTrue(report.getLines().get(0).getName().contains("é"), "character conversion"); } // @Test(groups = { "ImportLineUtf8Bom" }, description = "Import Plugin should detect bom in file encoding") public void verifyCheckGoodEncodingWithBom() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("C_NEPTUNE_1_utf8_bom.xml"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("C_NEPTUNE_1_utf8_bom.xml"); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_OK, "result"); Assert.assertEquals(report.getFiles().size(), 1, "file reported"); Assert.assertEquals(report.getLines().size(), 1, "line reported"); Assert.assertTrue(report.getLines().get(0).getName().contains("é"), "character conversion"); } // @Test(groups = { "ImportLineBadEnc" }, description = "Import Plugin should detect file encoding") public void verifyCheckBadEncoding() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("C_NEPTUNE_1_bad_enc.xml"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("C_NEPTUNE_1_bad_enc.xml"); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_ERROR, "result"); Assert.assertEquals(report.getFiles().size(), 1, "file reported"); Assert.assertEquals(report.getFiles().get(0).getStatus(), FILE_STATE.ERROR, "file status"); Assert.assertEquals(report.getFiles().get(0).getErrors().size(), 1, "file errors"); Assert.assertTrue(report.getFiles().get(0).getErrors().get(0).getDescription().startsWith("invalid encoding"), "file error message " + report.getFiles().get(0).getErrors().get(0)); System.out.println("file error message = " + report.getFiles().get(0).getErrors().get(0)); } @Test(groups = { "ImportLine" }, description = "Import Plugin should import file") public void verifyImportLine() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("C_NEPTUNE_1.xml"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("C_NEPTUNE_1.xml"); NeptuneImportParameters configuration = (NeptuneImportParameters) context.get(CONFIGURATION); configuration.setNoSave(false); configuration.setCleanRepository(true); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_OK, "result"); Assert.assertEquals(report.getFiles().size(), 1, "file reported"); Assert.assertEquals(report.getLines().size(), 1, "line reported"); Reporter.log("report line :" + report.getLines().get(0).toString(), true); Assert.assertEquals(report.getLines().get(0).getStatus(), LINE_STATE.OK, "line status"); NeptuneTestsUtils.checkLine(context); Referential referential = (Referential) context.get(REFERENTIAL); Assert.assertNotEquals(referential.getTimetables(),0, "timetables" ); Assert.assertNotEquals(referential.getSharedTimetables(),0, "shared timetables" ); // line should be saved utx.begin(); em.joinTransaction(); Line line = lineDao.findByObjectId("NINOXE:Line:15574334"); NeptuneTestsUtils.checkMinimalLine(line); utx.rollback(); } @Test(groups = { "ImportLine" }, description = "Import Plugin should import file with frequencies") public void verifyImportLineWithFrequency() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("Neptune_With_Frequencies.xml"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("Neptune_With_Frequencies.xml"); NeptuneImportParameters configuration = (NeptuneImportParameters) context.get(CONFIGURATION); configuration.setNoSave(false); configuration.setCleanRepository(true); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_OK, "result"); Assert.assertEquals(report.getFiles().size(), 1, "file reported"); Assert.assertEquals(report.getLines().size(), 1, "line reported"); Reporter.log("report line :" + report.getLines().get(0).toString(), true); Assert.assertEquals(report.getLines().get(0).getStatus(), LINE_STATE.OK, "line status"); NeptuneTestsUtils.checkLineWithFrequencies(context); Referential referential = (Referential) context.get(REFERENTIAL); Assert.assertNotEquals(referential.getTimetables(),0, "timetables" ); Assert.assertNotEquals(referential.getSharedTimetables(),0, "shared timetables" ); // line should be saved utx.begin(); em.joinTransaction(); Line line = lineDao.findByObjectId("NINOXE:Line:15574334"); NeptuneTestsUtils.checkMinimalLine(line); utx.rollback(); } // @Test(groups = { "ImportRCLine" }, description = "Import Plugin should import file with ITL") public void verifyImportRCLine() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("C_CHOUETTE_52.xml"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("C_CHOUETTE_52.xml"); NeptuneImportParameters configuration = (NeptuneImportParameters) context.get(CONFIGURATION); configuration.setNoSave(true); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Reporter.log("report :" + report.toString(), true); ValidationReport valreport = (ValidationReport) context.get(MAIN_VALIDATION_REPORT); Reporter.log("valreport :" + valreport.toString(), true); Assert.assertEquals(report.getResult(), STATUS_OK, "result"); Assert.assertEquals(report.getFiles().size(), 1, "file reported"); Assert.assertEquals(report.getLines().size(), 1, "line reported"); Assert.assertEquals(report.getLines().get(0).getStatus(), LINE_STATE.OK, "line status"); Referential referential = (Referential) context.get(REFERENTIAL); Assert.assertNotNull(referential, "referential"); Assert.assertEquals(referential.getLines().size(), 1, "lines size"); Line line = referential.getLines().get("Hastustoto:Line:52"); Assert.assertNotNull(line, "line"); Assert.assertNotNull(line.getRoutingConstraints(), "line must have routing constraints"); Assert.assertEquals(line.getRoutingConstraints().size(), 1, "line must have 1 routing constraint"); StopArea area = line.getRoutingConstraints().get(0); Assert.assertEquals(area.getAreaType(), ChouetteAreaEnum.ITL, "routing constraint area must be of " + ChouetteAreaEnum.ITL + " type"); Assert.assertNotNull(area.getRoutingConstraintAreas(), "routing constraint area must have stopArea children as routing constraints"); Assert.assertEquals(area.getContainedStopAreas().size(),0, "routing constraint area must not have stopArea children"); Assert.assertNull(area.getParent(), "routing constraint area must not have stopArea parent"); Assert.assertTrue(area.getRoutingConstraintAreas().size() > 0, "routing constraint area must have stopArea children as routing constraints"); } // @Test(groups = { "ImportZipLines" }, description = "Import Plugin should import zip file") public void verifyImportZipLines() throws Exception { Context context = initImportContext(); NeptuneImporterCommand command = (NeptuneImporterCommand) CommandFactory.create(initialContext, NeptuneImporterCommand.class.getName()); NeptuneTestsUtils.copyFile("lignes_neptune.zip"); JobDataTest jobData = (JobDataTest) context.get(JOB_DATA); jobData.setFilename("lignes_neptune.zip"); NeptuneImportParameters configuration = (NeptuneImportParameters) context.get(CONFIGURATION); configuration.setNoSave(false); try { command.execute(context); } catch (Exception ex) { log.error("test failed", ex); throw ex; } ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), STATUS_OK, "result"); Assert.assertEquals(report.getFiles().size(), 7, "file reported"); Assert.assertEquals(report.getLines().size(), 6, "line reported"); for (LineInfo line : report.getLines()) { Reporter.log("report line :" + line.toString(), true); Assert.assertEquals(line.getStatus(), LINE_STATE.OK, "line status"); } } }
9239b9e58127519369cc49a42ca93eee8b81ae24
12,960
java
Java
library/src/main/java/com/leonxtp/library/YModem.java
LeonXtp/YModemForAndroid
7b57a46e8825230ab158bd2bb977aaea0fce1ca2
[ "MIT" ]
44
2017-09-19T01:04:10.000Z
2022-03-29T22:33:36.000Z
library/src/main/java/com/leonxtp/library/YModem.java
DIT4FUN/YModemForAndroid
7b57a46e8825230ab158bd2bb977aaea0fce1ca2
[ "MIT" ]
2
2017-09-19T09:08:57.000Z
2020-12-17T05:47:00.000Z
library/src/main/java/com/leonxtp/library/YModem.java
DIT4FUN/YModemForAndroid
7b57a46e8825230ab158bd2bb977aaea0fce1ca2
[ "MIT" ]
25
2017-09-19T01:20:05.000Z
2021-12-23T01:50:37.000Z
34.376658
132
0.515278
998,928
package com.leonxtp.library; import android.content.Context; import java.io.IOException; /** * THE YMODEM: * *SENDER: ANDROID APP *------------------------------------------* RECEIVER: BLE DEVICE* * HELLO BOOTLOADER ---------------------------------------------->* * <---------------------------------------------------------------* C * SOH 00 FF filename0fileSizeInByte0MD5[90] ZERO[38] CRC CRC----->* * <---------------------------------------------------------------* ACK C * STX 01 FE data[1024] CRC CRC ---------------------------------->* * <---------------------------------------------------------------* ACK * STX 02 FF data[1024] CRC CRC ---------------------------------->* * <---------------------------------------------------------------* ACK * ... * ... * <p> * STX 08 F7 data[1000] CPMEOF[24] CRC CRC ----------------------->* * <---------------------------------------------------------------* ACK * EOT ----------------------------------------------------------->* * <---------------------------------------------------------------* ACK * SOH 00 FF ZERO[128] ------------------------------------------->* * <---------------------------------------------------------------* ACK * <---------------------------------------------------------------* MD5_OK * <p> * Created by leonxtp on 2017/9/16. * Modified by leonxtp on 2017/9/16 */ public class YModem implements FileStreamThread.DataRaderListener { private static final int STEP_HELLO = 0x00; private static final int STEP_FILE_NAME = 0x01; private static final int STEP_FILE_BODY = 0x02; private static final int STEP_EOT = 0x03; private static final int STEP_END = 0x04; private static int CURR_STEP = STEP_HELLO; private static final byte ACK = 0x06; /* ACKnowlege */ private static final byte NAK = 0x15; /* Negative AcKnowlege */ private static final byte CAN = 0x18; /* CANcel character */ private static final byte ST_C = 'C'; private static final String MD5_OK = "MD5_OK"; private static final String MD5_ERR = "MD5_ERR"; private Context mContext; private String filePath; private String fileNameString = "LPK001_Android"; private String fileMd5String = "63e7bb6eed1de3cece411a7e3e8e763b"; private YModemListener listener; private TimeOutHelper timerHelper = new TimeOutHelper(); private FileStreamThread streamThread; //bytes has been sent of this transmission private int bytesSent = 0; //package data of current sending, used for int case of fail private byte[] currSending = null; private int packageErrorTimes = 0; private static final int MAX_PACKAGE_SEND_ERROR_TIMES = 6; //the timeout interval for a single package private static final int PACKAGE_TIME_OUT = 6000; /** * Construct of the YModemBLE,you may don't need the fileMD5 checking,remove it * * @param filePath absolute path of the file * @param fileNameString file name for sending to the terminal * @param fileMd5String md5 for terminal checking after transmission finished * @param listener */ public YModem(Context context, String filePath, String fileNameString, String fileMd5String, YModemListener listener) { this.filePath = filePath; this.fileNameString = fileNameString; this.fileMd5String = fileMd5String; this.mContext = context; this.listener = listener; } /** * Start the transmission */ public void start() { sayHello(); } /** * Stop the transmission when you don't need it or shut it down in accident */ public void stop() { bytesSent = 0; currSending = null; packageErrorTimes = 0; if (streamThread != null) { streamThread.release(); } timerHelper.stopTimer(); timerHelper.unRegisterListener(); } /** * Method for the outer caller when received data from the terminal */ public void onReceiveData(byte[] respData) { //Stop the package timer timerHelper.stopTimer(); if (respData != null && respData.length > 0) { L.f("YModem received " + respData.length + " bytes."); switch (CURR_STEP) { case STEP_HELLO: handleHello(respData); break; case STEP_FILE_NAME: handleFileName(respData); break; case STEP_FILE_BODY: handleFileBody(respData); break; case STEP_EOT: handleEOT(respData); break; case STEP_END: handleEnd(respData); break; default: break; } } else { L.f("The terminal do responsed something, but received nothing??"); } } /** * ============================================================================== * Methods for sending data begin * ============================================================================== */ private void sayHello() { streamThread = new FileStreamThread(mContext, filePath, this); CURR_STEP = STEP_HELLO; L.f("sayHello!!!"); byte[] hello = YModemUtil.getYModelHello(); sendPackageData(hello); } private void sendFileName() { CURR_STEP = STEP_FILE_NAME; L.f("sendFileName"); try { int fileByteSize = streamThread.getFileByteSize(); byte[] fileNamePackage = YModemUtil.getFileNamePackage(fileNameString, fileByteSize , fileMd5String); sendPackageData(fileNamePackage); } catch (IOException e) { e.printStackTrace(); } } private void startSendFileData() { CURR_STEP = STEP_FILE_BODY; L.f("startSendFileData"); streamThread.start(); } //Callback from the data reading thread when a data package is ready @Override public void onDataReady(byte[] data) { sendPackageData(data); } private void sendEOT() { CURR_STEP = STEP_EOT; L.f("sendEOT"); if (listener != null) { listener.onDataReady(YModemUtil.getEOT()); } } private void sendEND() { CURR_STEP = STEP_END; L.f("sendEND"); if (listener != null) { try { listener.onDataReady(YModemUtil.getEnd()); } catch (IOException e) { e.printStackTrace(); } } } private void sendPackageData(byte[] packageData) { if (listener != null && packageData != null) { currSending = packageData; //Start the timer, it will be cancelled when reponse received, // or trigger the timeout and resend the current package data timerHelper.startTimer(timeoutListener, PACKAGE_TIME_OUT); listener.onDataReady(packageData); } } /** * ============================================================================== * Method for handling the response of a package * ============================================================================== */ private void handleHello(byte[] value) { int character = value[0]; if (character == ST_C) {//Receive "C" for "HELLO" L.f("Received 'C'"); packageErrorTimes = 0; sendFileName(); } else { handleOthers(character); } } //The file name package was responsed private void handleFileName(byte[] value) { if (value.length == 2 && value[0] == ACK && value[1] == ST_C) {//Receive 'ACK C' for file name L.f("Received 'ACK C'"); packageErrorTimes = 0; startSendFileData(); } else if (value[0] == ST_C) {//Receive 'C' for file name, this package should be resent L.f("Received 'C'"); handlePackageFail("Received 'C' without 'ACK' after sent file name"); } else { handleOthers(value[0]); } } private void handleFileBody(byte[] value) { if (value.length == 1 && value[0] == ACK) {//Receive ACK for file data L.f("Received 'ACK'"); packageErrorTimes = 0; bytesSent += currSending.length; try { if (listener != null) { listener.onProgress(bytesSent, streamThread.getFileByteSize()); } } catch (IOException e) { e.printStackTrace(); } streamThread.keepReading(); } else if (value.length == 1 && value[0] == ST_C) { L.f("Received 'C'"); //Receive C for file data, the ymodem cannot handle this circumstance, transmission failed... handlePackageFail("Received 'C' after sent file data"); } else { handleOthers(value[0]); } } private void handleEOT(byte[] value) { if (value[0] == ACK) { L.f("Received 'ACK'"); packageErrorTimes = 0; sendEND(); } else if (value[0] == ST_C) {//As we haven't received ACK, we should resend EOT handlePackageFail("Received 'C' after sent EOT"); } else { handleOthers(value[0]); } } private void handleEnd(byte[] character) { if (character[0] == ACK) {//The last ACK represents that the transmission has been finished, but we should validate the file L.f("Received 'ACK'"); packageErrorTimes = 0; } else if ((new String(character)).equals(MD5_OK)) {//The file data has been checked,Well Done! L.f("Received 'MD5_OK'"); stop(); if (listener != null) { listener.onSuccess(); } } else if ((new String(character)).equals(MD5_ERR)) {//Oops...Transmission Failed... L.f("Received 'MD5_ERR'"); stop(); if (listener != null) { listener.onFailed("MD5 check failed!!!"); } } else { handleOthers(character[0]); } } private void handleOthers(int character) { if (character == NAK) {//We need to resend this package as the terminal failed when checking the crc L.f("Received 'NAK'"); handlePackageFail("Received NAK"); } else if (character == CAN) {//Some big problem occurred, transmission failed... L.f("Received 'CAN'"); if (listener != null) { listener.onFailed("Received CAN"); } stop(); } } //Handle a failed package data ,resend it up to MAX_PACKAGE_SEND_ERROR_TIMES times. //If still failed, then the transmission failed. private void handlePackageFail(String reason) { packageErrorTimes++; L.f("Fail:" + reason + " for " + packageErrorTimes + " times"); if (packageErrorTimes < MAX_PACKAGE_SEND_ERROR_TIMES) { sendPackageData(currSending); } else { //Still, we stop the transmission, release the resources stop(); if (listener != null) { listener.onFailed(reason); } } } /* The InputStream data reading thread was done */ @Override public void onFinish() { sendEOT(); } //The timeout listener private TimeOutHelper.ITimeOut timeoutListener = new TimeOutHelper.ITimeOut() { @Override public void onTimeOut() { L.f("------ time out ------"); if (currSending != null) { handlePackageFail("package timeout..."); } } }; public static class Builder { private Context context; private String filePath; private String fileNameString; private String fileMd5String; private YModemListener listener; public Builder with(Context context) { this.context = context; return this; } public Builder filePath(String filePath) { this.filePath = filePath; return this; } public Builder fileName(String fileName) { this.fileNameString = fileName; return this; } public Builder checkMd5(String fileMd5String) { this.fileMd5String = fileMd5String; return this; } public Builder callback(YModemListener listener) { this.listener = listener; return this; } public YModem build() { return new YModem(context, filePath, fileNameString, fileMd5String, listener); } } }
9239bb373c16984538fac7aeb9692a4123e53e77
3,508
java
Java
A2/app/src/main/java/mobandsoccomp/a2/vib_service.java
kushal90/Metal_Detector_demo
c3cb008685cd06f43db0942552a58888931d46ea
[ "MIT" ]
1
2019-06-02T07:29:19.000Z
2019-06-02T07:29:19.000Z
A2/app/src/main/java/mobandsoccomp/a2/vib_service.java
kevinmel2000/Android_Metal_Detector
c3cb008685cd06f43db0942552a58888931d46ea
[ "MIT" ]
null
null
null
A2/app/src/main/java/mobandsoccomp/a2/vib_service.java
kevinmel2000/Android_Metal_Detector
c3cb008685cd06f43db0942552a58888931d46ea
[ "MIT" ]
1
2019-06-02T07:29:06.000Z
2019-06-02T07:29:06.000Z
32.785047
100
0.657925
998,929
package mobandsoccomp.a2; import android.app.IntentService; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.HandlerThread; import android.os.IBinder; import android.os.Vibrator; import android.support.annotation.Nullable; import android.text.format.DateFormat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; /** * Created by Kushal on 25/01/2016. */ public class vib_service extends Service implements SensorEventListener{ /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ public static final String PARAM_IN_MSG = "Metalpower: "; public static final String PARAM_OUT_MSG = "omsg"; private SensorManager mSensorManager; private Sensor mMagnetometer; private Vibrator vibrator; @Override public void onSensorChanged(SensorEvent event) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; double metalpower = Math.round(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))); String text = "Metalpower (in microTesla): " + Double.toString(metalpower); Log.d("TAG", text); if (metalpower > 70) { Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(100);} Intent broadcastIntent = new Intent(); // broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.setAction("mobandsoccomp.a2.ACTION_Magnetometer"); broadcastIntent.putExtra("abcdef",text); sendBroadcast(broadcastIntent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service starting", Toast.LENGTH_SHORT).show(); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_FASTEST); return START_STICKY; } /* final static String MY_ACTION = "MY_ACTION"; public class MyThread extends Thread{ @Override public void run() { // TODO Auto-generated method stub for(int i=0; i<10; i++){ try { Thread.sleep(5000); Intent intent = new Intent(); intent.setAction(MY_ACTION); sendBroadcast(intent); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } stopSelf(); } } */ @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onDestroy() { // TODO Auto-generated method stub mSensorManager.unregisterListener(this); Toast.makeText(this, "Destroy", Toast.LENGTH_SHORT).show(); super.onDestroy(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
9239bbd070372397da6f41681abf2f9ddee6fbfb
4,080
java
Java
app/src/main/java/dev/mstiehr/de/fieldserviceapplication/json/Job.java
mstiehr-dev/FieldServiceApplication
f10f5942ff841630f42f58c74d75a9e89e0224a5
[ "Apache-2.0" ]
null
null
null
app/src/main/java/dev/mstiehr/de/fieldserviceapplication/json/Job.java
mstiehr-dev/FieldServiceApplication
f10f5942ff841630f42f58c74d75a9e89e0224a5
[ "Apache-2.0" ]
null
null
null
app/src/main/java/dev/mstiehr/de/fieldserviceapplication/json/Job.java
mstiehr-dev/FieldServiceApplication
f10f5942ff841630f42f58c74d75a9e89e0224a5
[ "Apache-2.0" ]
null
null
null
21.25
113
0.587255
998,930
package dev.mstiehr.de.fieldserviceapplication.json; import android.os.Bundle; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import dev.mstiehr.de.fieldserviceapplication.misc.Constants; /** * Created by Martin on 03.03.2016. */ @Table(name = Constants.TABLE_JOBS) public class Job extends Model { @Column(name = "_id", index=true) private String id; @Column(name = "_status") private String status; @Column(name = "_customer") private String customer; @Column(name = "_address") private String address; @Column(name = "_city") private String city; @Column(name = "_state") private String state; @Column(name = "_zip") private String zip; @Column(name = "_product") private String product; @Column(name = "_producturl") private String productUrl; @Column(name = "_comments") private String comments; public void setId (String id) { this.id = id; } public String getStatus () { return status; } public void setStatus (String status) { this.status = status; } public String getCustomer () { return customer; } public void setCustomer (String customer) { this.customer = customer; } public String getAddress () { return address; } public void setAddress (String address) { this.address = address; } public String getCity () { return city; } public void setCity (String city) { this.city = city; } public String getState () { return state; } public void setState (String state) { this.state = state; } public String getZip () { return zip; } public void setZip (String zip) { this.zip = zip; } public String getProduct () { return product; } public void setProduct (String product) { this.product = product; } public String getProductUrl () { return productUrl; } public void setProductUrl (String productUrl) { this.productUrl = productUrl; } public String getComments () { return comments; } public void setComments (String comments) { this.comments = comments; } public Job () { super(); } public Job (String id, String status, String customer, String address, String city, String state, String zip, String product, String productUrl, String comments) { super(); this.id = id; this.status = status; this.customer = customer; this.address = address; this.city = city; this.state = state; this.zip = zip; this.product = product; this.productUrl = productUrl; this.comments = comments; } public Bundle toBundle() { Bundle b = new Bundle(); b.putString("jobid", this.id); b.putString("status", this.status); b.putString("customer", this.customer); b.putString("address", this.address); b.putString("city",this.city); b.putString("state",this.state); b.putString("zip", this.zip); b.putString("product", this.product); b.putString("producturl", this.productUrl); b.putString("comments", this.comments); return b; } public static Job fromBundle(Bundle b) { Job job = new Job(); job.setId(b.getString("jobid")); job.setStatus(b.getString("status")); job.setCustomer(b.getString("customer")); job.setAddress(b.getString("address")); job.setCity(b.getString("city")); job.setState(b.getString("state")); job.setZip(b.getString("zip")); job.setProduct(b.getString("product")); job.setProductUrl(b.getString("producturl")); job.setComments(b.getString("comments")); return job; } }
9239bc63030130f110ca1f3a28588060aeeebeb1
349
java
Java
src/com/github/shanj/objextends/Student.java
shanj0508/java_project
de0899f30122123e3d4be6166a06f6233277ed34
[ "Apache-2.0" ]
null
null
null
src/com/github/shanj/objextends/Student.java
shanj0508/java_project
de0899f30122123e3d4be6166a06f6233277ed34
[ "Apache-2.0" ]
null
null
null
src/com/github/shanj/objextends/Student.java
shanj0508/java_project
de0899f30122123e3d4be6166a06f6233277ed34
[ "Apache-2.0" ]
null
null
null
20.529412
62
0.65043
998,931
package com.github.shanj.objextends; class Student extends Person { private int score; public void setScore(int score) { this.score = score; System.out.println("子类Student中打印父类Person的name:"+name); System.out.println("子类Student中打印父类Person的age:"+age); } public int getScore() { return score; } }
9239bcc6c79df1ea03f1955dd0333631e21fdf68
731
java
Java
annotation-processors/src/main/java/com/comsysto/livingdoc/annotation/processors/plantuml/model/DiagramId.java
comsysto/livingdoc
2d53681d680c355cb55152ee600cd94e5b38dfd9
[ "MIT" ]
9
2020-03-10T03:54:05.000Z
2021-08-15T01:03:48.000Z
annotation-processors/src/main/java/com/comsysto/livingdoc/annotation/processors/plantuml/model/DiagramId.java
comsysto/livingdoc
2d53681d680c355cb55152ee600cd94e5b38dfd9
[ "MIT" ]
2
2020-02-05T06:59:17.000Z
2022-03-01T15:28:36.000Z
annotation-processors/src/main/java/com/comsysto/livingdoc/annotation/processors/plantuml/model/DiagramId.java
comsysto/livingdoc
2d53681d680c355cb55152ee600cd94e5b38dfd9
[ "MIT" ]
3
2020-02-05T13:53:55.000Z
2021-03-24T10:11:55.000Z
29.24
91
0.756498
998,932
package com.comsysto.livingdoc.annotation.processors.plantuml.model; import com.comsysto.livingdoc.annotation.plantuml.PlantUmlClass; import com.comsysto.livingdoc.annotation.processors.plantuml.PlantUmlClassDiagramProcessor; import lombok.NonNull; import lombok.Value; /** * The unique ID of a diagram. */ @Value @PlantUmlClass(diagramIds = PlantUmlClassDiagramProcessor.DIAGRAM_ID) public class DiagramId { private static final DiagramId DEFAULT = new DiagramId("package"); private final String value; private DiagramId(final String value) { this.value = value; } public static DiagramId of(@NonNull final String s) { return s.equals(DEFAULT.value) ? DEFAULT : new DiagramId(s); } }
9239bcee9d349f522b6e4f7bfe20279eb6b964ca
837
java
Java
java_backup/my java/Nabina/arrange5.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
java_backup/my java/Nabina/arrange5.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
java_backup/my java/Nabina/arrange5.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
14.684211
112
0.551971
998,933
import java.io.*; class arrange5 { public static void main(String args[])throws IOException { int i,p; String s,vow="",num="",cons="",sym="",w=""; char ch; BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter text:"); s=input.readLine(); for(i=0;i<s.length();i++) { ch=s.charAt(i); //System.out.println(ch); if(ch!=' ') { p=(int)ch; if((ch=='A')||(ch=='a')||(ch=='E')||(ch=='e')||(ch=='I')||(ch=='i')||(ch=='O')||(ch=='o')||(ch=='U')||(ch=='u')) { vow=vow+ch; //break; } else if((p>=48)&&(p<=57)) { num=num+ch; //break; } else if(((p>=65)&&(p<=91))||((p>=97)&&(p<=123))) { cons=cons+ch; //break; } else { sym=sym+ch; //break; } } else if(ch==' ') { w=w+vow+cons+num+sym; System.out.print(w+" "); w=""; vow=""; num=""; cons=""; sym=""; } } w=w+vow+cons+num+sym; System.out.print(w+" "); } }
9239bd1d79ffce369b31a616fc28c97378c73bef
3,769
java
Java
soul-register-center/soul-register-client/soul-register-client-consul/src/main/java/org/dromara/soul/register/client/consul/ConsulClientRegisterRepository.java
onlyonezhongjinhui/soul
8b824dd75e085b43ad3031c0bfd9f0c3423ed4b7
[ "Apache-2.0" ]
1
2021-03-22T08:13:51.000Z
2021-03-22T08:13:51.000Z
soul-register-center/soul-register-client/soul-register-client-consul/src/main/java/org/dromara/soul/register/client/consul/ConsulClientRegisterRepository.java
onlyonezhongjinhui/soul
8b824dd75e085b43ad3031c0bfd9f0c3423ed4b7
[ "Apache-2.0" ]
74
2020-11-12T16:48:53.000Z
2021-04-22T11:07:42.000Z
soul-register-center/soul-register-client/soul-register-client-consul/src/main/java/org/dromara/soul/register/client/consul/ConsulClientRegisterRepository.java
onlyonezhongjinhui/soul
8b824dd75e085b43ad3031c0bfd9f0c3423ed4b7
[ "Apache-2.0" ]
null
null
null
45.409639
149
0.741841
998,934
/* * 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.dromara.soul.register.client.consul; import com.ecwid.consul.v1.kv.KeyValueClient; import lombok.extern.slf4j.Slf4j; import org.dromara.soul.common.enums.RpcTypeEnum; import org.dromara.soul.common.utils.GsonUtils; import org.dromara.soul.register.client.api.SoulClientRegisterRepository; import org.dromara.soul.register.common.dto.MetaDataRegisterDTO; import org.dromara.soul.register.common.dto.URIRegisterDTO; import org.dromara.soul.register.common.path.RegisterPathConstants; import org.dromara.soul.spi.Join; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.consul.serviceregistry.ConsulRegistration; @Join @Slf4j public class ConsulClientRegisterRepository implements SoulClientRegisterRepository { @Autowired private ConsulRegistration consulRegistration; @Autowired private KeyValueClient keyValueClient; @Override public void persistInterface(final MetaDataRegisterDTO metadata) { String rpcType = metadata.getRpcType(); String contextPath = metadata.getContextPath().substring(1); registerMetadata(rpcType, contextPath, metadata); if (RpcTypeEnum.HTTP.getName().equals(rpcType) || RpcTypeEnum.TARS.getName().equals(rpcType) || RpcTypeEnum.GRPC.getName().equals(rpcType)) { registerURI(metadata); } log.info("{} Consul client register success: {}", rpcType, metadata.toString()); } private void registerMetadata(final String rpcType, final String contextPath, final MetaDataRegisterDTO metadata) { String metadataNodeName = buildMetadataNodeName(metadata); String metaDataPath = RegisterPathConstants.buildMetaDataParentPath(rpcType, contextPath); String realNode = RegisterPathConstants.buildRealNode(metaDataPath, metadataNodeName); String metadataJson = GsonUtils.getInstance().toJson(metadata); keyValueClient.setKVValue(realNode, metadataJson); } private void registerURI(final MetaDataRegisterDTO metadata) { URIRegisterDTO uriRegisterDTO = URIRegisterDTO.transForm(metadata); consulRegistration.getService().getMeta().put("uri", GsonUtils.getInstance().toJson(uriRegisterDTO)); } private String buildMetadataNodeName(final MetaDataRegisterDTO metadata) { String nodeName; String rpcType = metadata.getRpcType(); if (RpcTypeEnum.HTTP.getName().equals(rpcType) || RpcTypeEnum.SPRING_CLOUD.getName().equals(rpcType)) { nodeName = String.join("-", metadata.getContextPath(), metadata.getRuleName().replace("/", "-")); } else { nodeName = buildNodeName(metadata.getServiceName(), metadata.getMethodName()); } return nodeName.substring(1); } private String buildNodeName(final String serviceName, final String methodName) { return String.join(DOT_SEPARATOR, serviceName, methodName); } }
9239be405494fa838375e3eae90d9b7cfac001c1
2,940
java
Java
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
whaling/RuoYi
184cc11d1c143aad3fb0dbbbda8cb73535b5cea3
[ "MIT" ]
1,966
2018-08-11T12:52:25.000Z
2022-03-31T15:50:41.000Z
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
whaling/RuoYi
184cc11d1c143aad3fb0dbbbda8cb73535b5cea3
[ "MIT" ]
105
2019-10-04T05:48:05.000Z
2022-03-24T03:38:47.000Z
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDictDataServiceImpl.java
whaling/RuoYi
184cc11d1c143aad3fb0dbbbda8cb73535b5cea3
[ "MIT" ]
807
2019-01-03T06:11:28.000Z
2022-03-31T05:47:51.000Z
25.565217
99
0.611565
998,935
package com.ruoyi.system.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.core.domain.entity.SysDictData; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.utils.DictUtils; import com.ruoyi.system.mapper.SysDictDataMapper; import com.ruoyi.system.service.ISysDictDataService; /** * 字典 业务层处理 * * @author ruoyi */ @Service public class SysDictDataServiceImpl implements ISysDictDataService { @Autowired private SysDictDataMapper dictDataMapper; /** * 根据条件分页查询字典数据 * * @param dictData 字典数据信息 * @return 字典数据集合信息 */ @Override public List<SysDictData> selectDictDataList(SysDictData dictData) { return dictDataMapper.selectDictDataList(dictData); } /** * 根据字典类型和字典键值查询字典数据信息 * * @param dictType 字典类型 * @param dictValue 字典键值 * @return 字典标签 */ @Override public String selectDictLabel(String dictType, String dictValue) { return dictDataMapper.selectDictLabel(dictType, dictValue); } /** * 根据字典数据ID查询信息 * * @param dictCode 字典数据ID * @return 字典数据 */ @Override public SysDictData selectDictDataById(Long dictCode) { return dictDataMapper.selectDictDataById(dictCode); } /** * 批量删除字典数据 * * @param ids 需要删除的数据 * @return 结果 */ @Override public void deleteDictDataByIds(String ids) { Long[] dictCodes = Convert.toLongArray(ids); for (Long dictCode : dictCodes) { SysDictData data = selectDictDataById(dictCode); dictDataMapper.deleteDictDataById(dictCode); List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); DictUtils.setDictCache(data.getDictType(), dictDatas); } } /** * 新增保存字典数据信息 * * @param data 字典数据信息 * @return 结果 */ @Override public int insertDictData(SysDictData data) { int row = dictDataMapper.insertDictData(data); if (row > 0) { List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); DictUtils.setDictCache(data.getDictType(), dictDatas); } return row; } /** * 修改保存字典数据信息 * * @param data 字典数据信息 * @return 结果 */ @Override public int updateDictData(SysDictData data) { int row = dictDataMapper.updateDictData(data); if (row > 0) { List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); DictUtils.setDictCache(data.getDictType(), dictDatas); } return row; } }
9239be8d1e98a821d0fcc21085d4cd3421ba9827
2,053
java
Java
src/main/java/frc/robot/Components/ArduinoSensors.java
iraiders/Robot2020_EAC
e10a18b0fc8a794aed6e4f862bbf91aaf0bc711f
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/Components/ArduinoSensors.java
iraiders/Robot2020_EAC
e10a18b0fc8a794aed6e4f862bbf91aaf0bc711f
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/Components/ArduinoSensors.java
iraiders/Robot2020_EAC
e10a18b0fc8a794aed6e4f862bbf91aaf0bc711f
[ "BSD-3-Clause" ]
null
null
null
21.385417
90
0.567949
998,936
package frc.robot.Components; import edu.wpi.first.hal.util.UncleanStatusException; import edu.wpi.first.wpilibj.SerialPort; import frc.robot.ACE.Component; public class ArduinoSensors extends Component { private double LRFinches = 0; private int SwitchBool = -1; private SerialPort port; public ArduinoSensors() { setIsActiveForTeleOp(); setIsActiveForAutonomous(); setComponentIsPrimaryForInput(); } @Override public void initialize() { try { port = new SerialPort(9600, SerialPort.Port.kUSB); } catch (UncleanStatusException u) { try { port = new SerialPort(9600, SerialPort.Port.kUSB2); } catch (UncleanStatusException u2) { port = null; } } if (port != null) { port.enableTermination(); } } public void pollSensors() { String str; if (port == null) return; str = port.readString().trim(); switch (str) { case "LRF": try { LRFinches = Double.parseDouble(port.readString().trim()) * 0.0393701; } catch (NumberFormatException e) { LRFinches = -1; } // if (LRFinches != -1) System.out.println("This is the distance: " + LRFinches); break; case "Switch": String cond = port.readString().trim(); if (cond.equals("1")) { // System.out.println("one"); SwitchBool = 1; } else if (cond.equals("0")) { // System.out.println("zero"); SwitchBool = 0; } else { // System.out.println("Error for switch"); // System.out.println("State is: " + cond); SwitchBool = -1; } break; default: break; } } public double getLRFinches() { return LRFinches; } public boolean getSwitchBool() { if (SwitchBool == 1) { return true; } if (SwitchBool == 0) { return false; } if (SwitchBool == -1) { System.out.println("Switch failed."); return false; } return false; } }
9239bed77b291332880a2e08663f936541adf85d
3,120
java
Java
src/test/java/ch/uzh/ifi/seal/soprafs19/service/UserServiceTest.java
Joey-chn/server
21587283efaeb5391bd43560507f3a5013e913b0
[ "Apache-2.0" ]
null
null
null
src/test/java/ch/uzh/ifi/seal/soprafs19/service/UserServiceTest.java
Joey-chn/server
21587283efaeb5391bd43560507f3a5013e913b0
[ "Apache-2.0" ]
null
null
null
src/test/java/ch/uzh/ifi/seal/soprafs19/service/UserServiceTest.java
Joey-chn/server
21587283efaeb5391bd43560507f3a5013e913b0
[ "Apache-2.0" ]
null
null
null
32.842105
93
0.720833
998,937
package ch.uzh.ifi.seal.soprafs19.service; import ch.uzh.ifi.seal.soprafs19.Application; import ch.uzh.ifi.seal.soprafs19.constant.UserStatus; import ch.uzh.ifi.seal.soprafs19.entity.User; import ch.uzh.ifi.seal.soprafs19.repository.UserRepository; import ch.uzh.ifi.seal.soprafs19.service.UserService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.internal.stubbing.answers.ThrowsException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.junit.rules.ExpectedException; /** * Test class for the UserResource REST resource. * * @see UserService */ @WebAppConfiguration @RunWith(SpringRunner.class) @SpringBootTest(classes= Application.class) public class UserServiceTest { @Qualifier("userRepository") @Autowired private UserRepository userRepository; @Autowired private UserService userService; @Test public void createUser() { Assert.assertNull(userRepository.findByUsername("testUsername1")); User testUser = new User(); testUser.setName("testName1"); testUser.setUsername("testUsername1"); testUser.setPassword("test"); User createdUser = userService.createUser(testUser); Assert.assertNotNull(createdUser.getToken()); Assert.assertEquals(createdUser.getStatus(),UserStatus.ONLINE); Assert.assertEquals(createdUser, userRepository.findByToken(createdUser.getToken())); } @Test public void duplicate_username() { Assert.assertNull(userRepository.findByUsername("testUsername2")); User testUser = new User(); testUser.setName("testName2"); testUser.setUsername("testUsername2"); testUser.setPassword("test"); User createdUser = userService.createUser(testUser); User testUser_2 = new User(); testUser_2.setName("testName2"); testUser_2.setUsername("testUsername2"); testUser.setPassword("test"); Assert.assertNull(userService.createUser(testUser_2)); } @Test public void updateUser() { // create a new user Assert.assertNull(userRepository.findByUsername("testUsername4")); User testUser = new User(); testUser.setName("testName4"); testUser.setUsername("testUsername4"); testUser.setPassword("test4"); User createdUser = userService.createUser(testUser); // change the new username and save it Assert.assertNull(userRepository.findByUsername("123")); String new_username = "123"; createdUser.setUsername(new_username); userRepository.save(createdUser); // find by the new username and compare the name Assert.assertEquals(userRepository.findByUsername("123").getUsername(),"123"); } }
9239bf22fd9da0c6d527708fdf9f7b00f5fd93a5
1,686
java
Java
test/com/liu233w/encryption/ex1/PlayfairCipherTest.java
Liu233w/encryption
198e5dd464bf8dbc3a6014daa80638be090081a8
[ "MIT" ]
null
null
null
test/com/liu233w/encryption/ex1/PlayfairCipherTest.java
Liu233w/encryption
198e5dd464bf8dbc3a6014daa80638be090081a8
[ "MIT" ]
null
null
null
test/com/liu233w/encryption/ex1/PlayfairCipherTest.java
Liu233w/encryption
198e5dd464bf8dbc3a6014daa80638be090081a8
[ "MIT" ]
null
null
null
29.578947
76
0.581257
998,938
package com.liu233w.encryption.ex1; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; public class PlayfairCipherTest { private PlayfairCipher playfairCipher; public PlayfairCipherTest() throws IllegalArgumentException { playfairCipher = new PlayfairCipher("INFOSEC"); } @Test public void testConstructor() throws IllegalArgumentException { char[][] table = playfairCipher.getTable(); char[][] expected = { buildRowFromString("INFOS"), buildRowFromString("ECABD"), buildRowFromString("GHKLM"), buildRowFromString("PQRTU"), buildRowFromString("VWXYZ"), }; assertThat(table).isEqualTo(expected); assertThat(new PlayfairCipher("NFOSEC").getTable()) .isEqualTo(new char[][]{ buildRowFromString("NFOSE"), buildRowFromString("CABDG"), buildRowFromString("HIKLM"), buildRowFromString("PQRTU"), buildRowFromString("VWXYZ"), }); } private char[] buildRowFromString(String row) { char[] chars = new char[5]; for (int i = 0; i < 5; ++i) { chars[i] = row.charAt(i); } return chars; } @Test public void testEncrypt() { doTest("CRYPTOISTOOEASY", "AQVTYBNIYBYFCBOZ"); doTest("CRYPTOISTOOEAS", "AQVTYBNIYBYFCBFZ"); } private void doTest(String plaintext, String cipherText) { assertThat(playfairCipher.encrypt(plaintext)).isEqualTo(cipherText); } }
9239bf6438e8d38630e96154783bc23dde05cd3a
102
java
Java
src/main/java/com/reandroid/lib/arsc/pool/PoolType.java
REAndroid/ARSCLib
1763dfbc3cf7e80e0485b6a11fcd67a1d813dc66
[ "Apache-2.0" ]
4
2021-11-17T14:15:17.000Z
2022-03-26T04:24:34.000Z
src/main/java/com/reandroid/lib/arsc/pool/PoolType.java
REAndroid/ARSCLib
1763dfbc3cf7e80e0485b6a11fcd67a1d813dc66
[ "Apache-2.0" ]
null
null
null
src/main/java/com/reandroid/lib/arsc/pool/PoolType.java
REAndroid/ARSCLib
1763dfbc3cf7e80e0485b6a11fcd67a1d813dc66
[ "Apache-2.0" ]
2
2021-11-17T14:15:19.000Z
2022-02-17T09:09:08.000Z
11.333333
36
0.627451
998,939
package com.reandroid.lib.arsc.pool; public enum PoolType { TABLE, SPEC, TYPE, XML }
9239c0bd1079c9a87e920a930c0f02b76abe4229
230
java
Java
grex/app/src/test/java/com/caffinc/grex/app/utils/ApiTest.java
caffinc/grex
fd626c91535659f2350d87e928a6671104661ae0
[ "MIT" ]
7
2017-12-02T10:45:54.000Z
2021-01-04T07:56:16.000Z
grex/app/src/test/java/com/caffinc/grex/app/utils/ApiTest.java
caffinc/grex
fd626c91535659f2350d87e928a6671104661ae0
[ "MIT" ]
null
null
null
grex/app/src/test/java/com/caffinc/grex/app/utils/ApiTest.java
caffinc/grex
fd626c91535659f2350d87e928a6671104661ae0
[ "MIT" ]
1
2017-04-26T06:25:43.000Z
2017-04-26T06:25:43.000Z
15.333333
35
0.630435
998,940
package com.caffinc.grex.app.utils; /** * Tests for the Api class * * @author Sriram */ public class ApiTest { /* TODO: Test the following: 1. Launch service without Auth 2. Launch service with Auth */ }
9239c0ddcb18a71c2d7e4082410cf1d64ffc9b23
2,764
java
Java
lexa-core/src/main/java/io/github/lexa/core/schema/profiles/CategoryProfile.java
koushikr/lexa
1f4efab09793322e2933aaf8e63b7c5be94d6d38
[ "Apache-2.0" ]
null
null
null
lexa-core/src/main/java/io/github/lexa/core/schema/profiles/CategoryProfile.java
koushikr/lexa
1f4efab09793322e2933aaf8e63b7c5be94d6d38
[ "Apache-2.0" ]
4
2020-12-14T11:58:54.000Z
2021-08-31T18:58:06.000Z
lexa-core/src/main/java/io/github/lexa/core/schema/profiles/CategoryProfile.java
koushikr/lexa
1f4efab09793322e2933aaf8e63b7c5be94d6d38
[ "Apache-2.0" ]
null
null
null
26.361905
81
0.688223
998,941
package io.github.lexa.core.schema.profiles; /* Copyright 2020 Koushik R <kenaa@example.com>. <p> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <p> http://www.apache.org/licenses/LICENSE-2.0 <p> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.google.common.collect.Sets; import lombok.*; import org.hibernate.validator.constraints.Length; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @JsonIgnoreProperties(ignoreUnknown = true) @Getter @Setter @AllArgsConstructor @ToString @NoArgsConstructor @Builder public class CategoryProfile { @NonNull @Length(max = 32) private String categoryId; private String categoryGroup; @Builder.Default private long priority = 0; @NonNull private Set<String> outgoingCategories; @Builder.Default private EntityType entityType = EntityType.CATEGORY; private EntityStatus status; private Object data; private boolean mapped; @Length(max = 255) private String entityName; @Length(max = 255) private String displayName; @Builder.Default private long updatedAt = System.currentTimeMillis(); /** * A function to add an outgoingCategoryId to the current categoryProfile */ @JsonIgnore public void addOutgoingCategory(String categoryId) { if (Objects.isNull(outgoingCategories) || outgoingCategories.isEmpty()) { this.outgoingCategories = Sets.newHashSet(categoryId); } else { this.getOutgoingCategories().add(categoryId); } } /** * A function to remove the outgoingCategoryId from the categoryProfile */ @JsonIgnore public void removeOutgoingCategory(String categoryId) { if (Objects.isNull(outgoingCategories) || outgoingCategories.isEmpty()) { return; } this.outgoingCategories = this.outgoingCategories .stream() .filter( each -> !each.equalsIgnoreCase(categoryId)) .collect(Collectors.toSet()); } public long getUpdatedAt() { if (this.updatedAt == 0) { return System.currentTimeMillis(); } return updatedAt; } }
9239c0f43ff3160e6bbab539177a70d0d53dabd7
3,560
java
Java
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/util/AbstractSequentialList/AbstractSequentialListTest.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
5
2017-03-08T20:32:39.000Z
2021-07-10T10:12:38.000Z
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/util/AbstractSequentialList/AbstractSequentialListTest.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
null
null
null
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/util/AbstractSequentialList/AbstractSequentialListTest.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
4
2015-07-07T07:06:59.000Z
2018-06-19T22:38:04.000Z
25.985401
80
0.612079
998,942
/* * 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.harmony.test.func.api.java.util.AbstractSequentialList; import java.util.AbstractSequentialList; import java.util.Iterator; import java.util.ListIterator; import org.apache.harmony.share.MultiCase; import org.apache.harmony.share.Result; class MyListIterator implements ListIterator { private int index = -1; private int fill = 0; private Object[] list; public MyListIterator(int count) { index = count - 1; list = new Object[1000]; } public int nextIndex() { return index + 1; } public int previousIndex() { return index - 1; } public void remove() { } public boolean hasNext() { //System.out.println("hasNext" + index + " " + fill); return (index + 1 < fill); } public boolean hasPrevious() { return false; } public Object next() { index++; //System.out.println("DEBUG" + index + " " + list[index]); return list[index]; } public Object previous() { return null; } public void add(Object arg0) { list[fill] = arg0; //System.out.println("DEBUG" + fill + " " + list[fill]); fill++; } public void set(Object arg0) { } } class MyAbstractSequentialList extends AbstractSequentialList { private ListIterator iter; public MyAbstractSequentialList() { super(); iter = new MyListIterator(0); } public ListIterator listIterator(int arg0) { return iter; } public int size() { return 0; } } public class AbstractSequentialListTest extends MultiCase { public static void main(String[] args) { System.exit(new AbstractSequentialListTest().test(args)); } public Result testAbstractSequentialList() { AbstractSequentialList l = new MyAbstractSequentialList(); if (l instanceof AbstractSequentialList) { return passed(); } else { return failed("Wrong object is created: " + l.getClass().getName()); } } public Result testIterator() { final Object elems[] = { "0", new Integer(25), "aaa", "string with spaces", new Object(), new MyAbstractSequentialList(), }; AbstractSequentialList l = new MyAbstractSequentialList(); Iterator i = l.iterator(); for (int j = 0; j < elems.length; j++) { l.add(j, elems[j]); } int k = 0; while (i.hasNext()) { if (!i.next().equals(elems[k++])) { return failed("next returns wrong value: index=" + k + "element=" + elems[k]); } } return passed(); } }
9239c16b2861d1ad66450d5907009920bc2eaafa
112
java
Java
app/src/main/java/com/tjr/wordsearchsolver/data/SearchResponse.java
ThomasJRichards17/WordsearchSolver
6558f52486ce6d90112af49b3fda2cd9a1bb1669
[ "MIT" ]
1
2021-02-24T22:42:19.000Z
2021-02-24T22:42:19.000Z
app/src/main/java/com/tjr/wordsearchsolver/data/SearchResponse.java
ThomasJRichards17/WordsearchSolver
6558f52486ce6d90112af49b3fda2cd9a1bb1669
[ "MIT" ]
null
null
null
app/src/main/java/com/tjr/wordsearchsolver/data/SearchResponse.java
ThomasJRichards17/WordsearchSolver
6558f52486ce6d90112af49b3fda2cd9a1bb1669
[ "MIT" ]
null
null
null
14
38
0.723214
998,943
package com.tjr.wordsearchsolver.data; public enum SearchResponse { FOUND, INCOMPLETE, INCORRECT }
9239c256cfc110817024685aeb6755a7e078b8d2
781
java
Java
src/net/redwarp/tool/resizer/worker/UnsupportedDensityException.java
liudonghua123/9-Patch-Resizer
7efe188b3a1bb7e740161c12e7c6a1b335ff8fe9
[ "Apache-2.0" ]
796
2015-01-02T09:44:14.000Z
2022-03-01T17:30:26.000Z
src/net/redwarp/tool/resizer/worker/UnsupportedDensityException.java
liudonghua123/9-Patch-Resizer
7efe188b3a1bb7e740161c12e7c6a1b335ff8fe9
[ "Apache-2.0" ]
24
2015-01-14T14:04:10.000Z
2021-08-09T11:59:02.000Z
src/net/redwarp/tool/resizer/worker/UnsupportedDensityException.java
liudonghua123/9-Patch-Resizer
7efe188b3a1bb7e740161c12e7c6a1b335ff8fe9
[ "Apache-2.0" ]
158
2015-01-06T03:33:25.000Z
2021-12-11T11:17:15.000Z
35.5
75
0.759283
998,944
/* * 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. * * Copyright 2013-2015 Redwarp */ package net.redwarp.tool.resizer.worker; public class UnsupportedDensityException extends RuntimeException { private static final long serialVersionUID = -8219133514177459994L; }
9239c3d8dd470531ebdc5852f78284646c5748db
74,433
java
Java
commandapi-core/src/test/java/Examples.java
JorelAli/1.13-Command-API
a0d9fd27257e0c21143b226a9c23e91259190a7f
[ "MIT" ]
69
2018-10-05T04:42:17.000Z
2020-07-25T14:46:42.000Z
commandapi-core/src/test/java/Examples.java
JorelAli/1.13-Command-API
a0d9fd27257e0c21143b226a9c23e91259190a7f
[ "MIT" ]
107
2018-10-05T19:20:32.000Z
2020-08-19T17:50:36.000Z
commandapi-core/src/test/java/Examples.java
JorelAli/1.13-Command-API
a0d9fd27257e0c21143b226a9c23e91259190a7f
[ "MIT" ]
24
2018-11-04T05:58:33.000Z
2020-08-14T18:27:08.000Z
33.941176
190
0.663859
998,945
/******************************************************************************* * Copyright 2018, 2021 Jorel Ali (Skepter) - MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************/ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Server; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.WorldCreator; import org.bukkit.advancement.Advancement; import org.bukkit.advancement.AdvancementProgress; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.Sign; import org.bukkit.block.data.BlockData; import org.bukkit.command.CommandSender; import org.bukkit.command.ProxiedCommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ComplexRecipe; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.loot.LootContext; import org.bukkit.loot.LootTable; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; import org.bukkit.util.EulerAngle; import com.mojang.brigadier.ParseResults; import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.context.StringRange; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.tree.LiteralCommandNode; import de.tr7zw.nbtapi.NBTContainer; import dev.jorel.commandapi.Brigadier; import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.CommandAPICommand; import dev.jorel.commandapi.CommandAPIConfig; import dev.jorel.commandapi.CommandPermission; import dev.jorel.commandapi.CommandTree; import dev.jorel.commandapi.Converter; import dev.jorel.commandapi.IStringTooltip; import dev.jorel.commandapi.StringTooltip; import dev.jorel.commandapi.Tooltip; import dev.jorel.commandapi.arguments.AdvancementArgument; import dev.jorel.commandapi.arguments.AdventureChatArgument; import dev.jorel.commandapi.arguments.AdventureChatComponentArgument; import dev.jorel.commandapi.arguments.AngleArgument; import dev.jorel.commandapi.arguments.Argument; import dev.jorel.commandapi.arguments.ArgumentSuggestions; import dev.jorel.commandapi.arguments.BiomeArgument; import dev.jorel.commandapi.arguments.BlockPredicateArgument; import dev.jorel.commandapi.arguments.BlockStateArgument; import dev.jorel.commandapi.arguments.BooleanArgument; import dev.jorel.commandapi.arguments.ChatArgument; import dev.jorel.commandapi.arguments.ChatColorArgument; import dev.jorel.commandapi.arguments.ChatComponentArgument; import dev.jorel.commandapi.arguments.CustomArgument; import dev.jorel.commandapi.arguments.CustomArgument.CustomArgumentException; import dev.jorel.commandapi.arguments.CustomArgument.MessageBuilder; import dev.jorel.commandapi.arguments.EnchantmentArgument; import dev.jorel.commandapi.arguments.EntitySelectorArgument; import dev.jorel.commandapi.arguments.EntitySelectorArgument.EntitySelector; import dev.jorel.commandapi.arguments.EntityTypeArgument; import dev.jorel.commandapi.arguments.EnvironmentArgument; import dev.jorel.commandapi.arguments.FunctionArgument; import dev.jorel.commandapi.arguments.GreedyStringArgument; import dev.jorel.commandapi.arguments.IntegerArgument; import dev.jorel.commandapi.arguments.IntegerRangeArgument; import dev.jorel.commandapi.arguments.ItemStackArgument; import dev.jorel.commandapi.arguments.ItemStackPredicateArgument; import dev.jorel.commandapi.arguments.ListArgumentBuilder; import dev.jorel.commandapi.arguments.LiteralArgument; import dev.jorel.commandapi.arguments.LocationArgument; import dev.jorel.commandapi.arguments.LocationType; import dev.jorel.commandapi.arguments.LootTableArgument; import dev.jorel.commandapi.arguments.MathOperationArgument; import dev.jorel.commandapi.arguments.MultiLiteralArgument; import dev.jorel.commandapi.arguments.NBTCompoundArgument; import dev.jorel.commandapi.arguments.ObjectiveArgument; import dev.jorel.commandapi.arguments.ObjectiveCriteriaArgument; import dev.jorel.commandapi.arguments.ParticleArgument; import dev.jorel.commandapi.arguments.PlayerArgument; import dev.jorel.commandapi.arguments.PotionEffectArgument; import dev.jorel.commandapi.arguments.RecipeArgument; import dev.jorel.commandapi.arguments.RotationArgument; import dev.jorel.commandapi.arguments.SafeSuggestions; import dev.jorel.commandapi.arguments.ScoreHolderArgument; import dev.jorel.commandapi.arguments.ScoreHolderArgument.ScoreHolderType; import dev.jorel.commandapi.arguments.ScoreboardSlotArgument; import dev.jorel.commandapi.arguments.SoundArgument; import dev.jorel.commandapi.arguments.StringArgument; import dev.jorel.commandapi.arguments.TeamArgument; import dev.jorel.commandapi.arguments.TextArgument; import dev.jorel.commandapi.arguments.TimeArgument; import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException; import dev.jorel.commandapi.executors.ExecutorType; import dev.jorel.commandapi.wrappers.FunctionWrapper; import dev.jorel.commandapi.wrappers.IntegerRange; import dev.jorel.commandapi.wrappers.MathOperation; import dev.jorel.commandapi.wrappers.ParticleData; import dev.jorel.commandapi.wrappers.Rotation; import dev.jorel.commandapi.wrappers.ScoreboardSlot; import net.kyori.adventure.inventory.Book; import net.kyori.adventure.text.Component; import net.md_5.bungee.api.chat.BaseComponent; public class Examples extends JavaPlugin { /** * The list of all examples that are present in the CommandAPI's * documentation. The indentation SHOULD NOT be changed - any * indentation that appears in here will be reflected in the * documentation and that would look terrible! * * To manage scope between each example, these should be encased * in curly braces {}. */ { /* ANCHOR: commandunregistration */ //Unregister the gamemode command from the server (by force) CommandAPI.unregister("gamemode", true); // Register our new /gamemode, with survival, creative, adventure and spectator new CommandAPICommand("gamemode") .withArguments(new MultiLiteralArgument("survival", "creative", "adventure", "spectator")) .executes((sender, args) -> { //Implementation of our /gamemode command }).register(); /* ANCHOR_END: commandunregistration */ } { /* ANCHOR: booleanargs */ // Load keys from config file String[] configKeys = getConfig().getKeys(true).toArray(new String[0]); // Register our command new CommandAPICommand("editconfig") .withArguments(new TextArgument("config-key").replaceSuggestions(ArgumentSuggestions.strings(info -> configKeys))) .withArguments(new BooleanArgument("value")) .executes((sender, args) -> { // Update the config with the boolean argument getConfig().set((String) args[0], (boolean) args[1]); }) .register(); } /* ANCHOR_END: booleanargs */ { /* ANCHOR: rangedarguments */ new CommandAPICommand("searchrange") .withArguments(new IntegerRangeArgument("range")) // Range argument .withArguments(new ItemStackArgument("item")) // The item to search for .executesPlayer((player, args) -> { // Retrieve the range from the arguments IntegerRange range = (IntegerRange) args[0]; ItemStack itemStack = (ItemStack) args[1]; // Store the locations of chests with certain items List<Location> locations = new ArrayList<>(); // Iterate through all chunks, and then all tile entities within each chunk for(Chunk chunk : player.getWorld().getLoadedChunks()) { for(BlockState blockState : chunk.getTileEntities()) { // The distance between the block and the player int distance = (int) blockState.getLocation().distance(player.getLocation()); // Check if the distance is within the specified range if(range.isInRange(distance)) { // Check if the tile entity is a chest if(blockState instanceof Chest chest) { // Check if the chest contains the item specified by the player if(chest.getInventory().contains(itemStack.getType())) { locations.add(chest.getLocation()); } } } } } // Output the locations of the chests, or whether no chests were found if(locations.isEmpty()) { player.sendMessage("No chests were found"); } else { player.sendMessage("Found " + locations.size() + " chests:"); locations.forEach(location -> { player.sendMessage(" Found at: " + location.getX() + ", " + location.getY() + ", " + location.getZ()); }); } }) .register(); /* ANCHOR_END: rangedarguments */ } { /* ANCHOR: greedystringarguments */ new CommandAPICommand("message") .withArguments(new PlayerArgument("target")) .withArguments(new GreedyStringArgument("message")) .executes((sender, args) -> { ((Player) args[0]).sendMessage((String) args[1]); }) .register(); /* ANCHOR_END: greedystringarguments */ } { /* ANCHOR: locationarguments */ new CommandAPICommand("break") //We want to target blocks in particular, so use BLOCK_POSITION .withArguments(new LocationArgument("block", LocationType.BLOCK_POSITION)) .executesPlayer((player, args) -> { ((Location) args[0]).getBlock().setType(Material.AIR); }) .register(); /* ANCHOR_END: locationarguments */ } { /* ANCHOR: rotationarguments */ new CommandAPICommand("rotate") .withArguments(new RotationArgument("rotation")) .withArguments(new EntitySelectorArgument<Entity>("target", EntitySelector.ONE_ENTITY)) .executes((sender, args) -> { Rotation rotation = (Rotation) args[0]; Entity target = (Entity) args[1]; if(target instanceof ArmorStand armorStand) { armorStand.setHeadPose(new EulerAngle(Math.toRadians(rotation.getPitch()), Math.toRadians(rotation.getYaw() - 90), 0)); } }) .register(); /* ANCHOR_END: rotationarguments */ } @SuppressWarnings("deprecation") void chatcolorarguments(){ /* ANCHOR: chatcolorarguments */ new CommandAPICommand("namecolor") .withArguments(new ChatColorArgument("chatcolor")) .executesPlayer((player, args) -> { ChatColor color = (ChatColor) args[0]; player.setDisplayName(color + player.getName()); }) .register(); /* ANCHOR_END: chatcolorarguments */ } @SuppressWarnings("deprecation") void chatcomponentarguments(){ /* ANCHOR: chatcomponentarguments */ new CommandAPICommand("makebook") .withArguments(new PlayerArgument("player")) .withArguments(new ChatComponentArgument("contents")) .executes((sender, args) -> { Player player = (Player) args[0]; BaseComponent[] arr = (BaseComponent[]) args[1]; //Create book ItemStack is = new ItemStack(Material.WRITTEN_BOOK); BookMeta meta = (BookMeta) is.getItemMeta(); meta.setTitle("Custom Book"); meta.setAuthor(player.getName()); meta.spigot().setPages(arr); is.setItemMeta(meta); //Give player the book player.getInventory().addItem(is); }) .register(); /* ANCHOR_END: chatcomponentarguments */ } @SuppressWarnings("deprecation") void chatarguments() { /* ANCHOR: chatarguments */ new CommandAPICommand("pbroadcast") .withArguments(new ChatArgument("message")) .executes((sender, args) -> { BaseComponent[] message = (BaseComponent[]) args[0]; //Broadcast the message to everyone on the server Bukkit.getServer().spigot().broadcast(message); }) .register(); /* ANCHOR_END: chatarguments */ } { /* ANCHOR: ArgumentAdventureChatComponent */ new CommandAPICommand("showbook") .withArguments(new PlayerArgument("target")) .withArguments(new TextArgument("title")) .withArguments(new StringArgument("author")) .withArguments(new AdventureChatComponentArgument("contents")) .executes((sender, args) -> { Player target = (Player) args[0]; String title = (String) args[1]; String author = (String) args[2]; Component content = (Component) args[3]; // Create a book and show it to the user (Requires Paper) Book mybook = Book.book(Component.text(title), Component.text(author), content); target.openBook(mybook); }) .register(); /* ANCHOR_END: ArgumentAdventureChatComponent */ } { /* ANCHOR: ArgumentAdventureChat */ new CommandAPICommand("pbroadcast") .withArguments(new AdventureChatArgument("message")) .executes((sender, args) -> { Component message = (Component) args[0]; // Broadcast the message to everyone with broadcast permissions. Bukkit.getServer().broadcast(message, Server.BROADCAST_CHANNEL_USERS); Bukkit.getServer().broadcast(message); }) .register(); /* ANCHOR_END: ArgumentAdventureChat */ } { /* ANCHOR: entityselectorarguments */ new CommandAPICommand("remove") //Using a collective entity selector to select multiple entities .withArguments(new EntitySelectorArgument<Collection<Entity>>("entities", EntitySelector.MANY_ENTITIES)) .executes((sender, args) -> { //Parse the argument as a collection of entities (as stated above in the documentation) @SuppressWarnings("unchecked") Collection<Entity> entities = (Collection<Entity>) args[0]; sender.sendMessage("Removed " + entities.size() + " entities"); for(Entity e : entities) { e.remove(); } }) .register(); /* ANCHOR_END: entityselectorarguments */ } { /* ANCHOR: entitytypearguments */ new CommandAPICommand("spawnmob") .withArguments(new EntityTypeArgument("entity")) .withArguments(new IntegerArgument("amount", 1, 100)) //Prevent spawning too many entities .executesPlayer((Player player, Object[] args) -> { for(int i = 0; i < (int) args[1]; i++) { player.getWorld().spawnEntity(player.getLocation(), (EntityType) args[0]); } }) .register(); /* ANCHOR_END: entitytypearguments */ } { /* ANCHOR: scoreholderargument */ new CommandAPICommand("reward") //We want multiple players, so we use ScoreHolderType.MULTIPLE in the constructor .withArguments(new ScoreHolderArgument<Collection<String>>("players", ScoreHolderType.MULTIPLE)) .executes((sender, args) -> { //Get player names by casting to Collection<String> @SuppressWarnings("unchecked") Collection<String> players = (Collection<String>) args[0]; for(String playerName : players) { Bukkit.getPlayer(playerName).getInventory().addItem(new ItemStack(Material.DIAMOND, 3)); } }) .register(); /* ANCHOR_END: scoreholderargument */ } { Object[] args = new Object[0]; @SuppressWarnings("unchecked") // This example isn't used because for some reason, mdbook doesn't render it properly /* ANCHOR: scoreholderargument_2 */ Collection<String> entitiesAndPlayers = (Collection<String>) args[0]; for(String str : entitiesAndPlayers) { try { UUID uuid = UUID.fromString(str); // Is a UUID, so it must by an entity Bukkit.getEntity(uuid); } catch(IllegalArgumentException exception) { // Not a UUID, so it must be a player name Bukkit.getPlayer(str); } } /* ANCHOR_END: scoreholderargument_2 */ } { /* ANCHOR: scoreboardslotargument */ new CommandAPICommand("clearobjectives") .withArguments(new ScoreboardSlotArgument("slot")) .executes((sender, args) -> { Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); DisplaySlot slot = ((ScoreboardSlot) args[0]).getDisplaySlot(); scoreboard.clearSlot(slot); }) .register(); /* ANCHOR_END: scoreboardslotargument */ } { /* ANCHOR: objectiveargument */ new CommandAPICommand("sidebar") .withArguments(new ObjectiveArgument("objective")) .executes((sender, args) -> { //The ObjectArgument must be casted to a String String objectiveName = (String) args[0]; //An objective name can be turned into an Objective using getObjective(String) Objective objective = Bukkit.getScoreboardManager().getMainScoreboard().getObjective(objectiveName); //Set display slot objective.setDisplaySlot(DisplaySlot.SIDEBAR); }) .register(); /* ANCHOR_END: objectiveargument */ } { /* ANCHOR: objectivecriteriaarguments */ new CommandAPICommand("unregisterall") .withArguments(new ObjectiveCriteriaArgument("objective criteria")) .executes((sender, args) -> { String objectiveCriteria = (String) args[0]; Set<Objective> objectives = Bukkit.getScoreboardManager().getMainScoreboard().getObjectivesByCriteria(objectiveCriteria); //Unregister the objectives for(Objective objective : objectives) { objective.unregister(); } }) .register(); /* ANCHOR_END: objectivecriteriaarguments */ } { /* ANCHOR: teamarguments */ new CommandAPICommand("togglepvp") .withArguments(new TeamArgument("team")) .executes((sender, args) -> { //The TeamArgument must be casted to a String String teamName = (String) args[0]; //A team name can be turned into a Team using getTeam(String) Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(teamName); //Toggle pvp team.setAllowFriendlyFire(team.allowFriendlyFire()); }) .register(); /* ANCHOR_END: teamarguments */ } { /* ANCHOR: advancementarguments */ new CommandAPICommand("award") .withArguments(new PlayerArgument("player")) .withArguments(new AdvancementArgument("advancement")) .executes((sender, args) -> { Player target = (Player) args[0]; Advancement advancement = (Advancement) args[1]; //Award all criteria for the advancement AdvancementProgress progress = target.getAdvancementProgress(advancement); for(String criteria : advancement.getCriteria()) { progress.awardCriteria(criteria); } }) .register(); /* ANCHOR_END: advancementarguments */ } { /* ANCHOR: biomearguments */ new CommandAPICommand("setbiome") .withArguments(new BiomeArgument("biome")) .executesPlayer((player, args) -> { Biome biome = (Biome) args[0]; Chunk chunk = player.getLocation().getChunk(); player.getWorld().setBiome(chunk.getX(), player.getLocation().getBlockY(), chunk.getZ(), biome); }) .register(); /* ANCHOR_END: biomearguments */ } { /* ANCHOR: blockstateargument */ new CommandAPICommand("set") .withArguments(new BlockStateArgument("block")) .executesPlayer((player, args) -> { BlockData blockdata = (BlockData) args[0]; Block targetBlock = player.getTargetBlockExact(256); // Set the block, along with its data targetBlock.setType(blockdata.getMaterial()); targetBlock.getState().setBlockData(blockdata); }) .register(); /* ANCHOR_END: blockstateargument */ } { /* ANCHOR: enchantmentarguments */ new CommandAPICommand("enchantitem") .withArguments(new EnchantmentArgument("enchantment")) .withArguments(new IntegerArgument("level", 1, 5)) .executesPlayer((player, args) -> { Enchantment enchantment = (Enchantment) args[0]; int level = (int) args[1]; //Add the enchantment player.getInventory().getItemInMainHand().addEnchantment(enchantment, level); }) .register(); /* ANCHOR_END: enchantmentarguments */ } { /* ANCHOR: environmentarguments */ new CommandAPICommand("createworld") .withArguments(new StringArgument("worldname")) .withArguments(new EnvironmentArgument("type")) .executes((sender, args) -> { String worldName = (String) args[0]; Environment environment = (Environment) args[1]; // Create a new world with the specific world name and environment Bukkit.getServer().createWorld(new WorldCreator(worldName).environment(environment)); sender.sendMessage("World created!"); }) .register(); /* ANCHOR_END: environmentarguments */ } { /* ANCHOR: itemstackarguments */ new CommandAPICommand("item") .withArguments(new ItemStackArgument("itemstack")) .executesPlayer((player, args) -> { player.getInventory().addItem((ItemStack) args[0]); }) .register(); /* ANCHOR_END: itemstackarguments */ } { /* ANCHOR: loottablearguments */ new CommandAPICommand("giveloottable") .withArguments(new LootTableArgument("loottable")) .executesPlayer((player, args) -> { LootTable lootTable = (LootTable) args[0]; /* Some generated LootContext relating to the lootTable*/ LootContext context = new LootContext.Builder(player.getLocation()).build(); lootTable.fillInventory(player.getInventory(), new Random(), context); }) .register(); /* ANCHOR_END: loottablearguments */ } { /* ANCHOR: mathoperationarguments */ new CommandAPICommand("changelevel") .withArguments(new PlayerArgument("player")) .withArguments(new MathOperationArgument("operation")) .withArguments(new IntegerArgument("value")) .executes((sender, args) -> { Player target = (Player) args[0]; MathOperation op = (MathOperation) args[1]; int value = (int) args[2]; target.setLevel(op.apply(target.getLevel(), value)); }) .register(); /* ANCHOR_END: mathoperationarguments */ } { /* ANCHOR: particlearguments */ new CommandAPICommand("showparticle") .withArguments(new ParticleArgument("particle")) .executesPlayer((player, args) -> { ParticleData<?> particleData = (ParticleData<?>) args[0]; player.getWorld().spawnParticle(particleData.particle(), player.getLocation(), 1); }) .register(); /* ANCHOR_END: particlearguments */ /* ANCHOR: particlearguments2 */ new CommandAPICommand("showparticle") .withArguments(new ParticleArgument("particle")) .executesPlayer((player, args) -> { ParticleData<?> particleData = (ParticleData<?>) args[0]; player.getWorld().spawnParticle(particleData.particle(), player.getLocation(), 1, particleData.data()); }) .register(); /* ANCHOR_END: particlearguments2 */ } { /* ANCHOR: potioneffectarguments */ new CommandAPICommand("potion") .withArguments(new PlayerArgument("target")) .withArguments(new PotionEffectArgument("potion")) .withArguments(new TimeArgument("duration")) .withArguments(new IntegerArgument("strength")) .executes((sender, args) -> { Player target = (Player) args[0]; PotionEffectType potion = (PotionEffectType) args[1]; int duration = (int) args[2]; int strength = (int) args[3]; //Add the potion effect to the target player target.addPotionEffect(new PotionEffect(potion, duration, strength)); }) .register(); /* ANCHOR_END: potioneffectarguments */ } { /* ANCHOR: recipearguments */ new CommandAPICommand("giverecipe") .withArguments(new RecipeArgument("recipe")) .executesPlayer((player, args) -> { ComplexRecipe recipe = (ComplexRecipe) args[0]; player.getInventory().addItem(recipe.getResult()); }) .register(); /* ANCHOR_END: recipearguments */ } { /* ANCHOR: recipearguments2 */ new CommandAPICommand("unlockrecipe") .withArguments(new PlayerArgument("player")) .withArguments(new RecipeArgument("recipe")) .executes((sender, args) -> { Player target = (Player) args[0]; ComplexRecipe recipe = (ComplexRecipe) args[1]; target.discoverRecipe(recipe.getKey()); }) .register(); /* ANCHOR_END: recipearguments2 */ } { /* ANCHOR: soundarguments */ new CommandAPICommand("sound") .withArguments(new SoundArgument("sound")) .executesPlayer((player, args) -> { player.getWorld().playSound(player.getLocation(), (Sound) args[0], 100.0f, 1.0f); }) .register(); /* ANCHOR_END: soundarguments */ } @SuppressWarnings("deprecation") void timearg() { /* ANCHOR: timearguments */ new CommandAPICommand("bigmsg") .withArguments(new TimeArgument("duration")) .withArguments(new GreedyStringArgument("message")) .executes((sender, args) -> { //Duration in ticks int duration = (int) args[0]; String message = (String) args[1]; for(Player player : Bukkit.getOnlinePlayers()) { //Display the message to all players, with the default fade in/out times (10 and 20). player.sendTitle(message, "", 10, duration, 20); } }) .register(); /* ANCHOR_END: timearguments */ } { /* ANCHOR: blockpredicatearguments */ Argument<?>[] arguments = new Argument[] { new IntegerArgument("radius"), new BlockPredicateArgument("fromBlock"), new BlockStateArgument("toBlock"), }; /* ANCHOR_END: blockpredicatearguments */ /* ANCHOR: blockpredicatearguments2 */ new CommandAPICommand("replace") .withArguments(arguments) .executesPlayer((player, args) -> { // Parse the arguments int radius = (int) args[0]; @SuppressWarnings("unchecked") Predicate<Block> predicate = (Predicate<Block>) args[1]; BlockData blockData = (BlockData) args[2]; // Find a (solid) sphere of blocks around the player with a given radius Location center = player.getLocation(); for (int x = -radius; x <= radius; x++) { for (int y = -radius; y <= radius; y++) { for (int z = -radius; z <= radius; z++) { if (Math.sqrt((x * x) + (y * y) + (z * z)) <= radius) { Block block = center.getWorld().getBlockAt(x + center.getBlockX(), y + center.getBlockY(), z + center.getBlockZ()); // If that block matches a block from the predicate, set it if(predicate.test(block)) { block.setType(blockData.getMaterial()); block.setBlockData(blockData); } } } } } return; }) .register(); /* ANCHOR_END: blockpredicatearguments2 */ } { /* ANCHOR: itemstackpredicatearguments */ // Register our command new CommandAPICommand("rem") .withArguments(new ItemStackPredicateArgument("items")) .executesPlayer((player, args) -> { // Get our predicate @SuppressWarnings("unchecked") Predicate<ItemStack> predicate = (Predicate<ItemStack>) args[0]; for(ItemStack item : player.getInventory()) { if(predicate.test(item)) { player.getInventory().remove(item); } } }) .register(); /* ANCHOR_END: itemstackpredicatearguments */ } @SuppressWarnings("unused") void b(){ /* ANCHOR: nbtcompoundarguments */ new CommandAPICommand("award") .withArguments(new NBTCompoundArgument("nbt")) .executes((sender, args) -> { NBTContainer nbt = (NBTContainer) args[0]; //Do something with "nbt" here... }) .register(); /* ANCHOR_END: nbtcompoundarguments */ } @SuppressWarnings("unused") void c(){ /* ANCHOR: literalarguments */ new CommandAPICommand("mycommand") .withArguments(new LiteralArgument("hello")) .withArguments(new TextArgument("text")) .executes((sender, args) -> { // This gives the variable "text" the contents of the TextArgument, and not the literal "hello" String text = (String) args[0]; }) .register(); /* ANCHOR_END: literalarguments */ } { /* ANCHOR: literalarguments2 */ //Create a map of gamemode names to their respective objects HashMap<String, GameMode> gamemodes = new HashMap<>(); gamemodes.put("adventure", GameMode.ADVENTURE); gamemodes.put("creative", GameMode.CREATIVE); gamemodes.put("spectator", GameMode.SPECTATOR); gamemodes.put("survival", GameMode.SURVIVAL); //Iterate over the map for(String key : gamemodes.keySet()) { //Register the command as usual new CommandAPICommand("changegamemode") .withArguments(new LiteralArgument(key)) .executesPlayer((player, args) -> { //Retrieve the object from the map via the key and NOT the args[] player.setGameMode(gamemodes.get(key)); }) .register(); } /* ANCHOR_END: literalarguments2 */ } { /* ANCHOR: multiliteralarguments */ new CommandAPICommand("gamemode") .withArguments(new MultiLiteralArgument("adventure", "creative", "spectator", "survival")) .executesPlayer((player, args) -> { // The literal string that the player enters IS available in the args[] switch((String) args[0]) { case "adventure": player.setGameMode(GameMode.ADVENTURE); break; case "creative": player.setGameMode(GameMode.CREATIVE); break; case "spectator": player.setGameMode(GameMode.SPECTATOR); break; case "survival": player.setGameMode(GameMode.SURVIVAL); break; } }) .register(); /* ANCHOR_END: multiliteralarguments */ } { /* ANCHOR: customarguments */ new CommandAPICommand("tpworld") .withArguments(worldArgument("world")) .executesPlayer((player, args) -> { player.teleport(((World) args[0]).getSpawnLocation()); }) .register(); /* ANCHOR_END: customarguments */ } /* ANCHOR: customarguments2 */ // Function that returns our custom argument public Argument<World> worldArgument(String nodeName) { // Construct our CustomArgument that takes in a String input and returns a World object return new CustomArgument<World>(nodeName, info -> { // Parse the world from our input World world = Bukkit.getWorld(info.input()); if(world == null) { throw new CustomArgumentException(new MessageBuilder("Unknown world: ").appendArgInput()); } else { return world; } }).replaceSuggestions(ArgumentSuggestions.strings(info -> // List of world names on the server Bukkit.getWorlds().stream().map(World::getName).toArray(String[]::new)) ); } /* ANCHOR_END: customarguments2 */ { /* ANCHOR: functionarguments */ new CommandAPICommand("runfunc") .withArguments(new FunctionArgument("function")) .executes((sender, args) -> { FunctionWrapper[] functions = (FunctionWrapper[]) args[0]; for(FunctionWrapper function : functions) { function.run(); // The command executor in this case is 'sender' } }) .register(); /* ANCHOR_END: functionarguments */ } { /* ANCHOR: functionarguments2 */ new CommandAPICommand("runfunction") .withArguments(new FunctionArgument("function")) .executes((sender, args) -> { FunctionWrapper[] functions = (FunctionWrapper[]) args[0]; //Run all functions in our FunctionWrapper[] for(FunctionWrapper function : functions) { function.run(); } }) .register(); /* ANCHOR_END: functionarguments2 */ } { /* ANCHOR: permissions */ // Register the /god command with the permission node "command.god" new CommandAPICommand("god") .withPermission(CommandPermission.fromString("command.god")) .executesPlayer((player, args) -> { player.setInvulnerable(true); }) .register(); /* ANCHOR_END: permissions */ /* ANCHOR: permissions2 */ //Register the /god command with the permission node "command.god", without creating a CommandPermission new CommandAPICommand("god") .withPermission("command.god") .executesPlayer((player, args) -> { player.setInvulnerable(true); }) .register(); /* ANCHOR_END: permissions2 */ } { /* ANCHOR: permissions3_1 */ // Register /kill command normally. Since no permissions are applied, anyone can run this command new CommandAPICommand("kill") .executesPlayer((player, args) -> { player.setHealth(0); }) .register(); /* ANCHOR_END: permissions3_1 */ } { /* ANCHOR: permissions3_2 */ // Adds the OP permission to the "target" argument. The sender requires OP to execute /kill <target> new CommandAPICommand("kill") .withArguments(new PlayerArgument("target").withPermission(CommandPermission.OP)) .executesPlayer((player, args) -> { ((Player) args[0]).setHealth(0); }) .register(); /* ANCHOR_END: permissions3_2 */ } { /* ANCHOR: aliases */ new CommandAPICommand("getpos") // Declare your aliases .withAliases("getposition", "getloc", "getlocation", "whereami") // Declare your implementation .executesEntity((entity, args) -> { entity.sendMessage(String.format("You are at %d, %d, %d", entity.getLocation().getBlockX(), entity.getLocation().getBlockY(), entity.getLocation().getBlockZ()) ); }) .executesCommandBlock((block, args) -> { block.sendMessage(String.format("You are at %d, %d, %d", block.getBlock().getLocation().getBlockX(), block.getBlock().getLocation().getBlockY(), block.getBlock().getLocation().getBlockZ()) ); }) // Register the command .register(); /* ANCHOR_END: aliases */ } { /* ANCHOR: normalcommandexecutors */ new CommandAPICommand("suicide") .executesPlayer((player, args) -> { player.setHealth(0); }) .register(); /* ANCHOR_END: normalcommandexecutors */ } { /* ANCHOR: normalcommandexecutors2 */ new CommandAPICommand("suicide") .executesPlayer((player, args) -> { player.setHealth(0); }) .executesEntity((entity, args) -> { entity.getWorld().createExplosion(entity.getLocation(), 4); entity.remove(); }) .register(); /* ANCHOR_END: normalcommandexecutors2 */ } { /* ANCHOR: normalcommandexecutors3 */ new CommandAPICommand("suicide") .executes((sender, args) -> { LivingEntity entity; if(sender instanceof ProxiedCommandSender proxy) { entity = (LivingEntity) proxy.getCallee(); } else { entity = (LivingEntity) sender; } entity.setHealth(0); }, ExecutorType.PLAYER, ExecutorType.PROXY) .register(); /* ANCHOR_END: normalcommandexecutors3 */ } @SuppressWarnings("deprecation") void normalcommandexecutors3() { /* ANCHOR: normalcommandexecutors3 */ //Create our command new CommandAPICommand("broadcastmsg") .withArguments(new GreedyStringArgument("message")) // The arguments .withAliases("broadcast", "broadcastmessage") // Command aliases .withPermission(CommandPermission.OP) // Required permissions .executes((sender, args) -> { String message = (String) args[0]; Bukkit.getServer().broadcastMessage(message); }) .register(); /* ANCHOR_END: normalcommandexecutors3 */ } { /* ANCHOR: proxysender */ new CommandAPICommand("killme") .executesPlayer((player, args) -> { player.setHealth(0); }) .register(); /* ANCHOR_END: proxysender */ } { /* ANCHOR: proxysender2 */ new CommandAPICommand("killme") .executesPlayer((player, args) -> { player.setHealth(0); }) .executesProxy((proxy, args) -> { //Check if the callee (target) is an Entity and kill it if(proxy.getCallee() instanceof LivingEntity target) { target.setHealth(0); } }) .register(); /* ANCHOR_END: proxysender2 */ } { /* ANCHOR: nativesender */ new CommandAPICommand("break") .executesNative((sender, args) -> { Location location = sender.getLocation(); if(location != null) { location.getBlock().breakNaturally(); } }) .register(); /* ANCHOR_END: nativesender */ } { /* ANCHOR: resultingcommandexecutor */ new CommandAPICommand("randnum") .executes((sender, args) -> { return new Random().nextInt(); }) .register(); /* ANCHOR_END: resultingcommandexecutor */ } { /* ANCHOR: resultingcommandexecutor2 */ //Register random number generator command from 1 to 99 (inclusive) new CommandAPICommand("randomnumber") .executes((sender, args) -> { return ThreadLocalRandom.current().nextInt(1, 100); //Returns random number from 1 <= x < 100 }) .register(); /* ANCHOR_END: resultingcommandexecutor2 */ } @SuppressWarnings("deprecation") void resultingcommandexecutor3(){ /* ANCHOR: resultingcommandexecutor3 */ // Register reward giving system for a target player new CommandAPICommand("givereward") .withArguments(new EntitySelectorArgument<Player>("target", EntitySelector.ONE_PLAYER)) .executes((sender, args) -> { Player player = (Player) args[0]; player.getInventory().addItem(new ItemStack(Material.DIAMOND, 64)); Bukkit.broadcastMessage(player.getName() + " won a rare 64 diamonds from a loot box!"); }) .register(); /* ANCHOR_END: resultingcommandexecutor3 */ } { /* ANCHOR: commandfailures */ // Array of fruit String[] fruit = new String[] {"banana", "apple", "orange"}; // Register the command new CommandAPICommand("getfruit") .withArguments(new StringArgument("item").replaceSuggestions(ArgumentSuggestions.strings(fruit))) .executes((sender, args) -> { String inputFruit = (String) args[0]; if(Arrays.stream(fruit).anyMatch(inputFruit::equals)) { // Do something with inputFruit } else { // The sender's input is not in the list of fruit throw CommandAPI.fail("That fruit doesn't exist!"); } }) .register(); /* ANCHOR_END: commandfailures */ } { /* ANCHOR: argumentsyntax1 */ new CommandAPICommand("mycommand") .withArguments(new StringArgument("arg0")) .withArguments(new StringArgument("arg1")) .withArguments(new StringArgument("arg2")) // And so on /* ANCHOR_END: argumentsyntax1 */ ; /* ANCHOR: argumentsyntax2 */ new CommandAPICommand("mycommand") .withArguments(new StringArgument("arg0"), new StringArgument("arg1"), new StringArgument("arg2")) // And so on /* ANCHOR_END: argumentsyntax2 */ ; /* ANCHOR: argumentsyntax3 */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new StringArgument("arg0")); arguments.add(new StringArgument("arg1")); arguments.add(new StringArgument("arg2")); new CommandAPICommand("mycommand") .withArguments(arguments) // And so on /* ANCHOR_END: argumentsyntax3 */ ; } { /* ANCHOR: argumentkillcmd */ new CommandAPICommand("kill") .executesPlayer((player, args) -> { player.setHealth(0); }) .register(); /* ANCHOR_END: argumentkillcmd */ /* ANCHOR: argumentkillcmd2 */ // Register our second /kill <target> command new CommandAPICommand("kill") .withArguments(new PlayerArgument("target")) .executesPlayer((player, args) -> { ((Player) args[0]).setHealth(0); }) .register(); /* ANCHOR_END: argumentkillcmd2 */ } @SuppressWarnings("unused") public void argumentCasting() { /* ANCHOR: argumentcasting */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new StringArgument("arg0")); arguments.add(new PotionEffectArgument("arg1")); arguments.add(new LocationArgument("arg2")); new CommandAPICommand("cmd") .withArguments(arguments) .executes((sender, args) -> { String stringArg = (String) args[0]; PotionEffectType potionArg = (PotionEffectType) args[1]; Location locationArg = (Location) args[2]; }) .register(); /* ANCHOR_END: argumentcasting */ } { /* ANCHOR: requirements */ new CommandAPICommand("repair") .withRequirement(sender -> ((Player) sender).getLevel() >= 30) .executesPlayer((player, args) -> { //Repair the item back to full durability ItemStack is = player.getInventory().getItemInMainHand(); ItemMeta itemMeta = is.getItemMeta(); if(itemMeta instanceof Damageable) { ((Damageable) itemMeta).setDamage(0); is.setItemMeta(itemMeta); } // Subtract 30 levels player.setLevel(player.getLevel() - 30); }) .register(); /* ANCHOR_END: requirements */ } { /* ANCHOR: requirementsmap */ Map<UUID, String> partyMembers = new HashMap<>(); /* ANCHOR_END: requirementsmap */ /* ANCHOR: requirements2 */ List<Argument<?>> arguments = new ArrayList<>(); // The "create" literal, with a requirement that a player must have a party arguments.add(new LiteralArgument("create") .withRequirement(sender -> !partyMembers.containsKey(((Player) sender).getUniqueId())) ); arguments.add(new StringArgument("partyName")); /* ANCHOR_END: requirements2 */ /* ANCHOR: requirements3 */ new CommandAPICommand("party") .withArguments(arguments) .executesPlayer((player, args) -> { //Get the name of the party to create String partyName = (String) args[0]; partyMembers.put(player.getUniqueId(), partyName); }) .register(); /* ANCHOR_END: requirements3 */ /* ANCHOR: requirementstp */ /* ANCHOR: requirements4 */ arguments = new ArrayList<>(); arguments.add(new LiteralArgument("tp") .withRequirement(sender -> partyMembers.containsKey(((Player) sender).getUniqueId())) ); /* ANCHOR_END: requirementstp */ arguments.add(new PlayerArgument("player") .replaceSafeSuggestions(SafeSuggestions.suggest(info -> { //Store the list of party members to teleport to List<Player> playersToTeleportTo = new ArrayList<>(); String partyName = partyMembers.get(((Player) info.sender()).getUniqueId()); //Find the party members for(UUID uuid : partyMembers.keySet()) { //Ignore yourself if(uuid.equals(((Player) info.sender()).getUniqueId())) { continue; } else { //If the party member is in the same party as you if(partyMembers.get(uuid).equals(partyName)) { Player target = Bukkit.getPlayer(uuid); if(target.isOnline()) { //Add them if they are online playersToTeleportTo.add(target); } } } } return playersToTeleportTo.toArray(new Player[0]); }))); /* ANCHOR_END: requirements4 */ /* ANCHOR: requirements5 */ new CommandAPICommand("party") .withArguments(arguments) .executesPlayer((player, args) -> { Player target = (Player) args[0]; player.teleport(target); }) .register(); /* ANCHOR_END: requirements5 */ /* ANCHOR: updatingrequirements */ new CommandAPICommand("party") .withArguments(arguments) .executesPlayer((player, args) -> { //Get the name of the party to create String partyName = (String) args[0]; partyMembers.put(player.getUniqueId(), partyName); CommandAPI.updateRequirements(player); }) .register(); /* ANCHOR_END: updatingrequirements */ } { /* ANCHOR: multiplerequirements */ new CommandAPICommand("someCommand") .withRequirement(sender -> ((Player) sender).getLevel() >= 30) .withRequirement(sender -> ((Player) sender).getInventory().contains(Material.DIAMOND_PICKAXE)) .withRequirement(sender -> ((Player) sender).isInvulnerable()) .executesPlayer((player, args) -> { //Code goes here }) .register(); /* ANCHOR_END: multiplerequirements */ } { Map<UUID, String> partyMembers = new HashMap<>(); /* ANCHOR: predicatetips */ Predicate<CommandSender> testIfPlayerHasParty = sender -> { return partyMembers.containsKey(((Player) sender).getUniqueId()); }; /* ANCHOR_END: predicatetips */ /* ANCHOR: predicatetips2 */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new LiteralArgument("create").withRequirement(testIfPlayerHasParty.negate())); arguments.add(new StringArgument("partyName")); /* ANCHOR_END: predicatetips2 */ /* ANCHOR: predicatetips3 */ arguments = new ArrayList<>(); arguments.add(new LiteralArgument("tp").withRequirement(testIfPlayerHasParty)); /* ANCHOR_END: predicatetips3 */ } { /* ANCHOR: converter2 */ JavaPlugin essentials = (JavaPlugin) Bukkit.getPluginManager().getPlugin("Essentials"); // /speed <speed> Converter.convert(essentials, "speed", new IntegerArgument("speed", 0, 10)); // /speed <target> Converter.convert(essentials, "speed", new PlayerArgument("target")); // /speed <walk/fly> <speed> Converter.convert(essentials, "speed", new MultiLiteralArgument("walk", "fly"), new IntegerArgument("speed", 0, 10) ); // /speed <walk/fly> <speed> <target> Converter.convert(essentials, "speed", new MultiLiteralArgument("walk", "fly"), new IntegerArgument("speed", 0, 10), new PlayerArgument("target") ); /* ANCHOR_END: converter2 */ } @SuppressWarnings({ "rawtypes", "unchecked" }) void a(){ /* ANCHOR: brigadier */ /* ANCHOR: declareliteral */ //Register literal "randomchance" LiteralCommandNode randomChance = Brigadier.fromLiteralArgument(new LiteralArgument("randomchance")).build(); /* ANCHOR_END: declareliteral */ /* ANCHOR: declarearguments */ //Declare arguments like normal List<Argument> arguments = new ArrayList<>(); arguments.add(new IntegerArgument("numerator", 0)); arguments.add(new IntegerArgument("denominator", 1)); /* ANCHOR_END: declarearguments */ //Get brigadier argument objects /* ANCHOR: declareargumentbuilders */ ArgumentBuilder numerator = Brigadier.fromArgument(arguments, "numerator"); /* ANCHOR: declarefork */ ArgumentBuilder denominator = Brigadier.fromArgument(arguments, "denominator") /* ANCHOR_END: declareargumentbuilders */ //Fork redirecting to "execute" and state our predicate .fork(Brigadier.getRootNode().getChild("execute"), Brigadier.fromPredicate((sender, args) -> { //Parse arguments like normal int num = (int) args[0]; int denom = (int) args[1]; //Return boolean with a num/denom chance return Math.ceil(Math.random() * (double) denom) <= (double) num; }, arguments)); /* ANCHOR_END: declarefork */ /* ANCHOR: declarerandomchance */ //Add <numerator> <denominator> as a child of randomchance randomChance.addChild(numerator.then(denominator).build()); /* ANCHOR_END: declarerandomchance */ /* ANCHOR: injectintoroot */ //Add (randomchance <numerator> <denominator>) as a child of (execute -> if) Brigadier.getRootNode().getChild("execute").getChild("if").addChild(randomChance); /* ANCHOR_END: injectintoroot */ /* ANCHOR_END: brigadier */ } { /* ANCHOR: subcommandspart */ CommandAPICommand groupAdd = new CommandAPICommand("add") .withArguments(new StringArgument("permission")) .withArguments(new StringArgument("groupName")) .executes((sender, args) -> { //perm group add code }); /* ANCHOR_END: subcommandspart */ /* ANCHOR: subcommands */ CommandAPICommand groupRemove = new CommandAPICommand("remove") .withArguments(new StringArgument("permission")) .withArguments(new StringArgument("groupName")) .executes((sender, args) -> { //perm group remove code }); CommandAPICommand group = new CommandAPICommand("group") .withSubcommand(groupAdd) .withSubcommand(groupRemove); /* ANCHOR_END: subcommands */ /* ANCHOR: subcommandsend */ new CommandAPICommand("perm") .withSubcommand(group) .register(); /* ANCHOR_END: subcommandsend */ /* ANCHOR: subcommands1 */ new CommandAPICommand("perm") .withSubcommand(new CommandAPICommand("group") .withSubcommand(new CommandAPICommand("add") .withArguments(new StringArgument("permission")) .withArguments(new StringArgument("groupName")) .executes((sender, args) -> { //perm group add code }) ) .withSubcommand(new CommandAPICommand("remove") .withArguments(new StringArgument("permission")) .withArguments(new StringArgument("groupName")) .executes((sender, args) -> { //perm group remove code }) ) ) .withSubcommand(new CommandAPICommand("user") .withSubcommand(new CommandAPICommand("add") .withArguments(new StringArgument("permission")) .withArguments(new StringArgument("userName")) .executes((sender, args) -> { //perm user add code }) ) .withSubcommand(new CommandAPICommand("remove") .withArguments(new StringArgument("permission")) .withArguments(new StringArgument("userName")) .executes((sender, args) -> { //perm user remove code }) ) ) .register(); /* ANCHOR_END: subcommands1 */ } @SuppressWarnings("deprecation") void help() { /* ANCHOR: help */ new CommandAPICommand("mycmd") .withShortDescription("Says hi") .withFullDescription("Broadcasts hi to everyone on the server") .executes((sender, args) -> { Bukkit.broadcastMessage("Hi!"); }) .register(); /* ANCHOR_END: help */ /* ANCHOR: help2 */ new CommandAPICommand("mycmd") .withHelp("Says hi", "Broadcasts hi to everyone on the server") .executes((sender, args) -> { Bukkit.broadcastMessage("Hi!"); }) .register(); /* ANCHOR_END: help2 */ } { //NOTE: This example isn't used! /* ANCHOR: anglearguments */ new CommandAPICommand("yaw") .withArguments(new AngleArgument("amount")) .executesPlayer((player, args) -> { Location newLocation = player.getLocation(); newLocation.setYaw((float) args[0]); player.teleport(newLocation); }) .register(); /* ANCHOR_END: anglearguments */ } { /* ANCHOR: listed */ new CommandAPICommand("mycommand") .withArguments(new PlayerArgument("player")) .withArguments(new IntegerArgument("value").setListed(false)) .withArguments(new GreedyStringArgument("message")) .executes((sender, args) -> { // args == [player, message] Player player = (Player) args[0]; String message = (String) args[1]; //Note that this is args[1] and NOT args[2] player.sendMessage(message); }) .register(); /* ANCHOR_END: listed */ } { /* ANCHOR: Tooltips1 */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new StringArgument("emote") .replaceSuggestions(ArgumentSuggestions.stringsWithTooltips(info -> new IStringTooltip[] { StringTooltip.of("wave", "Waves at a player"), StringTooltip.of("hug", "Gives a player a hug"), StringTooltip.of("glare", "Gives a player the death glare") } )) ); arguments.add(new PlayerArgument("target")); /* ANCHOR_END: Tooltips1 */ /* ANCHOR: Tooltips2 */ new CommandAPICommand("emote") .withArguments(arguments) .executesPlayer((player, args) -> { String emote = (String) args[0]; Player target = (Player) args[1]; switch(emote) { case "wave": target.sendMessage(player.getName() + " waves at you!"); break; case "hug": target.sendMessage(player.getName() + " hugs you!"); break; case "glare": target.sendMessage(player.getName() + " gives you the death glare..."); break; } }) .register(); /* ANCHOR_END: Tooltips2 */ } { /* ANCHOR: Tooltips4 */ CustomItem[] customItems = new CustomItem[] { new CustomItem(new ItemStack(Material.DIAMOND_SWORD), "God sword", "A sword from the heavens"), new CustomItem(new ItemStack(Material.PUMPKIN_PIE), "Sweet pie", "Just like grandma used to make") }; new CommandAPICommand("giveitem") .withArguments(new StringArgument("item").replaceSuggestions(ArgumentSuggestions.stringsWithTooltips(customItems))) // We use customItems[] as the input for our suggestions with tooltips .executesPlayer((player, args) -> { String itemName = (String) args[0]; //Give them the item for(CustomItem item : customItems) { if(item.getName().equals(itemName)) { player.getInventory().addItem(item.getItem()); break; } } }) .register(); /* ANCHOR_END: Tooltips4 */ } { /* ANCHOR: SafeTooltips */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new LocationArgument("location") .replaceSafeSuggestions(SafeSuggestions.tooltips(info -> { // We know the sender is a player if we use .executesPlayer() Player player = (Player) info.sender(); return Tooltip.arrayOf( Tooltip.of(player.getWorld().getSpawnLocation(), "World spawn"), Tooltip.of(player.getBedSpawnLocation(), "Your bed"), Tooltip.of(player.getTargetBlockExact(256).getLocation(), "Target block") ); }))); /* ANCHOR_END: SafeTooltips */ /* ANCHOR: SafeTooltips2 */ new CommandAPICommand("warp") .withArguments(arguments) .executesPlayer((player, args) -> { player.teleport((Location) args[0]); }) .register(); /* ANCHOR_END: SafeTooltips2 */ } { /* ANCHOR: ArgumentSuggestionsPrevious */ // Declare our arguments as normal List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new IntegerArgument("radius")); // Replace the suggestions for the PlayerArgument. // info.sender() refers to the command sender that is running this command // info.previousArgs() refers to the Object[] of previously declared arguments (in this case, the IntegerArgument radius) arguments.add(new PlayerArgument("target").replaceSuggestions(ArgumentSuggestions.strings(info -> { // Cast the first argument (radius, which is an IntegerArgument) to get its value int radius = (int) info.previousArgs()[0]; // Get nearby entities within the provided radius Player player = (Player) info.sender(); Collection<Entity> entities = player.getWorld().getNearbyEntities(player.getLocation(), radius, radius, radius); // Get player names within that radius return entities.stream() .filter(e -> e.getType() == EntityType.PLAYER) .map(Entity::getName) .toArray(String[]::new); }))); arguments.add(new GreedyStringArgument("message")); // Declare our command as normal new CommandAPICommand("localmsg") .withArguments(arguments) .executesPlayer((player, args) -> { Player target = (Player) args[1]; String message = (String) args[2]; target.sendMessage(message); }) .register(); /* ANCHOR_END: ArgumentSuggestionsPrevious */ } { /* ANCHOR: ArgumentSuggestions2_2 */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new PlayerArgument("friend").replaceSuggestions(ArgumentSuggestions.strings(info -> Friends.getFriends(info.sender()) ))); new CommandAPICommand("friendtp") .withArguments(arguments) .executesPlayer((player, args) -> { Player target = (Player) args[0]; player.teleport(target); }) .register(); /* ANCHOR_END: ArgumentSuggestions2_2 */ } { Map<String, Location> warps = new HashMap<>(); /* ANCHOR: ArgumentSuggestions1 */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new StringArgument("world").replaceSuggestions(ArgumentSuggestions.strings( "northland", "eastland", "southland", "westland" ))); new CommandAPICommand("warp") .withArguments(arguments) .executesPlayer((player, args) -> { String warp = (String) args[0]; player.teleport(warps.get(warp)); // Look up the warp in a map, for example }) .register(); /* ANCHOR_END: ArgumentSuggestions1 */ } @SuppressWarnings("deprecation") void SafeRecipeArguments() { /* ANCHOR: SafeRecipeArguments */ // Create our itemstack ItemStack emeraldSword = new ItemStack(Material.DIAMOND_SWORD); ItemMeta meta = emeraldSword.getItemMeta(); meta.setDisplayName("Emerald Sword"); meta.setUnbreakable(true); emeraldSword.setItemMeta(meta); // Create and register our recipe ShapedRecipe emeraldSwordRecipe = new ShapedRecipe(new NamespacedKey(this, "emerald_sword"), emeraldSword); emeraldSwordRecipe.shape( "AEA", "AEA", "ABA" ); emeraldSwordRecipe.setIngredient('A', Material.AIR); emeraldSwordRecipe.setIngredient('E', Material.EMERALD); emeraldSwordRecipe.setIngredient('B', Material.BLAZE_ROD); getServer().addRecipe(emeraldSwordRecipe); // Omitted, more itemstacks and recipes /* ANCHOR_END: SafeRecipeArguments */ /* ANCHOR: SafeRecipeArguments_2 */ // Safely override with the recipe we've defined List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new RecipeArgument("recipe").replaceSafeSuggestions(SafeSuggestions.suggest(info -> new Recipe[] { emeraldSwordRecipe, /* Other recipes here */ } ))); // Register our command new CommandAPICommand("giverecipe") .withArguments(arguments) .executesPlayer((player, args) -> { Recipe recipe = (Recipe) args[0]; player.getInventory().addItem(recipe.getResult()); }) .register(); /* ANCHOR_END: SafeRecipeArguments_2 */ } { /* ANCHOR: SafeMobSpawnArguments */ EntityType[] forbiddenMobs = new EntityType[] {EntityType.ENDER_DRAGON, EntityType.WITHER}; List<EntityType> allowedMobs = new ArrayList<>(Arrays.asList(EntityType.values())); allowedMobs.removeAll(Arrays.asList(forbiddenMobs)); // Now contains everything except enderdragon and wither /* ANCHOR_END: SafeMobSpawnArguments */ /* ANCHOR: SafeMobSpawnArguments_2 */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new EntityTypeArgument("mob").replaceSafeSuggestions(SafeSuggestions.suggest( info -> { if(info.sender().isOp()) { // All entity types return EntityType.values(); } else { // Only allowedMobs return allowedMobs.toArray(new EntityType[0]); } }) )); /* ANCHOR_END: SafeMobSpawnArguments_2 */ /* ANCHOR: SafeMobSpawnArguments_3 */ new CommandAPICommand("spawnmob") .withArguments(arguments) .executesPlayer((player, args) -> { EntityType entityType = (EntityType) args[0]; player.getWorld().spawnEntity(player.getLocation(), entityType); }) .register(); /* ANCHOR_END: SafeMobSpawnArguments_3 */ } { /* ANCHOR: SafePotionArguments */ List<Argument<?>> arguments = new ArrayList<>(); arguments.add(new EntitySelectorArgument<Player>("target", EntitySelector.ONE_PLAYER)); arguments.add(new PotionEffectArgument("potioneffect").replaceSafeSuggestions(SafeSuggestions.suggest( info -> { Player target = (Player) info.previousArgs()[0]; // Convert PotionEffect[] into PotionEffectType[] return target.getActivePotionEffects().stream() .map(PotionEffect::getType) .toArray(PotionEffectType[]::new); }) )); /* ANCHOR_END: SafePotionArguments */ /* ANCHOR: SafePotionArguments_2 */ new CommandAPICommand("removeeffect") .withArguments(arguments) .executesPlayer((player, args) -> { Player target = (Player) args[0]; PotionEffectType potionEffect = (PotionEffectType) args[1]; target.removePotionEffect(potionEffect); }) .register(); /* ANCHOR_END: SafePotionArguments_2 */ } { // A really simple example showing how you can use the new suggestion system final String[] fruits = new String[] { "Apple", "Apricot", "Artichoke", "Asparagus", "Atemoya", "Avocado", "Bamboo Shoots", "Banana", "Bean Sprouts", "Beans", "Beets", "Blackberries", "Blueberries", "Boniato", "Boysenberries", "Broccoflower", "Broccoli", "Cabbage", "Cactus Pear", "Cantaloupe", "Carambola", "Carrots", "Cauliflower", "Celery", "Chayote", "Cherimoya", "Cherries", "Coconuts", "Corn", "Cranberries", "Cucumber", "Dates", "Eggplant", "Endive", "Escarole", "Feijoa", "Fennel", "Figs", "Garlic", "Gooseberries", "Grapefruit", "Grapes", "Greens", "Guava", "Hominy", "Jicama", "Kale", "Kiwifruit", "Kohlrabi", "Kumquat", "Leeks", "Lemons", "Lettuce", "Lima Beans", "Limes", "Longan", "Loquat", "Lychee", "Madarins", "Malanga", "Mangos", "Mulberries", "Mushrooms", "Napa", "Nectarines", "Okra", "Onion", "Oranges", "Papayas", "Parsnip", "Peaches", "Pears", "Peas", "Peppers", "Persimmons", "Pineapple", "Plantains", "Plums", "Pomegranate", "Potatoes", "Prunes", "Pummelo", "Pumpkin", "Quince", "Radicchio", "Radishes", "Raisins", "Raspberries", "Rhubarb", "Rutabaga", "Shallots", "Spinach", "Sprouts", "Squash", "Strawberries", "Tangelo", "Tangerines", "Tomatillo", "Tomato", "Turnip", "Watercress", "Watermelon", "Yams", "Zucchini" }; new CommandAPICommand("concept") .withArguments(new StringArgument("text")) .withArguments(new StringArgument("input").replaceSuggestions(ArgumentSuggestions.strings(info -> { System.out.println(info.currentArg()); // partially typed argument System.out.println(info.currentInput()); // current input (includes the /) return Arrays.stream(fruits).filter(s -> s.toLowerCase().startsWith(info.currentArg().toLowerCase())).toArray(String[]::new); }))) .withArguments(new IntegerArgument("int")) .executes((sender, args) -> { //stuff }) .register(); } { /* ANCHOR: CommandAPIConfigSilent */ CommandAPI.onLoad(new CommandAPIConfig().silentLogs(true)); /* ANCHOR_END: CommandAPIConfigSilent */ } { JavaPlugin plugin = new JavaPlugin() {}; /* ANCHOR: asyncreadfile */ new CommandAPICommand("setconfig") .withArguments(new StringArgument("key").replaceSuggestions(ArgumentSuggestions.stringsAsync(info -> { return CompletableFuture.supplyAsync(() -> { return plugin.getConfig().getKeys(false).toArray(new String[0]); }); }))) .withArguments(new TextArgument("value")) .executes((sender, args) -> { String key = (String) args[0]; String value = (String) args[1]; plugin.getConfig().set(key, value); }) .register(); /* ANCHOR_END: asyncreadfile */ } @SuppressWarnings("unchecked") void listargument() { /* ANCHOR: ListArgument_MultiGive */ new CommandAPICommand("multigive") .withArguments(new IntegerArgument("amount", 1, 64)) .withArguments(new ListArgumentBuilder<Material>("materials") .withList(List.of(Material.values())) .withMapper(material -> material.name().toLowerCase()) .build() ) .executesPlayer((player, args) -> { int amount = (int) args[0]; List<Material> theList = (List<Material>) args[1]; for(Material item : theList) { player.getInventory().addItem(new ItemStack(item, amount)); } }) .register(); /* ANCHOR_END: ListArgument_MultiGive */ } @SuppressWarnings({ "unchecked" }) void brigadierargs() { /* ANCHOR: BrigadierSuggestions1 */ ArgumentSuggestions commandSuggestions = (info, builder) -> { // The current argument, which is a full command String arg = info.currentArg(); // Identify the position of the current argument int start; if(arg.contains(" ")) { // Current argument contains spaces - it starts after the last space and after the start of this argument. start = builder.getStart() + arg.lastIndexOf(' ') + 1; } else { // Input starts at the start of this argument start = builder.getStart(); } // Parse command using brigadier ParseResults<?> parseResults = Brigadier.getCommandDispatcher() .parse(info.currentArg(), Brigadier.getBrigadierSourceFromCommandSender(info.sender())); // Intercept any parsing errors indicating an invalid command for(CommandSyntaxException exception : parseResults.getExceptions().values()) { // Raise the error, with the cursor offset to line up with the argument throw new CommandSyntaxException(exception.getType(), exception.getRawMessage(), exception.getInput(), exception.getCursor() + start); } return Brigadier .getCommandDispatcher() .getCompletionSuggestions(parseResults) .thenApply((suggestionsObject) -> { // Brigadier's suggestions Suggestions suggestions = (Suggestions) suggestionsObject; return new Suggestions( // Offset the index range of the suggestions by the start of the current argument new StringRange(start, start + suggestions.getRange().getLength()), // Copy the suggestions suggestions.getList() ); }); }; /* ANCHOR_END: BrigadierSuggestions1 */ /* ANCHOR: BrigadierSuggestions2 */ new CommandAPICommand("commandargument") .withArguments(new GreedyStringArgument("command").replaceSuggestions(commandSuggestions)) .executes((sender, args) -> { // Run the command using Bukkit.dispatchCommand() Bukkit.dispatchCommand(sender, (String) args[0]); }).register(); /* ANCHOR_END: BrigadierSuggestions2 */ } { new CommandTree("treeexample") //Set the aliases as you normally would .withAliases("treealias") //Set an executor on the command itself .executes((sender, args) -> { sender.sendMessage("Root with no arguments"); }) //Create a new branch starting with a the literal 'integer' .then(new LiteralArgument("integer") //Execute on the literal itself .executes((sender, args) -> { sender.sendMessage("Integer Branch with no arguments"); }) //Create a further branch starting with an integer argument, which executes a command .then(new IntegerArgument("integer").executes((sender, args) -> { sender.sendMessage("Integer Branch with integer argument: " + args[0]); }))) .then(new LiteralArgument("biome") .executes((sender, args) -> { sender.sendMessage("Biome Branch with no arguments"); }) .then(new BiomeArgument("biome").executes((sender, args) -> { sender.sendMessage("Biome Branch with biome argument: " + args[0]); }))) .then(new LiteralArgument("string") .executes((sender, args) -> { sender.sendMessage("String Branch with no arguments"); }) .then(new StringArgument("string").executes((sender, args) -> { sender.sendMessage("String Branch with string argument: " + args[0]); }))) //Call register to finish as you normally would .register(); /* ANCHOR: CommandTree_sayhi1 */ new CommandTree("sayhi") .executes((sender, args) -> { sender.sendMessage("Hi!"); }) .then(new PlayerArgument("target") .executes((sender, args) -> { Player target = (Player) args[0]; target.sendMessage("Hi"); })) .register(); /* ANCHOR_END: CommandTree_sayhi1 */ } @SuppressWarnings("deprecation") public void signedit(){ /* ANCHOR: CommandTree_signedit */ new CommandTree("signedit") .then(new LiteralArgument("set") .then(new IntegerArgument("line_number", 1, 4) .then(new GreedyStringArgument("text") .executesPlayer((player, args) -> { // /signedit set <line_number> <text> Sign sign = getTargetSign(player); int line_number = (int) args[0]; String text = (String) args[1]; sign.setLine(line_number - 1, text); sign.update(true); })))) .then(new LiteralArgument("clear") .then(new IntegerArgument("line_number", 1, 4) .executesPlayer((player, args) -> { // /signedit clear <line_number> Sign sign = getTargetSign(player); int line_number = (int) args[0]; sign.setLine(line_number - 1, ""); sign.update(true); }))) .then(new LiteralArgument("copy") .then(new IntegerArgument("line_number", 1, 4) .executesPlayer((player, args) -> { // /signedit copy <line_number> Sign sign = getTargetSign(player); int line_number = (int) args[0]; player.setMetadata("copied_sign_text", new FixedMetadataValue(this, sign.getLine(line_number - 1))); }))) .then(new LiteralArgument("paste") .then(new IntegerArgument("line_number", 1, 4) .executesPlayer((player, args) -> { // /signedit copy <line_number> Sign sign = getTargetSign(player); int line_number = (int) args[0]; sign.setLine(line_number - 1, player.getMetadata("copied_sign_text").get(0).asString()); sign.update(true); }))) .register(); /* ANCHOR_END: CommandTree_signedit */ } public Sign getTargetSign(Player player) throws WrapperCommandSyntaxException { Block block = player.getTargetBlock(null, 256); if(block != null && block.getState() instanceof Sign sign) { return sign; } else { throw CommandAPI.fail("You're not looking at a sign!"); } } } // Examples class end //////////////////////////////////////////////////////////////////// /* ANCHOR: ArgumentSuggestions2_1 */ class Friends { static Map<UUID, String[]> friends = new HashMap<>(); public static String[] getFriends(CommandSender sender) { if(sender instanceof Player player) { //Look up friends in a database or file return friends.get(player.getUniqueId()); } else { return new String[0]; } } } /* ANCHOR_END: ArgumentSuggestions2_1 */ /* ANCHOR: Tooltips3 */ @SuppressWarnings("deprecation") class CustomItem implements IStringTooltip { private ItemStack itemstack; private String name; public CustomItem(ItemStack itemstack, String name, String lore) { ItemMeta meta = itemstack.getItemMeta(); meta.setDisplayName(name); meta.setLore(Arrays.asList(lore)); itemstack.setItemMeta(meta); this.itemstack = itemstack; this.name = name; } public String getName() { return this.name; } public ItemStack getItem() { return this.itemstack; } @Override public String getSuggestion() { return this.itemstack.getItemMeta().getDisplayName(); } @Override public String getTooltip() { return this.itemstack.getItemMeta().getLore().get(0); } } /* ANCHOR_END: Tooltips3 */ /* ANCHOR: functionregistration */ class Main extends JavaPlugin { @Override public void onLoad() { //Commands which will be used in Minecraft functions are registered here new CommandAPICommand("killall") .executes((sender, args) -> { //Kills all enemies in all worlds Bukkit.getWorlds().forEach(w -> w.getLivingEntities().forEach(e -> e.setHealth(0))); }) .register(); } @Override public void onEnable() { //Register all other commands here } } /* ANCHOR_END: functionregistration */ /* ANCHOR: shading */ class MyPlugin extends JavaPlugin { @Override public void onLoad() { CommandAPI.onLoad(new CommandAPIConfig().verboseOutput(true)); //Load with verbose output new CommandAPICommand("ping") .executes((sender, args) -> { sender.sendMessage("pong!"); }) .register(); } @Override public void onEnable() { CommandAPI.onEnable(this); //Register commands, listeners etc. } } /* ANCHOR_END: shading */ /* ANCHOR: converter */ class YourPlugin extends JavaPlugin { @Override public void onEnable() { Converter.convert((JavaPlugin) Bukkit.getPluginManager().getPlugin("TargetPlugin")); //Other code goes here... } } /* ANCHOR_END: converter */
9239c49e3e774dfd84c733e7cc90d0dff31ddecb
14,220
java
Java
core/src/main/java/io/undertow/conduits/ChunkedStreamSinkConduit.java
jcrossley3/undertow
e8ae111c1a7cd83325cbf9de42cf3ca3592f0697
[ "Apache-2.0" ]
1
2019-03-24T08:41:44.000Z
2019-03-24T08:41:44.000Z
core/src/main/java/io/undertow/conduits/ChunkedStreamSinkConduit.java
jcrossley3/undertow
e8ae111c1a7cd83325cbf9de42cf3ca3592f0697
[ "Apache-2.0" ]
null
null
null
core/src/main/java/io/undertow/conduits/ChunkedStreamSinkConduit.java
jcrossley3/undertow
e8ae111c1a7cd83325cbf9de42cf3ca3592f0697
[ "Apache-2.0" ]
null
null
null
37.322835
283
0.599437
998,946
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.undertow.conduits; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.util.concurrent.TimeUnit; import io.undertow.UndertowMessages; import io.undertow.server.protocol.http.HttpAttachments; import io.undertow.util.Attachable; import io.undertow.util.AttachmentKey; import io.undertow.util.HeaderMap; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import org.xnio.IoUtils; import org.xnio.Pool; import org.xnio.Pooled; import org.xnio.channels.StreamSourceChannel; import org.xnio.conduits.AbstractStreamSinkConduit; import org.xnio.conduits.ConduitWritableByteChannel; import org.xnio.conduits.Conduits; import org.xnio.conduits.StreamSinkConduit; import static org.xnio.Bits.allAreClear; import static org.xnio.Bits.anyAreSet; /** * Channel that implements HTTP chunked transfer coding. * * @author Stuart Douglas */ public class ChunkedStreamSinkConduit extends AbstractStreamSinkConduit<StreamSinkConduit> { /** * Trailers that are to be attached to the end of the HTTP response. Note that it is the callers responsibility * to make sure the client understands trailers (i.e. they have provided a TE header), and to set the 'Trailers:' * header appropriately. * <p/> * This attachment must be set before the {@link #terminateWrites()} method is called. */ @Deprecated public static final AttachmentKey<HeaderMap> TRAILERS = HttpAttachments.RESPONSE_TRAILERS; private final HeaderMap responseHeaders; private final ConduitListener<? super ChunkedStreamSinkConduit> finishListener; private final int config; private final Pool<ByteBuffer> bufferPool; /** * "0\r\n" as bytes in US ASCII encoding. */ private static final byte[] LAST_CHUNK = new byte[] {(byte) 48, (byte) 13, (byte) 10}; /** * "\r\n" as bytes in US ASCII encoding. */ private static final byte[] CRLF = new byte[] {(byte) 13, (byte) 10}; private final Attachable attachable; private int state; private int chunkleft = 0; private final ByteBuffer chunkingBuffer = ByteBuffer.allocate(12); //12 is the most private final ByteBuffer chunkingSepBuffer = ByteBuffer.allocate(2); private Pooled<ByteBuffer> lastChunkBuffer; private static final int CONF_FLAG_CONFIGURABLE = 1 << 0; private static final int CONF_FLAG_PASS_CLOSE = 1 << 1; /** * Flag that is set when {@link #terminateWrites()} or @{link #close()} is called */ private static final int FLAG_WRITES_SHUTDOWN = 1; private static final int FLAG_NEXT_SHUTDOWN = 1 << 2; private static final int FLAG_WRITTEN_FIRST_CHUNK = 1 << 3; private static final int FLAG_FIRST_DATA_WRITTEN = 1 << 4; //set on first flush or write call private static final int FLAG_FINISHED = 1 << 5; int written = 0; /** * Construct a new instance. * * @param next the channel to wrap * @param configurable {@code true} to allow configuration of the next channel, {@code false} otherwise * @param passClose {@code true} to close the underlying channel when this channel is closed, {@code false} otherwise * @param responseHeaders The response headers * @param finishListener The finish listener * @param attachable The attachable */ public ChunkedStreamSinkConduit(final StreamSinkConduit next, final Pool<ByteBuffer> bufferPool, final boolean configurable, final boolean passClose, HeaderMap responseHeaders, final ConduitListener<? super ChunkedStreamSinkConduit> finishListener, final Attachable attachable) { super(next); this.bufferPool = bufferPool; this.responseHeaders = responseHeaders; this.finishListener = finishListener; this.attachable = attachable; config = (configurable ? CONF_FLAG_CONFIGURABLE : 0) | (passClose ? CONF_FLAG_PASS_CLOSE : 0); } @Override public int write(final ByteBuffer src) throws IOException { return doWrite(src); } int doWrite(final ByteBuffer src) throws IOException { if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) { throw new ClosedChannelException(); } if(src.remaining() == 0) { return 0; } this.state |= FLAG_FIRST_DATA_WRITTEN; int oldLimit = src.limit(); if (chunkleft == 0) { chunkingBuffer.clear(); written += src.remaining(); putIntAsHexString(chunkingBuffer, src.remaining()); chunkingBuffer.put(CRLF); chunkingBuffer.flip(); chunkingSepBuffer.clear(); chunkingSepBuffer.put(CRLF); chunkingSepBuffer.flip(); state |= FLAG_WRITTEN_FIRST_CHUNK; chunkleft = src.remaining(); } else { if (src.remaining() > chunkleft) { src.limit(chunkleft + src.position()); } } try { int chunkingSize = chunkingBuffer.remaining(); int chunkingSepSize = chunkingSepBuffer.remaining(); if (chunkingSize > 0 || chunkingSepSize > 0 || lastChunkBuffer != null) { int originalRemaining = src.remaining(); long result; if (lastChunkBuffer == null) { final ByteBuffer[] buf = new ByteBuffer[]{chunkingBuffer, src, chunkingSepBuffer}; result = next.write(buf, 0, buf.length); } else { final ByteBuffer[] buf = new ByteBuffer[]{chunkingBuffer, src, lastChunkBuffer.getResource()}; if (anyAreSet(state, CONF_FLAG_PASS_CLOSE)) { result = next.writeFinal(buf, 0, buf.length); } else { result = next.write(buf, 0, buf.length); } if (!src.hasRemaining()) { state |= FLAG_WRITES_SHUTDOWN; } if (!lastChunkBuffer.getResource().hasRemaining()) { state |= FLAG_NEXT_SHUTDOWN; lastChunkBuffer.free(); } } int srcWritten = originalRemaining - src.remaining(); chunkleft -= srcWritten; if (result < chunkingSize) { return 0; } else { return srcWritten; } } else { int result = next.write(src); chunkleft -= result; return result; } } finally { src.limit(oldLimit); } } @Override public void truncateWrites() throws IOException { if(lastChunkBuffer != null) { lastChunkBuffer.free(); } super.truncateWrites(); } @Override public long write(final ByteBuffer[] srcs, final int offset, final int length) throws IOException { for (int i = offset; i < length; ++i) { if (srcs[i].hasRemaining()) { return write(srcs[i]); } } return 0; } @Override public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException { return Conduits.writeFinalBasic(this, srcs, offset, length); } @Override public int writeFinal(ByteBuffer src) throws IOException { //todo: we could optimise this to just set a content length if no data has been written if(!src.hasRemaining()) { terminateWrites(); return 0; } if (lastChunkBuffer == null) { createLastChunk(true); } return doWrite(src); } @Override public long transferFrom(final FileChannel src, final long position, final long count) throws IOException { if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) { throw new ClosedChannelException(); } return src.transferTo(position, count, new ConduitWritableByteChannel(this)); } @Override public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException { if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) { throw new ClosedChannelException(); } return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this)); } @Override public boolean flush() throws IOException { this.state |= FLAG_FIRST_DATA_WRITTEN; if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) { if (anyAreSet(state, FLAG_NEXT_SHUTDOWN)) { boolean val = next.flush(); if (val && allAreClear(state, FLAG_FINISHED)) { invokeFinishListener(); } return val; } else { next.write(lastChunkBuffer.getResource()); if (!lastChunkBuffer.getResource().hasRemaining()) { lastChunkBuffer.free(); if (anyAreSet(config, CONF_FLAG_PASS_CLOSE)) { next.terminateWrites(); } state |= FLAG_NEXT_SHUTDOWN; boolean val = next.flush(); if (val && allAreClear(state, FLAG_FINISHED)) { invokeFinishListener(); } return val; } else { return false; } } } else { return next.flush(); } } private void invokeFinishListener() { state |= FLAG_FINISHED; if (finishListener != null) { finishListener.handleEvent(this); } } @Override public void terminateWrites() throws IOException { if(anyAreSet(state, FLAG_WRITES_SHUTDOWN)) { return; } if (this.chunkleft != 0) { throw UndertowMessages.MESSAGES.chunkedChannelClosedMidChunk(); } if (!anyAreSet(state, FLAG_FIRST_DATA_WRITTEN)) { //if no data was actually sent we just remove the transfer encoding header, and set content length 0 //TODO: is this the best way to do it? //todo: should we make this behaviour configurable? responseHeaders.put(Headers.CONTENT_LENGTH, "0"); //according to the spec we don't actually need this, but better to be safe responseHeaders.remove(Headers.TRANSFER_ENCODING); state |= FLAG_NEXT_SHUTDOWN | FLAG_WRITES_SHUTDOWN; if(anyAreSet(state, CONF_FLAG_PASS_CLOSE)) { next.terminateWrites(); } } else { createLastChunk(false); state |= FLAG_WRITES_SHUTDOWN; } } private void createLastChunk(final boolean writeFinal) throws UnsupportedEncodingException { lastChunkBuffer = bufferPool.allocate(); ByteBuffer lastChunkBuffer = this.lastChunkBuffer.getResource(); if (writeFinal) { lastChunkBuffer.put(CRLF); } lastChunkBuffer.put(LAST_CHUNK); //we just assume it will fit HeaderMap trailers = attachable.getAttachment(HttpAttachments.RESPONSE_TRAILERS); if (trailers != null && trailers.size() != 0) { for (HeaderValues trailer : trailers) { for (String val : trailer) { trailer.getHeaderName().appendTo(lastChunkBuffer); lastChunkBuffer.put((byte) ':'); lastChunkBuffer.put((byte) ' '); lastChunkBuffer.put(val.getBytes("US-ASCII")); lastChunkBuffer.put(CRLF); } } lastChunkBuffer.put(CRLF); } else { lastChunkBuffer.put(CRLF); } lastChunkBuffer.flip(); } @Override public void awaitWritable() throws IOException { next.awaitWritable(); } @Override public void awaitWritable(final long time, final TimeUnit timeUnit) throws IOException { next.awaitWritable(time, timeUnit); } private static void putIntAsHexString(final ByteBuffer buf, final int v) { byte int3 = (byte) (v >> 24); byte int2 = (byte) (v >> 16); byte int1 = (byte) (v >> 8); byte int0 = (byte) (v ); boolean nonZeroFound = false; if (int3 != 0) { buf.put(DIGITS[(0xF0 & int3) >>> 4]) .put(DIGITS[0x0F & int3]); nonZeroFound = true; } if (nonZeroFound || int2 != 0) { buf.put(DIGITS[(0xF0 & int2) >>> 4]) .put(DIGITS[0x0F & int2]); nonZeroFound = true; } if (nonZeroFound || int1 != 0) { buf.put(DIGITS[(0xF0 & int1) >>> 4]) .put(DIGITS[0x0F & int1]); } buf.put(DIGITS[(0xF0 & int0) >>> 4]) .put(DIGITS[0x0F & int0]); } /** * hexadecimal digits "0123456789abcdef" as bytes in US ASCII encoding. */ private static final byte[] DIGITS = new byte[] { (byte) 48, (byte) 49, (byte) 50, (byte) 51, (byte) 52, (byte) 53, (byte) 54, (byte) 55, (byte) 56, (byte) 57, (byte) 97, (byte) 98, (byte) 99, (byte) 100, (byte) 101, (byte) 102}; }
9239c4cab38debafde63782e090bc027e7e5cc8e
546
java
Java
easylibs-streamer-core/src/main/java/org/easylibs/streamer/builder/StreamerException.java
easylibs/streamer-core
9d24be05db2bb543b6d6fcd3cc4a4dc4cef6b9e0
[ "MIT" ]
null
null
null
easylibs-streamer-core/src/main/java/org/easylibs/streamer/builder/StreamerException.java
easylibs/streamer-core
9d24be05db2bb543b6d6fcd3cc4a4dc4cef6b9e0
[ "MIT" ]
null
null
null
easylibs-streamer-core/src/main/java/org/easylibs/streamer/builder/StreamerException.java
easylibs/streamer-core
9d24be05db2bb543b6d6fcd3cc4a4dc4cef6b9e0
[ "MIT" ]
null
null
null
18.2
84
0.732601
998,947
package org.easylibs.streamer.builder; public class StreamerException extends RuntimeException { /** * */ private static final long serialVersionUID = 8043894601035890107L; public StreamerException() { } public StreamerException(String arg0) { super(arg0); } public StreamerException(Throwable arg0) { super(arg0); } public StreamerException(String arg0, Throwable arg1) { super(arg0, arg1); } public StreamerException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); } }
9239c5079bb1728b4c0f1fed4aa561e90b1b65a5
18,494
java
Java
common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java
IGIT-CN/nacos
7ee0104426a6029cd1f0766d24ee627b5f63951d
[ "Apache-2.0" ]
23,439
2018-06-15T07:02:07.000Z
2022-03-31T14:18:55.000Z
common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java
IGIT-CN/nacos
7ee0104426a6029cd1f0766d24ee627b5f63951d
[ "Apache-2.0" ]
6,521
2018-07-22T15:40:04.000Z
2022-03-31T16:00:33.000Z
common/src/test/java/com/alibaba/nacos/common/utils/ConvertUtilsTest.java
IGIT-CN/nacos
7ee0104426a6029cd1f0766d24ee627b5f63951d
[ "Apache-2.0" ]
10,494
2018-07-20T16:37:36.000Z
2022-03-31T12:49:44.000Z
57.629283
102
0.714849
998,948
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.common.utils; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; /** * Unit test of ConvertUtils. * * @author <a href="mailto:ychag@example.com">sunjifeng</a> */ public class ConvertUtilsTest { @Test public void testToInt() { // ConvertUtils.toInt(String) Assert.assertEquals(0, ConvertUtils.toInt("0")); Assert.assertEquals(-1, ConvertUtils.toInt("-1")); Assert.assertEquals(10, ConvertUtils.toInt("10")); Assert.assertEquals(Integer.MAX_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MAX_VALUE))); Assert.assertEquals(Integer.MIN_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MIN_VALUE))); Assert.assertEquals(0, ConvertUtils.toInt("notIntValue")); // ConvertUtils.toInt(String, Integer) Assert.assertEquals(0, ConvertUtils.toInt("0", 100)); Assert.assertEquals(100, ConvertUtils.toInt(null, 100)); Assert.assertEquals(100, ConvertUtils.toInt("null", 100)); Assert.assertEquals(100, ConvertUtils.toInt("notIntValue", 100)); } @Test public void testToLong() { // ConvertUtils.toLong(Object) Assert.assertEquals(0L, ConvertUtils.toLong(new ArrayList<>())); Assert.assertEquals(10L, ConvertUtils.toLong((Object) 10L)); // ConvertUtils.toLong(String) Assert.assertEquals(0L, ConvertUtils.toLong("0")); Assert.assertEquals(-1L, ConvertUtils.toLong("-1")); Assert.assertEquals(10L, ConvertUtils.toLong("10")); Assert.assertEquals(Long.MAX_VALUE, ConvertUtils.toLong(String.valueOf(Long.MAX_VALUE))); Assert.assertEquals(Long.MIN_VALUE, ConvertUtils.toLong(String.valueOf(Long.MIN_VALUE))); Assert.assertEquals(0L, ConvertUtils.toLong("notIntValue")); // ConvertUtils.toLong(String, Integer) Assert.assertEquals(0L, ConvertUtils.toLong("0", 100L)); Assert.assertEquals(100L, ConvertUtils.toLong(null, 100L)); Assert.assertEquals(100L, ConvertUtils.toLong("null", 100L)); Assert.assertEquals(100L, ConvertUtils.toLong("notIntValue", 100L)); } @Test public void testToBoolean() { // ConvertUtils.toBoolean(String) Assert.assertTrue(ConvertUtils.toBoolean("true")); Assert.assertTrue(ConvertUtils.toBoolean("True")); Assert.assertTrue(ConvertUtils.toBoolean("TRUE")); Assert.assertFalse(ConvertUtils.toBoolean("false")); Assert.assertFalse(ConvertUtils.toBoolean("False")); Assert.assertFalse(ConvertUtils.toBoolean("FALSE")); Assert.assertFalse(ConvertUtils.toBoolean(null)); Assert.assertFalse(ConvertUtils.toBoolean("notBoolean")); // ConvertUtils.toBoolean(String, boolean) Assert.assertFalse(ConvertUtils.toBoolean("", false)); Assert.assertFalse(ConvertUtils.toBoolean(null, false)); Assert.assertFalse(ConvertUtils.toBoolean("notBoolean", false)); Assert.assertTrue(ConvertUtils.toBoolean("true", false)); } @Test public void testToBooleanObject() { Assert.assertTrue(ConvertUtils.toBooleanObject("T")); Assert.assertTrue(ConvertUtils.toBooleanObject("t")); Assert.assertTrue(ConvertUtils.toBooleanObject("Y")); Assert.assertTrue(ConvertUtils.toBooleanObject("y")); Assert.assertFalse(ConvertUtils.toBooleanObject("f")); Assert.assertFalse(ConvertUtils.toBooleanObject("F")); Assert.assertFalse(ConvertUtils.toBooleanObject("n")); Assert.assertFalse(ConvertUtils.toBooleanObject("N")); Assert.assertNull(ConvertUtils.toBooleanObject("a")); Assert.assertTrue(ConvertUtils.toBooleanObject("on")); Assert.assertTrue(ConvertUtils.toBooleanObject("oN")); Assert.assertTrue(ConvertUtils.toBooleanObject("On")); Assert.assertTrue(ConvertUtils.toBooleanObject("ON")); Assert.assertFalse(ConvertUtils.toBooleanObject("No")); Assert.assertFalse(ConvertUtils.toBooleanObject("NO")); Assert.assertNull(ConvertUtils.toBooleanObject("an")); Assert.assertNull(ConvertUtils.toBooleanObject("aN")); Assert.assertNull(ConvertUtils.toBooleanObject("oa")); Assert.assertNull(ConvertUtils.toBooleanObject("Oa")); Assert.assertNull(ConvertUtils.toBooleanObject("Na")); Assert.assertNull(ConvertUtils.toBooleanObject("na")); Assert.assertNull(ConvertUtils.toBooleanObject("aO")); Assert.assertNull(ConvertUtils.toBooleanObject("ao")); Assert.assertFalse(ConvertUtils.toBooleanObject("off")); Assert.assertFalse(ConvertUtils.toBooleanObject("ofF")); Assert.assertFalse(ConvertUtils.toBooleanObject("oFf")); Assert.assertFalse(ConvertUtils.toBooleanObject("oFF")); Assert.assertFalse(ConvertUtils.toBooleanObject("Off")); Assert.assertFalse(ConvertUtils.toBooleanObject("OfF")); Assert.assertFalse(ConvertUtils.toBooleanObject("OFf")); Assert.assertFalse(ConvertUtils.toBooleanObject("OFF")); Assert.assertTrue(ConvertUtils.toBooleanObject("yes")); Assert.assertTrue(ConvertUtils.toBooleanObject("yeS")); Assert.assertTrue(ConvertUtils.toBooleanObject("yEs")); Assert.assertTrue(ConvertUtils.toBooleanObject("yES")); Assert.assertTrue(ConvertUtils.toBooleanObject("Yes")); Assert.assertTrue(ConvertUtils.toBooleanObject("YeS")); Assert.assertTrue(ConvertUtils.toBooleanObject("YEs")); Assert.assertTrue(ConvertUtils.toBooleanObject("YES")); Assert.assertNull(ConvertUtils.toBooleanObject("ono")); Assert.assertNull(ConvertUtils.toBooleanObject("aes")); Assert.assertNull(ConvertUtils.toBooleanObject("aeS")); Assert.assertNull(ConvertUtils.toBooleanObject("aEs")); Assert.assertNull(ConvertUtils.toBooleanObject("aES")); Assert.assertNull(ConvertUtils.toBooleanObject("yas")); Assert.assertNull(ConvertUtils.toBooleanObject("yaS")); Assert.assertNull(ConvertUtils.toBooleanObject("Yas")); Assert.assertNull(ConvertUtils.toBooleanObject("YaS")); Assert.assertNull(ConvertUtils.toBooleanObject("yea")); Assert.assertNull(ConvertUtils.toBooleanObject("yEa")); Assert.assertNull(ConvertUtils.toBooleanObject("Yea")); Assert.assertNull(ConvertUtils.toBooleanObject("YEa")); Assert.assertNull(ConvertUtils.toBooleanObject("aff")); Assert.assertNull(ConvertUtils.toBooleanObject("afF")); Assert.assertNull(ConvertUtils.toBooleanObject("aFf")); Assert.assertNull(ConvertUtils.toBooleanObject("aFF")); Assert.assertNull(ConvertUtils.toBooleanObject("oaf")); Assert.assertNull(ConvertUtils.toBooleanObject("oaF")); Assert.assertNull(ConvertUtils.toBooleanObject("Oaf")); Assert.assertNull(ConvertUtils.toBooleanObject("OaF")); Assert.assertNull(ConvertUtils.toBooleanObject("Ofa")); Assert.assertNull(ConvertUtils.toBooleanObject("ofa")); Assert.assertNull(ConvertUtils.toBooleanObject("OFa")); Assert.assertNull(ConvertUtils.toBooleanObject("oFa")); Assert.assertTrue(ConvertUtils.toBooleanObject("true")); Assert.assertTrue(ConvertUtils.toBooleanObject("truE")); Assert.assertTrue(ConvertUtils.toBooleanObject("trUe")); Assert.assertTrue(ConvertUtils.toBooleanObject("trUE")); Assert.assertTrue(ConvertUtils.toBooleanObject("tRue")); Assert.assertTrue(ConvertUtils.toBooleanObject("tRuE")); Assert.assertTrue(ConvertUtils.toBooleanObject("tRUe")); Assert.assertTrue(ConvertUtils.toBooleanObject("tRUE")); Assert.assertTrue(ConvertUtils.toBooleanObject("True")); Assert.assertTrue(ConvertUtils.toBooleanObject("TruE")); Assert.assertTrue(ConvertUtils.toBooleanObject("TrUe")); Assert.assertTrue(ConvertUtils.toBooleanObject("TrUE")); Assert.assertTrue(ConvertUtils.toBooleanObject("TRue")); Assert.assertTrue(ConvertUtils.toBooleanObject("TRuE")); Assert.assertTrue(ConvertUtils.toBooleanObject("TRUe")); Assert.assertTrue(ConvertUtils.toBooleanObject("TRUE")); Assert.assertNull(ConvertUtils.toBooleanObject("Xrue")); Assert.assertNull(ConvertUtils.toBooleanObject("XruE")); Assert.assertNull(ConvertUtils.toBooleanObject("XrUe")); Assert.assertNull(ConvertUtils.toBooleanObject("XrUE")); Assert.assertNull(ConvertUtils.toBooleanObject("XRue")); Assert.assertNull(ConvertUtils.toBooleanObject("XRuE")); Assert.assertNull(ConvertUtils.toBooleanObject("XRUe")); Assert.assertNull(ConvertUtils.toBooleanObject("XRUE")); Assert.assertNull(ConvertUtils.toBooleanObject("tXue")); Assert.assertNull(ConvertUtils.toBooleanObject("tXuE")); Assert.assertNull(ConvertUtils.toBooleanObject("tXUe")); Assert.assertNull(ConvertUtils.toBooleanObject("tXUE")); Assert.assertNull(ConvertUtils.toBooleanObject("TXue")); Assert.assertNull(ConvertUtils.toBooleanObject("TXuE")); Assert.assertNull(ConvertUtils.toBooleanObject("TXUe")); Assert.assertNull(ConvertUtils.toBooleanObject("TXUE")); Assert.assertNull(ConvertUtils.toBooleanObject("trXe")); Assert.assertNull(ConvertUtils.toBooleanObject("trXE")); Assert.assertNull(ConvertUtils.toBooleanObject("tRXe")); Assert.assertNull(ConvertUtils.toBooleanObject("tRXE")); Assert.assertNull(ConvertUtils.toBooleanObject("TrXe")); Assert.assertNull(ConvertUtils.toBooleanObject("TrXE")); Assert.assertNull(ConvertUtils.toBooleanObject("TRXe")); Assert.assertNull(ConvertUtils.toBooleanObject("TRXE")); Assert.assertNull(ConvertUtils.toBooleanObject("truX")); Assert.assertNull(ConvertUtils.toBooleanObject("trUX")); Assert.assertNull(ConvertUtils.toBooleanObject("tRuX")); Assert.assertNull(ConvertUtils.toBooleanObject("tRUX")); Assert.assertNull(ConvertUtils.toBooleanObject("TruX")); Assert.assertNull(ConvertUtils.toBooleanObject("TrUX")); Assert.assertNull(ConvertUtils.toBooleanObject("TRuX")); Assert.assertNull(ConvertUtils.toBooleanObject("TRUX")); Assert.assertFalse(ConvertUtils.toBooleanObject("false")); Assert.assertFalse(ConvertUtils.toBooleanObject("falsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("falSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("falSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("faLse")); Assert.assertFalse(ConvertUtils.toBooleanObject("faLsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("faLSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("faLSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("fAlse")); Assert.assertFalse(ConvertUtils.toBooleanObject("fAlsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("fAlSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("fAlSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("fALse")); Assert.assertFalse(ConvertUtils.toBooleanObject("fALsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("fALSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("fALSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("False")); Assert.assertFalse(ConvertUtils.toBooleanObject("FalsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FalSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("FalSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FaLse")); Assert.assertFalse(ConvertUtils.toBooleanObject("FaLsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FaLSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("FaLSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FAlse")); Assert.assertFalse(ConvertUtils.toBooleanObject("FAlsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FAlSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("FAlSE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FALse")); Assert.assertFalse(ConvertUtils.toBooleanObject("FALsE")); Assert.assertFalse(ConvertUtils.toBooleanObject("FALSe")); Assert.assertFalse(ConvertUtils.toBooleanObject("FALSE")); Assert.assertNull(ConvertUtils.toBooleanObject("Xalse")); Assert.assertNull(ConvertUtils.toBooleanObject("XalsE")); Assert.assertNull(ConvertUtils.toBooleanObject("XalSe")); Assert.assertNull(ConvertUtils.toBooleanObject("XalSE")); Assert.assertNull(ConvertUtils.toBooleanObject("XaLse")); Assert.assertNull(ConvertUtils.toBooleanObject("XaLsE")); Assert.assertNull(ConvertUtils.toBooleanObject("XaLSe")); Assert.assertNull(ConvertUtils.toBooleanObject("XaLSE")); Assert.assertNull(ConvertUtils.toBooleanObject("XAlse")); Assert.assertNull(ConvertUtils.toBooleanObject("XAlsE")); Assert.assertNull(ConvertUtils.toBooleanObject("XAlSe")); Assert.assertNull(ConvertUtils.toBooleanObject("XAlSE")); Assert.assertNull(ConvertUtils.toBooleanObject("XALse")); Assert.assertNull(ConvertUtils.toBooleanObject("XALsE")); Assert.assertNull(ConvertUtils.toBooleanObject("XALSe")); Assert.assertNull(ConvertUtils.toBooleanObject("XALSE")); Assert.assertNull(ConvertUtils.toBooleanObject("fXlse")); Assert.assertNull(ConvertUtils.toBooleanObject("fXlsE")); Assert.assertNull(ConvertUtils.toBooleanObject("fXlSe")); Assert.assertNull(ConvertUtils.toBooleanObject("fXlSE")); Assert.assertNull(ConvertUtils.toBooleanObject("fXLse")); Assert.assertNull(ConvertUtils.toBooleanObject("fXLsE")); Assert.assertNull(ConvertUtils.toBooleanObject("fXLSe")); Assert.assertNull(ConvertUtils.toBooleanObject("fXLSE")); Assert.assertNull(ConvertUtils.toBooleanObject("FXlse")); Assert.assertNull(ConvertUtils.toBooleanObject("FXlsE")); Assert.assertNull(ConvertUtils.toBooleanObject("FXlSe")); Assert.assertNull(ConvertUtils.toBooleanObject("FXlSE")); Assert.assertNull(ConvertUtils.toBooleanObject("FXLse")); Assert.assertNull(ConvertUtils.toBooleanObject("FXLsE")); Assert.assertNull(ConvertUtils.toBooleanObject("FXLSe")); Assert.assertNull(ConvertUtils.toBooleanObject("FXLSE")); Assert.assertNull(ConvertUtils.toBooleanObject("faXse")); Assert.assertNull(ConvertUtils.toBooleanObject("faXsE")); Assert.assertNull(ConvertUtils.toBooleanObject("faXSe")); Assert.assertNull(ConvertUtils.toBooleanObject("faXSE")); Assert.assertNull(ConvertUtils.toBooleanObject("fAXse")); Assert.assertNull(ConvertUtils.toBooleanObject("fAXsE")); Assert.assertNull(ConvertUtils.toBooleanObject("fAXSe")); Assert.assertNull(ConvertUtils.toBooleanObject("fAXSE")); Assert.assertNull(ConvertUtils.toBooleanObject("FaXse")); Assert.assertNull(ConvertUtils.toBooleanObject("FaXsE")); Assert.assertNull(ConvertUtils.toBooleanObject("FaXSe")); Assert.assertNull(ConvertUtils.toBooleanObject("FaXSE")); Assert.assertNull(ConvertUtils.toBooleanObject("FAXse")); Assert.assertNull(ConvertUtils.toBooleanObject("FAXsE")); Assert.assertNull(ConvertUtils.toBooleanObject("FAXSe")); Assert.assertNull(ConvertUtils.toBooleanObject("FAXSE")); Assert.assertNull(ConvertUtils.toBooleanObject("falXe")); Assert.assertNull(ConvertUtils.toBooleanObject("falXE")); Assert.assertNull(ConvertUtils.toBooleanObject("faLXe")); Assert.assertNull(ConvertUtils.toBooleanObject("faLXE")); Assert.assertNull(ConvertUtils.toBooleanObject("fAlXe")); Assert.assertNull(ConvertUtils.toBooleanObject("fAlXE")); Assert.assertNull(ConvertUtils.toBooleanObject("fALXe")); Assert.assertNull(ConvertUtils.toBooleanObject("fALXE")); Assert.assertNull(ConvertUtils.toBooleanObject("FalXe")); Assert.assertNull(ConvertUtils.toBooleanObject("FalXE")); Assert.assertNull(ConvertUtils.toBooleanObject("FaLXe")); Assert.assertNull(ConvertUtils.toBooleanObject("FaLXE")); Assert.assertNull(ConvertUtils.toBooleanObject("FAlXe")); Assert.assertNull(ConvertUtils.toBooleanObject("FAlXE")); Assert.assertNull(ConvertUtils.toBooleanObject("FALXe")); Assert.assertNull(ConvertUtils.toBooleanObject("FALXE")); Assert.assertNull(ConvertUtils.toBooleanObject("falsX")); Assert.assertNull(ConvertUtils.toBooleanObject("falSX")); Assert.assertNull(ConvertUtils.toBooleanObject("faLsX")); Assert.assertNull(ConvertUtils.toBooleanObject("faLSX")); Assert.assertNull(ConvertUtils.toBooleanObject("fAlsX")); Assert.assertNull(ConvertUtils.toBooleanObject("fAlSX")); Assert.assertNull(ConvertUtils.toBooleanObject("fALsX")); Assert.assertNull(ConvertUtils.toBooleanObject("fALSX")); Assert.assertNull(ConvertUtils.toBooleanObject("FalsX")); Assert.assertNull(ConvertUtils.toBooleanObject("FalSX")); Assert.assertNull(ConvertUtils.toBooleanObject("FaLsX")); Assert.assertNull(ConvertUtils.toBooleanObject("FaLSX")); Assert.assertNull(ConvertUtils.toBooleanObject("FAlsX")); Assert.assertNull(ConvertUtils.toBooleanObject("FAlSX")); Assert.assertNull(ConvertUtils.toBooleanObject("FALsX")); Assert.assertNull(ConvertUtils.toBooleanObject("FALSX")); Assert.assertNull(ConvertUtils.toBooleanObject(null)); } }
9239c5092e98776cca22eb44539f5c83fe89906c
289
java
Java
1-Patron/Java/SteamAPI.java
TanZng/patrones-combinados
93796d9d5296649bd76b7b2ee7c723156b9a120f
[ "MIT" ]
1
2021-09-13T15:45:48.000Z
2021-09-13T15:45:48.000Z
1-Patron/Java/SteamAPI.java
TanZng/patrones-combinados
93796d9d5296649bd76b7b2ee7c723156b9a120f
[ "MIT" ]
null
null
null
1-Patron/Java/SteamAPI.java
TanZng/patrones-combinados
93796d9d5296649bd76b7b2ee7c723156b9a120f
[ "MIT" ]
1
2021-09-24T03:00:47.000Z
2021-09-24T03:00:47.000Z
20.642857
41
0.636678
998,949
package masterwholeproxy; public class SteamAPI implements IAuth{ private Account account; public SteamAPI(Account account){ this.account = account; } @Override public boolean SolicitarAuth(){ return this.account.authLogin(); } }
9239c6071c55f2acc59af88eef5fca1e68a6c898
1,071
java
Java
http/src/main/java/zipkin/http/path$.java
sschwartzman/zipkin-finagle
59a50d5902c9156f73a9b626eec64b90250de082
[ "Apache-2.0" ]
1
2020-01-30T19:08:31.000Z
2020-01-30T19:08:31.000Z
http/src/main/java/zipkin/http/path$.java
sschwartzman/zipkin-finagle
59a50d5902c9156f73a9b626eec64b90250de082
[ "Apache-2.0" ]
null
null
null
http/src/main/java/zipkin/http/path$.java
sschwartzman/zipkin-finagle
59a50d5902c9156f73a9b626eec64b90250de082
[ "Apache-2.0" ]
null
null
null
32.454545
100
0.726424
998,950
/* * Copyright 2016-2018 The OpenZipkin 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 zipkin.http; import com.twitter.app.Flag; import com.twitter.app.Flaggable; import com.twitter.app.JavaGlobalFlag; public final class path$ extends JavaGlobalFlag<String> { private path$() { super("/api/v2/spans", "The URL path of the Zipkin http service. Defaults to /api/v2/spans", Flaggable.ofString()); } public static final Flag<String> Flag = new path$(); public static Flag<?> globalFlagInstance() { return Flag; } }
9239c85ec091365d289e681b35e4b16f219edb2f
2,861
java
Java
xdbm-partition/src/main/java/org/apache/directory/server/xdbm/AbstractIndexCursor.java
Dieken/directory-server
693d591f2fa4be1767b9296213b6d7f9aff0925a
[ "Apache-2.0" ]
86
2015-02-03T04:58:06.000Z
2022-03-08T10:55:45.000Z
xdbm-partition/src/main/java/org/apache/directory/server/xdbm/AbstractIndexCursor.java
Dieken/directory-server
693d591f2fa4be1767b9296213b6d7f9aff0925a
[ "Apache-2.0" ]
21
2016-05-17T13:48:07.000Z
2021-11-15T11:03:24.000Z
xdbm-partition/src/main/java/org/apache/directory/server/xdbm/AbstractIndexCursor.java
Dieken/directory-server
693d591f2fa4be1767b9296213b6d7f9aff0925a
[ "Apache-2.0" ]
82
2015-03-29T03:16:06.000Z
2022-02-20T04:59:19.000Z
27.576923
93
0.689679
998,951
/* * 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.directory.server.xdbm; import org.apache.directory.api.ldap.model.cursor.AbstractCursor; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.server.core.api.partition.PartitionTxn; /** * An abstract Cursor used by the index cursors. * * @author <a href="mailto:dycjh@example.com">Apache Directory Project</a> */ public abstract class AbstractIndexCursor<V> extends AbstractCursor<IndexEntry<V, String>> { /** Tells if there are some element available in the cursor */ private boolean available = false; /** A transaction associated with this cursor */ protected PartitionTxn partitionTxn; /** The message used for unsupported operations */ protected static final String UNSUPPORTED_MSG = "Unsupported operation"; /** * {@inheritDoc} */ public boolean available() { return available; } /** * Gets the message to return for operations that are not supported * * @return The Unsupported message */ protected abstract String getUnsupportedMessage(); /** * {@inheritDoc} */ public void after( IndexEntry<V, String> element ) throws LdapException, CursorException { throw new UnsupportedOperationException( getUnsupportedMessage() ); } /** * {@inheritDoc} */ public void before( IndexEntry<V, String> element ) throws LdapException, CursorException { throw new UnsupportedOperationException( getUnsupportedMessage() ); } /** * {@inheritDoc} */ protected boolean setAvailable( boolean available ) { this.available = available; return available; } @Override public boolean previous() throws LdapException, CursorException { return false; } @Override public boolean next() throws LdapException, CursorException { return false; } }
9239c89c7702a90febe886c27d64d23152ff4342
1,807
java
Java
api/src/main/java/cn/surveyking/server/api/AuthApi.java
jdingapp/SurveyKing
0e6a5dfee651331b107c3ce02290402f0baaf05a
[ "MIT" ]
null
null
null
api/src/main/java/cn/surveyking/server/api/AuthApi.java
jdingapp/SurveyKing
0e6a5dfee651331b107c3ce02290402f0baaf05a
[ "MIT" ]
null
null
null
api/src/main/java/cn/surveyking/server/api/AuthApi.java
jdingapp/SurveyKing
0e6a5dfee651331b107c3ce02290402f0baaf05a
[ "MIT" ]
null
null
null
34.75
114
0.830659
998,952
package cn.surveyking.server.api; import cn.surveyking.server.core.security.JwtTokenUtil; import cn.surveyking.server.domain.dto.AuthRequest; import cn.surveyking.server.domain.dto.CreateUserRequest; import cn.surveyking.server.domain.dto.UserView; import cn.surveyking.server.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; /** * @author javahuang * @date 2021/8/24 */ @RestController @RequestMapping("/api/public") @RequiredArgsConstructor public class AuthApi { private final AuthenticationManager authenticationManager; private final JwtTokenUtil jwtTokenUtil; private final UserService userService; @PostMapping("login") public ResponseEntity<UserView> login(@RequestBody @Valid AuthRequest request) { Authentication authenticate = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())); UserView user = (UserView) authenticate.getPrincipal(); return ResponseEntity.ok().header(HttpHeaders.AUTHORIZATION, jwtTokenUtil.generateAccessToken(user)).body(user); } @PostMapping("register") public UserView register(@RequestBody @Valid CreateUserRequest request) { return userService.create(request); } }
9239c904ebc57a647ac8f0c24492be9f238244c6
387
java
Java
aoe-rms-spoon/src/main/java/com/thekoldar/aoe_rms_spoon/age_versions/common/nodes/commands/connection_generation/StandardCreateConnectTeamsLands.java
Koldar/aoe-rms-spoon
9c8cbe97000c20a5d14f809fcc805fd6491720f7
[ "Apache-2.0" ]
1
2021-01-28T13:49:50.000Z
2021-01-28T13:49:50.000Z
aoe-rms-spoon/src/main/java/com/thekoldar/aoe_rms_spoon/age_versions/common/nodes/commands/connection_generation/StandardCreateConnectTeamsLands.java
Koldar/aoe-rms-spoon
9c8cbe97000c20a5d14f809fcc805fd6491720f7
[ "Apache-2.0" ]
null
null
null
aoe-rms-spoon/src/main/java/com/thekoldar/aoe_rms_spoon/age_versions/common/nodes/commands/connection_generation/StandardCreateConnectTeamsLands.java
Koldar/aoe-rms-spoon
9c8cbe97000c20a5d14f809fcc805fd6491720f7
[ "Apache-2.0" ]
null
null
null
29.769231
95
0.834625
998,953
package com.thekoldar.aoe_rms_spoon.age_versions.common.nodes.commands.connection_generation; import com.thekoldar.aoe_rms_spoon.ast.abstract_nodes.commands.AbstractCreateConnectTeamsLands; /** * Age of empires Definitive Edition version of the node. It is instantiable * @author massi * */ public class StandardCreateConnectTeamsLands extends AbstractCreateConnectTeamsLands { }
9239c989c76efc9a6fbd3d4a6db7c761fbcb460d
4,754
java
Java
dr-spring-gateway/src/main/java/com/github/wgx731/gateway/service/BermudaCounterConverter.java
wgx731/dr-spring
d6a2c18720f52b4f443e35327bf6433f18eb6fa2
[ "MIT" ]
1
2019-09-03T01:54:15.000Z
2019-09-03T01:54:15.000Z
dr-spring-gateway/src/main/java/com/github/wgx731/gateway/service/BermudaCounterConverter.java
wgx731/dr-spring
d6a2c18720f52b4f443e35327bf6433f18eb6fa2
[ "MIT" ]
9
2018-07-31T01:43:09.000Z
2019-11-26T14:46:41.000Z
dr-spring-gateway/src/main/java/com/github/wgx731/gateway/service/BermudaCounterConverter.java
wgx731/dr-spring
d6a2c18720f52b4f443e35327bf6433f18eb6fa2
[ "MIT" ]
null
null
null
31.90604
79
0.761885
998,954
package com.github.wgx731.gateway.service; import java.util.Base64; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.avro.AvroFactory; import com.fasterxml.jackson.dataformat.avro.AvroSchema; import com.fasterxml.jackson.dataformat.avro.schema.AvroSchemaGenerator; import com.fasterxml.jackson.dataformat.cbor.CBORFactory; import com.fasterxml.jackson.dataformat.csv.CsvFactory; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.fasterxml.jackson.dataformat.ion.IonFactory; import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory; import com.fasterxml.jackson.dataformat.javaprop.JavaPropsSchema; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.github.wgx731.common.pojo.BermudaTriangle; import com.github.wgx731.common.service.BermudaConverterService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Service @Slf4j public class BermudaCounterConverter implements BermudaConverterService { public static final String SEPARATOR = "<-===->"; private AvroSchema avroSchema = null; /** * Generate static UUID Response avro schema. * * @return AvroSchema UUIDResponse avro schema * @throws JsonMappingException error generate schema */ public synchronized AvroSchema getAvroSchema() throws JsonMappingException { if (avroSchema == null) { ObjectMapper mapper = new ObjectMapper(new AvroFactory()); AvroSchemaGenerator gen = new AvroSchemaGenerator(); mapper.acceptJsonFormatVisitor(BermudaTriangle.class, gen); avroSchema = gen.getGeneratedSchema(); } return avroSchema; } private CsvSchema csvSchema = null; /** * Generate static UUID Response csv schema. * * @return CsvSchema UUIDResponse csv schema * @throws JsonMappingException error generate schema */ public synchronized CsvSchema getCsvSchema() { if (csvSchema == null) { CsvMapper mapper = new CsvMapper(); csvSchema = mapper.schemaFor(BermudaTriangle.class); } return csvSchema; } private ObjectMapper propsMapper = new ObjectMapper(new JavaPropsFactory()); private ObjectMapper csvMapper = new ObjectMapper(new CsvFactory()); private ObjectMapper jsonMapper = new ObjectMapper(new JsonFactory()); private XmlMapper xmlMapper = new XmlMapper(); private ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory()); private ObjectMapper avroMapper = new ObjectMapper(new AvroFactory()); private ObjectMapper ionMapper = new ObjectMapper(new IonFactory()); private ObjectMapper cborMapper = new ObjectMapper(new CBORFactory()); @Override public String getPropertiesString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return propsMapper .writer(JavaPropsSchema.emptySchema().withKeyValueSeparator(SEPARATOR)) .writeValueAsString(bermudaTriangle); } @Override public String getCsvString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return csvMapper .writer(this.getCsvSchema()) .writeValueAsString(bermudaTriangle); } @Override public String getJsonString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return jsonMapper.writeValueAsString(bermudaTriangle); } @Override public String getXmlString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return xmlMapper.writeValueAsString(bermudaTriangle); } @Override public String getYamlString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return yamlMapper.writeValueAsString(bermudaTriangle); } @Override public String getAvroString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return Base64 .getEncoder() .encodeToString(avroMapper .writer(this.getAvroSchema()) .writeValueAsBytes(bermudaTriangle) ); } @Override public String getIonString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return Base64 .getEncoder() .encodeToString(ionMapper .writeValueAsBytes(bermudaTriangle) ); } @Override public String getCborString(BermudaTriangle bermudaTriangle) throws JsonProcessingException { return Base64 .getEncoder() .encodeToString(cborMapper .writeValueAsBytes(bermudaTriangle) ); } }
9239cacb6db17edc83f6433275dd0d3722390ba6
4,949
java
Java
coeey/io/reactivex/observers/SafeObserver.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
1
2021-08-21T17:56:56.000Z
2021-08-21T17:56:56.000Z
coeey/io/reactivex/observers/SafeObserver.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
null
null
null
coeey/io/reactivex/observers/SafeObserver.java
ankurshukla1993/IOT-test
174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6
[ "Apache-2.0" ]
1
2018-11-26T08:56:33.000Z
2018-11-26T08:56:33.000Z
33.214765
152
0.534451
998,955
package io.reactivex.observers; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.disposables.EmptyDisposable; import io.reactivex.plugins.RxJavaPlugins; public final class SafeObserver<T> implements Observer<T>, Disposable { final Observer<? super T> actual; boolean done; Disposable f2817s; public SafeObserver(@NonNull Observer<? super T> actual) { this.actual = actual; } public void onSubscribe(@NonNull Disposable s) { if (DisposableHelper.validate(this.f2817s, s)) { this.f2817s = s; try { this.actual.onSubscribe(this); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); RxJavaPlugins.onError(new CompositeException(e, e1)); } } } public void dispose() { this.f2817s.dispose(); } public boolean isDisposed() { return this.f2817s.isDisposed(); } public void onNext(@NonNull T t) { if (!this.done) { if (this.f2817s == null) { onNextNoSubscription(); } else if (t == null) { Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."); try { this.f2817s.dispose(); onError(ex); } catch (Throwable e1) { Exceptions.throwIfFatal(e1); onError(new CompositeException(ex, e1)); } } else { try { this.actual.onNext(t); } catch (Throwable e12) { Exceptions.throwIfFatal(e12); onError(new CompositeException(e, e12)); } } } } void onNextNoSubscription() { this.done = true; Throwable ex = new NullPointerException("Subscription not set!"); try { this.actual.onSubscribe(EmptyDisposable.INSTANCE); try { this.actual.onError(ex); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(new CompositeException(ex, e)); } } catch (Throwable e2) { Exceptions.throwIfFatal(e2); RxJavaPlugins.onError(new CompositeException(ex, e2)); } } public void onError(@NonNull Throwable t) { if (this.done) { RxJavaPlugins.onError(t); return; } this.done = true; if (this.f2817s == null) { Throwable npe = new NullPointerException("Subscription not set!"); try { this.actual.onSubscribe(EmptyDisposable.INSTANCE); try { this.actual.onError(new CompositeException(t, npe)); return; } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(new CompositeException(t, npe, e)); return; } } catch (Throwable e2) { Exceptions.throwIfFatal(e2); RxJavaPlugins.onError(new CompositeException(t, npe, e2)); return; } } if (t == null) { t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources."); } try { this.actual.onError(t); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); RxJavaPlugins.onError(new CompositeException(t, ex)); } } public void onComplete() { if (!this.done) { this.done = true; if (this.f2817s == null) { onCompleteNoSubscription(); return; } try { this.actual.onComplete(); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(e); } } } void onCompleteNoSubscription() { Throwable ex = new NullPointerException("Subscription not set!"); try { this.actual.onSubscribe(EmptyDisposable.INSTANCE); try { this.actual.onError(ex); } catch (Throwable e) { Exceptions.throwIfFatal(e); RxJavaPlugins.onError(new CompositeException(ex, e)); } } catch (Throwable e2) { Exceptions.throwIfFatal(e2); RxJavaPlugins.onError(new CompositeException(ex, e2)); } } }
9239cb3426e070dcdb547342a51c0a0d8f087103
1,279
java
Java
graphql-thorntail-fraction/src/main/java/org/wildfly/swarm/microprofile/graphql/MicroprofileGraphQLFraction.java
phillip-kruger/graphql
7cec283b630ff73a842992c5df9b2e7ab8870704
[ "Apache-2.0" ]
null
null
null
graphql-thorntail-fraction/src/main/java/org/wildfly/swarm/microprofile/graphql/MicroprofileGraphQLFraction.java
phillip-kruger/graphql
7cec283b630ff73a842992c5df9b2e7ab8870704
[ "Apache-2.0" ]
null
null
null
graphql-thorntail-fraction/src/main/java/org/wildfly/swarm/microprofile/graphql/MicroprofileGraphQLFraction.java
phillip-kruger/graphql
7cec283b630ff73a842992c5df9b2e7ab8870704
[ "Apache-2.0" ]
null
null
null
37.852941
140
0.784771
998,956
/** * Copyright 2019 Phillip Kruger * * 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.wildfly.swarm.microprofile.graphql; import static org.wildfly.swarm.spi.api.annotations.DeploymentModule.MetaInfDisposition.IMPORT; import lombok.NoArgsConstructor; import org.wildfly.swarm.spi.api.Fraction; import org.wildfly.swarm.spi.api.Module; import org.wildfly.swarm.spi.api.annotations.DeploymentModule; /** * Thorntail fraction for MicroProfile GraphQL * @author Phillip Kruger (nnheo@example.com) */ @DeploymentModule(name = "org.wildfly.swarm.microprofile.graphql",metaInf = IMPORT, export = true, services = Module.ServiceHandling.IMPORT) @NoArgsConstructor public class MicroprofileGraphQLFraction implements Fraction<MicroprofileGraphQLFraction> { }
9239cb7d0e787ee61ac51f42172eb049ab299ba2
1,065
java
Java
src/main/java/sk/stuba/fei/zadanie3/contract/nonlifesurence/HouseholdInsurance.java
matush97/userContract
f2c14e11090d6478b6a856db89ed4668cde26da0
[ "MIT" ]
null
null
null
src/main/java/sk/stuba/fei/zadanie3/contract/nonlifesurence/HouseholdInsurance.java
matush97/userContract
f2c14e11090d6478b6a856db89ed4668cde26da0
[ "MIT" ]
null
null
null
src/main/java/sk/stuba/fei/zadanie3/contract/nonlifesurence/HouseholdInsurance.java
matush97/userContract
f2c14e11090d6478b6a856db89ed4668cde26da0
[ "MIT" ]
null
null
null
36.724138
219
0.621596
998,957
package sk.stuba.fei.zadanie3.contract.nonlifesurence; import lombok.NoArgsConstructor; import sk.stuba.fei.zadanie3.user.Adress; import sk.stuba.fei.zadanie3.user.User; @NoArgsConstructor public class HouseholdInsurance extends NonLifeInsurance { // TODO Poistenie domácnosti public HouseholdInsurance(int id, String date, User user, String startDate, String endDate, int amaunt, int monthlyPayment, TypeProperty typeProperty, Adress adress, int valueProperty, int valueHouseholdEquipment) { super(id, date, user, startDate, endDate, amaunt, monthlyPayment, typeProperty, adress, valueProperty, valueHouseholdEquipment); } @Override public String toString() { return "HouseholdInsurance{" + "id=" + id + ", date='" + date + '\'' + ", user=" + user + ", startDate='" + startDate + '\'' + ", endDate='" + endDate + '\'' + ", amaunt=" + amaunt + ", monthlyPayment=" + monthlyPayment + '}'; } }
9239cc02d4149dbfbdc69c41d33adefdeecb5f68
661
java
Java
flink-streaming-web-common/src/main/java/com/flink/streaming/web/model/entity/AlartLog.java
bulolo/flink-streaming-platform-web
1a3afa0e4c36065d6a91607395b19553accfa43b
[ "MIT" ]
1,175
2020-10-21T02:47:06.000Z
2022-03-31T20:48:32.000Z
flink-streaming-web-common/src/main/java/com/flink/streaming/web/model/entity/AlartLog.java
bulolo/flink-streaming-platform-web
1a3afa0e4c36065d6a91607395b19553accfa43b
[ "MIT" ]
46
2020-11-09T02:44:46.000Z
2022-03-31T04:11:41.000Z
flink-streaming-web-common/src/main/java/com/flink/streaming/web/model/entity/AlartLog.java
bulolo/flink-streaming-platform-web
1a3afa0e4c36065d6a91607395b19553accfa43b
[ "MIT" ]
461
2020-10-21T07:27:09.000Z
2022-03-31T06:29:50.000Z
11.596491
45
0.546142
998,958
package com.flink.streaming.web.model.entity; import lombok.Data; import java.util.Date; /** * @author */ @Data public class AlartLog { private Long id; private Long jobConfigId; private String jobName; /** * 消息内容 */ private String message; /** * 1:钉钉 */ private Integer type; /** * 1:成功 0:失败 */ private Integer status; /** * 失败原因 */ private String failLog; private Integer isDeleted; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date editTime; private String creator; private String editor; }
9239cc1e4355a6ca94d876733200b6e9f9a5f582
7,183
java
Java
source/apis/canvaslms4j/src/main/java/de/m0ep/canvas/Entries.java
m0ep/master-thesis
f4fc3d857a9f12baddc46366b78764e913dbf55f
[ "MIT" ]
null
null
null
source/apis/canvaslms4j/src/main/java/de/m0ep/canvas/Entries.java
m0ep/master-thesis
f4fc3d857a9f12baddc46366b78764e913dbf55f
[ "MIT" ]
null
null
null
source/apis/canvaslms4j/src/main/java/de/m0ep/canvas/Entries.java
m0ep/master-thesis
f4fc3d857a9f12baddc46366b78764e913dbf55f
[ "MIT" ]
1
2018-08-05T17:05:52.000Z
2018-08-05T17:05:52.000Z
29.318367
82
0.665739
998,959
/* * The MIT License (MIT) Copyright © 2013 Florian Müller * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Software”), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package de.m0ep.canvas; import java.nio.charset.Charset; import java.util.Arrays; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.damnhandy.uri.template.UriTemplate; import de.m0ep.canvas.exceptions.CanvasLmsException; import de.m0ep.canvas.exceptions.NotFoundException; import de.m0ep.canvas.model.Entry; /** * Implementation of an Entries endpoint * * @author Florian Müller * */ public class Entries extends AbstractEndpoint { private static final Logger LOG = LoggerFactory.getLogger( Entries.class ); private static final String PARAM_ENTRY_ID = "entryId"; private static final String PATH = "/entries"; private static final String PATH_REPLIES = "/entries/{entryId}/replies"; private static final String PATH_ENTRY_LIST = "/entry_list?ids[]={entryId}"; public class List extends CanvasLmsRequest<Entry> { public List() { super( Entries.this.getClient(), HttpGet.class, getEndpointPath(), Entry.class ); } @Override public Entry execute() throws CanvasLmsException { throw new UnsupportedOperationException( "execute() is not supported by List" ); } } public class Get extends CanvasLmsRequest<Entry> { long entryId; public Get( long entryId ) { super( Entries.this.getClient(), HttpGet.class, UriTemplate.fromTemplate( getParentEndpointPath() + PATH_ENTRY_LIST ) .set( PARAM_ENTRY_ID, entryId ) .expand(), Entry.class ); this.entryId = entryId; } @Override public Entry execute() throws CanvasLmsException { Pagination<Entry> pagination = super.executePagination(); for ( java.util.List<Entry> list : pagination ) { for ( Entry entry : list ) { return entry; } } throw new NotFoundException( "No entry found with id= " + entryId ); } @Override public Pagination<Entry> executePagination() throws CanvasLmsException { throw new UnsupportedOperationException( "executePagination() is not supported by Post" ); } } public class Post extends CanvasLmsRequest<Entry> { public Post( final String message ) { super( Entries.this.getClient(), HttpPost.class, getEndpointPath(), Entry.class ); setContent( new UrlEncodedFormEntity( Arrays.asList( new BasicNameValuePair( "message", message ) ), Charset.defaultCharset() ) ); } @Override public Pagination<Entry> executePagination() throws CanvasLmsException { throw new UnsupportedOperationException( "executePagination() is not supported by Post" ); } } public class ListReplies extends CanvasLmsRequest<Entry> { public ListReplies( final long entryId ) { super( Entries.this.getClient(), HttpGet.class, UriTemplate.fromTemplate( getParentEndpointPath() + PATH_REPLIES ) .set( PARAM_ENTRY_ID, entryId ).expand(), Entry.class ); } @Override public Entry execute() throws CanvasLmsException { throw new UnsupportedOperationException( "execute() is not supported by List" ); } } public class PostReply extends CanvasLmsRequest<Entry> { public PostReply( final String message, final long entryId ) { super( Entries.this.getClient(), HttpPost.class, UriTemplate.fromTemplate( getParentEndpointPath() + PATH_REPLIES ) .set( PARAM_ENTRY_ID, entryId ).expand(), Entry.class ); setContent( new UrlEncodedFormEntity( Arrays.asList( new BasicNameValuePair( "message", message ) ), Charset.defaultCharset() ) ); } @Override public Pagination<Entry> executePagination() throws CanvasLmsException { throw new UnsupportedOperationException( "executePagination() is not supported by Post" ); } } public Entries( final CanvasLmsClient client, final String parentEndpointPath ) { setClient( client ); setParentEndpointPath( parentEndpointPath ); setEndpointPath( getParentEndpointPath() + PATH ); LOG.info( "Create Entries for '{}' endpoint.", getParentEndpointPath() ); } /** * Create a request to list all entries. * * @return A {@link List} request. */ public List list() { List request = new List(); initializeRequest( request ); return request; } /** * Create a request to get a single entry. * * @param entryId * Entry id. * @return A {@link Get} request. */ public Get get( final long entryId ) { Get request = new Get( entryId ); initializeRequest( request ); return request; } /** * Request to post a message. * * @param message * The message content. * @return A {@link Post} request. */ public Post post( final String message ) { Post request = new Post( message ); initializeRequest( request ); return request; } /** * Creates a request to list all replies of an entry. * * @param entryId * The entry id. * @return A {@link ListReplies} request. */ public ListReplies listReplies( final long entryId ) { ListReplies request = new ListReplies( entryId ); initializeRequest( request ); return request; } /** * Creates a request to post a reply to an entry. * * @param message * Message content * @param entryId * The id of the entry. * @return A {@link PostReply} request. */ public PostReply postReply( final String message, final long entryId ) { PostReply request = new PostReply( message, entryId ); initializeRequest( request ); return request; } }
9239cca360085a54c223dde8fb2904eb19df4ddb
1,529
java
Java
src/main/java/net/mybrainlab/camp/common/Utils.java
jyogu-i/spring-boot-rest-example
c428786afc100906a7a193318868c6b4d3f703c1
[ "MIT" ]
null
null
null
src/main/java/net/mybrainlab/camp/common/Utils.java
jyogu-i/spring-boot-rest-example
c428786afc100906a7a193318868c6b4d3f703c1
[ "MIT" ]
null
null
null
src/main/java/net/mybrainlab/camp/common/Utils.java
jyogu-i/spring-boot-rest-example
c428786afc100906a7a193318868c6b4d3f703c1
[ "MIT" ]
null
null
null
30.58
127
0.57554
998,960
package net.mybrainlab.camp.common; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Date; import java.util.function.Supplier; import static java.util.Objects.*; /** * ユーティリティクラス. */ public class Utils { /** * 文字列前後の半角スペース, 全角スペース, {@value &nbsp;}を除去する. * @param src 対象文字列 * @return {@link String} */ public static String trim(final String src) { if (isNull(src) || src.length() == 0) return src; int st = 0; int len = src.length(); char[] val = src.toCharArray(); while ((st < len) && ((val[st] <= '\u0020') || (val[st] == '\u00A0') || (val[st] == '\u3000'))) { st++; } while ((st < len) && ((val[len - 1] <= '\u0020') || (val[len - 1] == '\u00A0') || (val[len - 1] == '\u3000'))) { len--; } return ((st > 0) || (len < src.length())) ? src.substring(st, len) : src; }; private static Supplier<ZoneOffset> systemZoneOffset = () -> (ZoneOffset) ZoneOffset.systemDefault(); /** * 指定時間後の{@linkplain java.util.Date 日時}を取得する。 * @param offsetHours * @return {@linkplain java.util.Date 日時} */ public static Date getDateOffsetHours(int offsetHours) { LocalDateTime ldt = LocalDateTime.now(); Instant instant = ldt.toInstant(systemZoneOffset.get()); return offsetHours == 0 ? Date.from(instant) : Date.from(ldt.plusHours(offsetHours).toInstant(systemZoneOffset.get())); } }