hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
8eaa7f415e7f0a068d93924aeb946073e4a0f311 | 2,779 | class Test {
static interface I {
void m();
}
I i1 = ()-> { continue <error descr="Undefined label: 'l'">l</error>; };
I i2 = ()-> { break <error descr="Undefined label: 'l'">l</error>; };
I i3 = ()-> {
I i_i1 = ()-> { continue <error descr="Undefined label: 'l'">l</error>; };
I i_i2= ()-> { break <error descr="Undefined label: 'l'">l</error>; };
foo:
while (true) {
if (false) {
break;
}
if (true) {
break <error descr="Undefined label: 'l'">l</error>;
} else {
continue foo;
}
if (false) {
break <error descr="Undefined label: 'l1'">l1</error>;
}
}
};
I i4 = ()-> { <error descr="Continue outside of loop">continue;</error> };
I i5 = ()-> { <error descr="Break outside switch or loop">break;</error> };
{
l:
while (true) {
I i1 = ()-> { continue <error descr="Undefined label: 'l'">l</error>; };
I i2 = ()-> { break <error descr="Undefined label: 'l'">l</error>; };
I i3 = ()-> {
I i_i1 = ()-> { continue <error descr="Undefined label: 'l'">l</error>; };
I i_i2= ()-> { break <error descr="Undefined label: 'l'">l</error>; };
foo:
while (true) {
if (false) {
break;
}
if (true) {
break <error descr="Undefined label: 'l'">l</error>;
} else {
continue foo;
}
if (false) {
break <error descr="Undefined label: 'l1'">l1</error>;
}
}
};
}
while (true) {
I i1 = ()-> { continue <error descr="Undefined label: 'l'">l</error>; };
I i2 = ()-> { break <error descr="Undefined label: 'l'">l</error>; };
I i3 = ()-> {
I i_i1 = ()-> { continue <error descr="Undefined label: 'l'">l</error>; };
I i_i2= ()-> { break <error descr="Undefined label: 'l'">l</error>; };
foo:
while (true) {
if (false) {
break;
}
if (true) {
break <error descr="Undefined label: 'l'">l</error>;
} else {
continue foo;
}
if (false) {
break <error descr="Undefined label: 'l1'">l1</error>;
}
}
};
}
}
} | 35.177215 | 90 | 0.369917 |
ad96017cdd52e9098d83203ad6201576504dd565 | 9,782 | /*
* 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 co.edu.uniandes.csw.requirement.resources;
import co.edu.uniandes.csw.requirement.dtos.ObjetivoDTO;
import co.edu.uniandes.csw.requirement.dtos.ObjetivoDetailDTO;
import co.edu.uniandes.csw.requirement.ejb.ObjetivoLogic;
import co.edu.uniandes.csw.requirement.entities.ObjetivoEntity;
import co.edu.uniandes.csw.requirement.exceptions.BusinessLogicException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.ws.rs.*;
/**
* Clase que representa el Recurso para obtener DTOS de tipo Objetivo
*
* @author David Manosalva
*/
@Produces("application/json")
@Consumes("application/json")
public class ObjetivoResource {
/**
* Logger de la clase
*/
private static final Logger LOGGER = Logger.getLogger(ObjetivoResource.class.getName());
/**
* Logica de la clase
*/
@Inject
private ObjetivoLogic objetivoLogic;
/**
* Crea un nuevo Objetivo con la informacion que se recibe en el cuerpo de
* la petición y se regresa un objeto identico con un id auto-generado por
* la base de datos.
*
* @param proyectosId El ID del proyecto del cual se le agrega la objetivo
* @param objetivo{@link ObjetivoDTO} - La objetivo que se desea guardar.
* @return JSON {@link ObjetivoDTO} - El objetivo guardado con el atributo
* id autogenerado.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera cuando ya existe el Objetivo.
*/
@POST
public ObjetivoDetailDTO createObjetivo(@PathParam("proyectosId") Long proyectosId, ObjetivoDTO objetivo) throws BusinessLogicException {
LOGGER.log(Level.INFO, "ObjetivoResource createObjetivo: input: {0}", objetivo);
ObjetivoDetailDTO objetivoDTO = new ObjetivoDetailDTO(objetivoLogic.createObjetivo(proyectosId, objetivo.toEntity()));
LOGGER.log(Level.INFO, "ObjetivoResource createObjetivo: output: {0}", objetivoDTO);
return objetivoDTO;
}
/**
* Metodo que retorna todoslos objetivos en objetos DTO
*
* @param proyectosId el id del proyecto papá.
* @return Lista con los ObjetivosDetailDTO
*/
@GET
public List<ObjetivoDetailDTO> getObjetivos(@PathParam("proyectosId") Long proyectosId) {
LOGGER.info("ObjetivoResource getObjetivos: input: void");
List<ObjetivoDetailDTO> listaObjetivos = listEntity2DTO(objetivoLogic.getObjetivos(proyectosId));
LOGGER.log(Level.INFO, "ObjetivoResource getObjetivos: output: {0}", listaObjetivos);
return listaObjetivos;
}
/**
* Metodo que retorna el objetivoDTO dado por parametro
*
* @param proyectosId el id del proyecto padre.
* @param objetivosId Id del objetivo a consultar
* @return Objetivo consultado
*/
@GET
@Path("{objetivosId: \\d+}")
public ObjetivoDetailDTO getObjetivo(@PathParam("proyectosId") Long proyectosId, @PathParam("objetivosId") Long objetivosId) {
LOGGER.log(Level.INFO, "ObjetivoResource getObjetivo: input: {0}", objetivosId);
ObjetivoEntity objetivoEntity = objetivoLogic.getObjetivo(proyectosId, objetivosId);
if (objetivoEntity == null) {
throw new WebApplicationException("El recurso /proyectos" + proyectosId + "/objetivos/" + objetivosId + " no existe.", 404);
}
ObjetivoDetailDTO detailDTO = new ObjetivoDetailDTO(objetivoEntity);
LOGGER.log(Level.INFO, "ObjetivoResource getObjetivo: output: {0}", detailDTO);
return detailDTO;
}
/**
* Actualiza una reseña con la informacion que se recibe en el cuerpo de la
* petición y se regresa el objeto actualizado.
*
* @param proyectosId El ID del proyecto del cual se guarda el objetivo
* @param objetivosId El ID del objetivo que se va a actualizar
* @param objetivo {@link ObjetivoDTO} - el objetivo que se va a guardar.
* @return JSON {@link ObjetivoDTO} - El objetivo actualizado.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera cuando ya existe el objetivo.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra el objetivo.
*/
//**
// WARNING! PREGUNTAR SI ES DETAIL O NO
//
@PUT
@Path("{objetivosId: \\d+}")
public ObjetivoDetailDTO updateObjetivo(@PathParam("proyectosId") Long proyectosId, @PathParam("objetivosId") Long objetivosId, ObjetivoDetailDTO objetivo) throws BusinessLogicException {
LOGGER.log(Level.INFO, "ObjetivoResource updateObjetivo: input: proyectosId: {0} , objetivosId: {1} , objetivo: {2}", new Object[]{proyectosId, objetivosId, objetivo});
ObjetivoEntity oe = objetivoLogic.getObjetivo(proyectosId, objetivosId);
if (oe == null) {
throw new WebApplicationException("El recurso proyectos/" + proyectosId + "/objetivos/" + objetivosId + " no existe.", 404);
}
ObjetivoDetailDTO current = new ObjetivoDetailDTO(oe);
objetivo.setRequisitos(current.getRequisitos());
objetivo.setAprobaciones(current.getAprobaciones());
objetivo.setAutor(current.getAutor());
objetivo.setFuentes(current.getFuentes());
objetivo.setId(objetivosId);
if (objetivo.getComentarios() == null || objetivo.getComentarios().equals(""))
{
objetivo.setComentarios(current.getComentarios());
}
if (objetivo.getImportancia() == null)
{
objetivo.setImportancia(current.getImportancia());
}
if (objetivo.getDescripcion() == null || objetivo.getDescripcion().equals(""))
{
objetivo.setDescripcion(current.getDescripcion());
}
if (objetivo.getEstabilidad() == null)
{
objetivo.setEstabilidad(current.getEstabilidad());
}
ObjetivoDetailDTO detailDTO = new ObjetivoDetailDTO(objetivoLogic.updateObjetivo(proyectosId, objetivo.toEntity()));
LOGGER.log(Level.INFO, "ObjetivoResource updateObjetivo: output: {0}", detailDTO);
return detailDTO;
}
/**
* Borra la reseña con el id asociado recibido en la URL.
*
* @param booksId El ID del libro del cual se va a eliminar la reseña.
* @param reviewsId El ID de la reseña que se va a eliminar.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera cuando no se puede eliminar la reseña.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra la reseña.
*/
@DELETE
@Path("{objetivosId: \\d+}")
public void deleteObjetivo(@PathParam("proyectosId") Long proyectosId, @PathParam("objetivosId") Long objetivosId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "ObjetivoResource deleteObjetivo: input: proyectosId: {0} , objetivosId: {1} , ", new Object[]{proyectosId, objetivosId});
ObjetivoEntity entity = objetivoLogic.getObjetivo(proyectosId, objetivosId);
if (entity == null) {
throw new WebApplicationException("El recurso /proyectos/" + proyectosId + "/objetivos/" + objetivosId + " no existe.", 404);
}
if (!entity.getRequisitos().isEmpty())
{
throw new BusinessLogicException("No se puede borrar el objetivo con id " + objetivosId + " pues tiene requisitos dependientes ");
}
objetivoLogic.deleteObjetivo(proyectosId, objetivosId);
LOGGER.info("ObjetivoResource deleteObjetivo: output: void");
}
@Path("{objetivosId: \\d+}/requisitos")
public Class<RequisitoResource> getRequisitoResource(@PathParam("proyectosId") Long proyectosId, @PathParam("objetivosId") Long objetivosId) {
if (objetivoLogic.getObjetivo(proyectosId, objetivosId) == null) {
throw new WebApplicationException("El recurso /objetivos/" + objetivosId + " no existe.", 404);
}
return RequisitoResource.class;
}
@Path("{objetivosId: \\d+}/cambios")
public Class<CambioResource> getCambiosResource(@PathParam("proyectosId") Long proyectosId, @PathParam("objetivosId") Long objetivosId) {
if (objetivoLogic.getObjetivo(proyectosId, objetivosId) == null) {
throw new WebApplicationException("El recurso /objetivos/" + objetivosId + " no existe.", 404);
}
return CambioResource.class;
}
/**
* Lista que devuelve una lista de objetos de tipo DTO de una lista de
* ObjetivoEntity
*
* @param entityList Lista de ObjetivoEmntity a cambiar a DTo
* @return Lista cambiada de DTO
*/
private List<ObjetivoDetailDTO> listEntity2DTO(List<ObjetivoEntity> entityList) {
List<ObjetivoDetailDTO> list = new ArrayList<>();
for (ObjetivoEntity entity : entityList) {
list.add(new ObjetivoDetailDTO(entity));
}
return list;
}
@Path("{objetivosId: \\d+}/aprobaciones")
public Class<AprobacionResource> getAprobacionResource(@PathParam("proyectosId") Long proyectosId, @PathParam("objetivosId") Long objetivosId) {
if (objetivoLogic.getObjetivo(proyectosId, objetivosId) == null) {
throw new WebApplicationException("El recurso /objetivos/" + objetivosId + " no existe.", 404);
}
return AprobacionResource.class;
}
}
| 45.078341 | 191 | 0.685238 |
f0426dc8d15aa7992420c6da34defa68d4cc8dcc | 2,247 | package games.stendhal.client.gui.j2d.entity.helpers;
import games.stendhal.client.sprite.Sprite;
import temp.java.awt.Graphics;
/**
* Helper class for drawing sprites with a certain alignment in a certain area
*
* @author madmetzger
*/
public class DrawingHelper {
/**
* Align a sprite in a defined area, which is defined by upper left corner (x,y)
* and width to the right and height downwards
*
* @param g2d
* @param sprite the sprite to draw
* @param horizontalAlign (left, center, right)
* @param verticalAlign (top, middle, bottom)
* @param x
* @param y
* @param width
* @param height
*/
public static void drawAlignedSprite(Graphics g2d, Sprite sprite,
HorizontalAlignment horizontalAlign, VerticalAlignment verticalAlign,
int x, int y, int width, int height) {
/*
* NOTE: This has be calibrated to fit the size of an entity slot
* visual.
*/
int qx = alignHorizontal(sprite, horizontalAlign, x, width);
int qy = alignVertical(sprite, verticalAlign, y, height);
sprite.draw(g2d, qx, qy);
}
private static int alignVertical(Sprite sprite,
VerticalAlignment verticalAlign, int y, int height) {
int qy = y;
switch (verticalAlign) {
case TOP:
qy = y - 5;
break;
case MIDDLE:
qy = y + (height - sprite.getHeight()) / 2;
break;
case BOTTOM:
qy = y + height + 5 - sprite.getHeight();
break;
}
return qy;
}
private static int alignHorizontal(Sprite sprite, HorizontalAlignment a,
int x, int width) {
int qx = x;
switch (a) {
case RIGHT:
qx = x + width + 5 - sprite.getWidth();
break;
case CENTER:
qx = x + (width - sprite.getWidth()) / 2;
break;
case LEFT:
qx = x + 5;
break;
}
return qx;
}
}
| 30.364865 | 110 | 0.511348 |
49d4cd16f9f6b3058cd114226530d1eba5e47c4e | 136 | package org.ihtsdo.snowowl.authoring.single.api.review.pojo;
public enum BranchState {
UP_TO_DATE, FORWARD, BEHIND, DIVERGED, STALE
}
| 22.666667 | 60 | 0.794118 |
6cec922a74e02ee2c03e8f5f3d7151f5bad320d6 | 14,828 | package org.firstinspires.ftc.teamcode;
/*
Made By Cameron Doughty 1/15/2018
*/
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cColorSensor;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorController;
import com.qualcomm.robotcore.hardware.DcMotorControllerEx;
import com.qualcomm.robotcore.hardware.GyroSensor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import com.vuforia.CameraDevice;
import java.util.Timer;
import org.firstinspires.ftc.robotcontroller.external.samples.ConceptVuforiaNavigation;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark;
import org.firstinspires.ftc.robotcore.external.navigation.VuMarkInstanceId;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
@com.qualcomm.robotcore.eventloop.opmode.Autonomous(name="Red_Autonomous_Left")
public class Red_Autonomous_Left extends LinearOpMode { //Linear op mode is being used so the program does not get stuck in loop()
private ElapsedTime runtime = new ElapsedTime();
private ElapsedTime timer = new ElapsedTime();
public DcMotor FleftDrive = null;
public DcMotor FrightDrive = null;
public DcMotor BleftDrive = null;
public DcMotor BrightDrive = null;
private Servo RelicServo = null;
private Servo Blockservo_left = null;
private Servo Blockservo_right = null;
public Servo Color_sensor_servo = null;
ModernRoboticsI2cColorSensor Color_sensor = null;
private DcMotor RelicMotor = null;
private DcMotor BlockMotor = null;
public double speed = .25;
int zAccumulated; //Total rotation left/right
int target = 0; //Desired angle to turn to
GyroSensor sensorGyro; //General Gyro Sensor allows us to point to the sensor in the configuration file.
ModernRoboticsI2cGyro mrGyro; //ModernRoboticsI2cGyro allows us to .getIntegratedZValue()
boolean random = true;
boolean Relicarmon;
void stopDrive() {
FleftDrive.setPower(0);
FrightDrive.setPower(0);
BleftDrive.setPower(0);
BrightDrive.setPower(0);
}
void forward(long time) {
FleftDrive.setPower(-speed);
FrightDrive.setPower(-speed);
BleftDrive.setPower(-speed);
BrightDrive.setPower(-speed);
sleep(time);
}
void reverse(long time) {
FleftDrive.setPower(speed);
FrightDrive.setPower(speed);
BleftDrive.setPower(speed);
BrightDrive.setPower(speed);
sleep(time);
}
void strafeleft(long time) {
FleftDrive.setPower(speed);
FrightDrive.setPower(-speed);
BleftDrive.setPower(-speed);
BrightDrive.setPower(speed);
sleep(time);
}
void straferight(long time) {
FleftDrive.setPower(-speed);
FrightDrive.setPower(speed);
BleftDrive.setPower(speed);
BrightDrive.setPower(-speed);
sleep(time);
}
void TurnLeft(long time) {
FleftDrive.setPower(speed);
FrightDrive.setPower(-speed);
BleftDrive.setPower(speed);
BrightDrive.setPower(-speed);
sleep(time);
}
void TurnRight(long time) {
FleftDrive.setPower(-speed);
FrightDrive.setPower(speed);
BleftDrive.setPower(-speed);
BrightDrive.setPower(speed);
sleep(time);
}
void Block_motor(long time) {
BlockMotor.setPower(1);
sleep(time);
}
void ServoTurn(long time) {
Blockservo_left.setPosition(0);
Blockservo_right.setPosition(1);
sleep(time);
}
@Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
FleftDrive = hardwareMap.get(DcMotor.class, "FleftDrive");
FrightDrive = hardwareMap.get(DcMotor.class, "FrightDrive");
BleftDrive = hardwareMap.get(DcMotor.class, "BleftDrive");
BrightDrive = hardwareMap.get(DcMotor.class, "BrightDrive");
RelicServo = hardwareMap.get(Servo.class, "RelicServo");
Blockservo_left = hardwareMap.get(Servo.class, "Blockservo_left");
Blockservo_right = hardwareMap.get(Servo.class, "Blockservo_right");
Color_sensor_servo = hardwareMap.get(Servo.class, "Color_sensor_servo");
Color_sensor = (ModernRoboticsI2cColorSensor) hardwareMap.get(ColorSensor.class, "Color_sensor");
BlockMotor = hardwareMap.get(DcMotor.class, "Block_motor");
RelicMotor = hardwareMap.get(DcMotor.class, "RelicMotor");
Color_sensor.enableLight(true);
FrightDrive.setDirection(DcMotor.Direction.REVERSE);
BrightDrive.setDirection(DcMotor.Direction.REVERSE);
sensorGyro = hardwareMap.gyroSensor.get("gyro"); //Point to the gyro in the configuration file
mrGyro = (ModernRoboticsI2cGyro) sensorGyro; //ModernRoboticsI2cGyro allows us to .getIntegratedZValue()
mrGyro.calibrate(); //Calibrate the sensor so it knows where 0 is and what still is. DO NOT MOVE SENSOR WHILE BLUE LIGHT IS SOLID
while (!isStopRequested() && mrGyro.isCalibrating()) {
telemetry.addData("calibrating", "%s", Math.round(timer.seconds()) % 2 == 0 ? "|.." : "..|");
telemetry.update();
sleep(50);
}
telemetry.log().clear();
telemetry.log().add("Gyro Calibrated. Press Start.");
telemetry.clear();
telemetry.update();
waitForStart();
runtime.reset();
Color_sensor.red(); // Red channel value
Color_sensor.green(); // Green channel value
Color_sensor.blue(); // Blue channel value
Color_sensor.alpha(); // Total luminosity
Color_sensor.argb(); // Combined color value
Color_sensor.enableLight(true);
Blockservo_left.setPosition(.5);
Blockservo_right.setPosition(.5);
RelicServo.setPosition(0.5);
//PictoGraph(2);
TestGyro(2);
}
public void PictoGraph(double holdTime) {
ElapsedTime holdTimer = new ElapsedTime();
holdTimer.reset();
Color_sensor_servo.setPosition(.83);
VuforiaTest.type type = new VuforiaTest().vuforiarun(hardwareMap);
if (type == VuforiaTest.type.LEFT) {
telemetry.addData("Type", "Left");
Armdown(2);
Jewel(0.5);
LiftDown(2);
sleep(300);
LiftUp(2);
sleep(300);
//Glyph(2, 1);
}
if (type == VuforiaTest.type.CENTER) {
telemetry.addData("Type", "Center");
Armdown(2);
Jewel(0.5);
LiftDown(2);
sleep(300);
LiftUp(2);
sleep(300);
//Glyph(2, 2);
}
if (type == VuforiaTest.type.RIGHT) {
telemetry.addData("Type", "Right");
Armdown(2);
Jewel(0.5);
LiftDown(2);
sleep(300);
LiftUp(2);
sleep(300);
//Glyph(2, 3);
}
if (type == VuforiaTest.type.ERROR) {
telemetry.addData("Type", "Error");
Armdown(2);
Jewel(0.5);
LiftDown(2);
sleep(300);
LiftUp(2);
sleep(300);
//Glyph(2, 2);
}
}
// }
public void TestGyro(int sleepTime) {
Color_sensor_servo.setPosition(0.83);
mrGyro.resetZAxisIntegrator();
target = target - 20;
turnAbsolute(target);
sleep(1000);
//mrGyro.resetZAxisIntegrator();
target = target + 20;
turnAbsolute(target);
sleep(1000);
Forward(500, .20);
sleep(1000);
//mrGyro.resetZAxisIntegrator();
target = target - 85;
turnAbsolute(target);
}
public void LiftDown(int sleepTime) {
Color_sensor_servo.setPosition(.30);
long time = System.currentTimeMillis();
while (System.currentTimeMillis() < time + 800) {
BlockMotor.setPower(-0.4);
}
BlockMotor.setPower(0.0);
/*BlockMotor.setPower(-0.4);
sleep(sleepTime);
BlockMotor.setPower(0.0);
*/
}
public void LiftUp(int sleepTime) {
long time = System.currentTimeMillis();
while (System.currentTimeMillis() < time + 1000) {
BlockMotor.setPower(0.4);
}
BlockMotor.setPower(0.0);
/*BlockMotor.setPower(0.4);
sleep(sleepTime);
BlockMotor.setPower(0.0);
*/
}
public void Forward(int sleepTime, double Speed) {
long time = System.currentTimeMillis();
while (System.currentTimeMillis() < time + sleepTime) {
FleftDrive.setPower(-Speed);
FrightDrive.setPower(-Speed);
BleftDrive.setPower(-Speed);
BrightDrive.setPower(-Speed);
}
FleftDrive.setPower(0);
FrightDrive.setPower(0);
BleftDrive.setPower(0);
BrightDrive.setPower(0);
}
//This function turns a number of degrees compared to where the robot is. Positive numbers trn left.
public void turn(int target) throws InterruptedException {
turnAbsolute(target + mrGyro.getIntegratedZValue());
}
//This function turns a number of degrees compared to where the robot was when the program started. Positive numbers trn left.
public void turnAbsolute(int target) {
zAccumulated = mrGyro.getIntegratedZValue(); //Set variables to gyro readings
double turnSpeed = 0.25;
while (Math.abs(zAccumulated - target) > 1.5 /* Was 3*/ && opModeIsActive()) { //Continue while the robot direction is further than three degrees from the target
telemetry.addData("Target", target);
if (zAccumulated < target) { //if gyro is positive, we will turn right
FleftDrive.setPower(turnSpeed);
BleftDrive.setPower(turnSpeed);
FrightDrive.setPower(-turnSpeed);
BrightDrive.setPower(-turnSpeed);
}
if (zAccumulated > target) { //if gyro is positive, we will turn left
FleftDrive.setPower(-turnSpeed);
BleftDrive.setPower(-turnSpeed);
FrightDrive.setPower(turnSpeed);
BrightDrive.setPower(turnSpeed);
}
zAccumulated = mrGyro.getIntegratedZValue(); //Set variables to gyro readings
telemetry.addData("accu", String.format("%03d", zAccumulated));
telemetry.update();
}
FleftDrive.setPower(0);
BleftDrive.setPower(0);
FrightDrive.setPower(0);
BrightDrive.setPower(0);
}
public void Jewel(double holdTime) {
ElapsedTime holdTimer = new ElapsedTime();
holdTimer.reset();
telemetry.update();
while (opModeIsActive() && holdTimer.time() < holdTime) {
telemetry.update();
if (Color_sensor.blue() >= 0.3) {
target = target + 20;
turnAbsolute(target);
sleep(500);
Color_sensor_servo.setPosition(0.83);
//mrGyro.resetZAxisIntegrator();
target = target - 20;
turnAbsolute(target);
Forward(1500, .20);
} else if (Color_sensor.red() >= 0.3) {
target = target - 20;
turnAbsolute(target);
sleep(500);
Color_sensor_servo.setPosition(0.83);
//mrGyro.resetZAxisIntegrator();
target = target + 20;
turnAbsolute(target);
Forward(1500, .20);
}
}
}
public void Armdown(double holdTime) {
ElapsedTime holdTimer = new ElapsedTime();
holdTimer.reset();
while (opModeIsActive() && holdTimer.time() < holdTime) {
Color_sensor_servo.setPosition(0.05);
}
}
public void Glyph(double holdTime, int Direction) {
ElapsedTime holdTimer = new ElapsedTime();
holdTimer.reset();
Color_sensor_servo.setPosition(.83);
while (opModeIsActive() && holdTimer.time() < holdTime) {
if (Direction == 1) {
forward(1000);
//mrGyro.resetZAxisIntegrator();
sleep(300);
target = target - 80;
turnAbsolute(target);
strafeleft(1500);
sleep(500);
ServoTurn(1500);
forward(300);
}
if (Direction == 2) {
forward(1000);
//mrGyro.resetZAxisIntegrator();
sleep(300);
target = target - 80;
turnAbsolute(target);
strafeleft(1000);
sleep(500);
ServoTurn(1500);
forward(300);
}
if (Direction == 3) {
forward(1000);
//mrGyro.resetZAxisIntegrator();
sleep(300);
target = target - 80;
turnAbsolute(target);
strafeleft(500);
sleep(500);
ServoTurn(1500);
forward(300);
}
}
}
} | 36.70297 | 170 | 0.606353 |
d03b854d3b2c3e05deb1231f5ffd42f359d82475 | 271 | package com.drakklord.gradle.metric.tooling.checkstyle;
import org.gradle.api.plugins.quality.Checkstyle;
import java.util.List;
/**
* Created by DrakkLord on 2016. 11. 01..
*/
public interface CheckstyleMetricModel {
List<CheckstyleTaskContainer> getTasks();
}
| 20.846154 | 55 | 0.763838 |
64069f2b2211378afc0a378726fdb0ffbcd3bd5d | 664 | package uk.co.idv.method.entities.verification;
import lombok.Builder;
import lombok.Data;
import uk.co.idv.method.entities.result.Result;
@Builder
@Data
public class CompleteVerificationResponse {
private final boolean sequenceCompletedByVerification;
private final boolean methodCompletedByVerification;
private final Verification verification;
public Result getResult() {
return verification.toResult();
}
public boolean isSequenceCompletedByVerification() {
return sequenceCompletedByVerification;
}
public boolean isMethodCompletedByVerification() {
return methodCompletedByVerification;
}
}
| 23.714286 | 58 | 0.763554 |
cde8c960f321fd1870b9d06a7cff8c0da90ef14a | 3,947 | package edu.ohsu.sonmezsysbio.cloudbreak;
import org.apache.commons.math3.distribution.LogNormalDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.log4j.Logger;
/**
* Created by IntelliJ IDEA.
* User: cwhelan
* Date: 3/12/12
* Time: 3:11 PM
*/
/**
* Functions to compute a simple deletion likelihood score given an insert size and pMapping correct.
* Not currently used in the GMM fit code, this is here for legacy reasons.
*/
public class ProbabilisticPairedAlignmentScorer extends PairedAlignmentScorer {
private static org.apache.log4j.Logger logger = Logger.getLogger(ProbabilisticPairedAlignmentScorer.class);
@Override
public double computeDeletionScore(int insertSize, Double targetIsize, Double targetIsizeSD, Double pMappingCorrect) {
// calculate:
//
// p(Del | IS) = p( IS | Del) p(Del) / p (IS)
//
// p(NoDel | IS) = p( IS | NoDel) p(NoDel) / p (IS)
//
// ((p(IS | Del) p (Del)) / (p(IS | NoDel) p(NoDel))) (((( * p (IS | AQ) ???? )))
//
// log ( ((p(IS | Del) p (Del)) / (p(IS | NoDel) p(NoDel))) * p (IS | AQ) )
// log ((p(IS | Del) p (Del)) - log (p(IS | NoDel) p(NoDel)) + log ( p (IS | AQ))
//
// p (Del) = # of deletions per individual / genome size = 2432 / 3137161264
// p (IS | Del) = density at IS in gamma(0.2, 40000)
// p (noDel) = 1 - p(Del)
// p (IS | NoDel) = density at IS in N(isize, isizeSD)
//GammaDistribution gammaDistribution = new GammaDistribution(0.2, 40000);
LogNormalDistribution logNormalDistribution = new LogNormalDistribution(6, 0.6);
NormalDistribution normalDistribution = new NormalDistribution(targetIsize, targetIsizeSD);
double pDeletion = Math.log(2432.0 / 2700000000.0);
double pNoDeletion = Math.log(1 - 2432.0 / 2700000000.0);
double pISgivenDeletion = Math.log(logNormalDistribution.density(insertSize)); // todo add fragment size
double pISgivenNoDeletion = Math.log(normalDistribution.density(insertSize));
// todo
// need to cap p(IS | NoDel) because it goes to infinity as the insert size gets large
if (insertSize > targetIsize + 30 * targetIsizeSD) {
pISgivenNoDeletion = Math.log(normalDistribution.density(targetIsize + 30 * targetIsizeSD));
}
double pMappingIncorrect = Math.log(1 - Math.exp(pMappingCorrect));
double normalization = logAdd(pDeletion + pISgivenDeletion, pNoDeletion + pISgivenNoDeletion);
double pDeletionGivenIS = pDeletion + pISgivenDeletion - normalization;
double pNoDeletionGivenIS = pNoDeletion + pISgivenNoDeletion - normalization;
double pDeletionNew = logAdd(pDeletionGivenIS + pMappingCorrect, pDeletion + pMappingIncorrect);
double pNoDeletionNew = logAdd(pNoDeletionGivenIS + pMappingCorrect, pNoDeletion + pMappingIncorrect);
double likelihoodRatio = pDeletionNew
- pNoDeletionNew;
return likelihoodRatio;
}
// from https://facwiki.cs.byu.edu/nlp/index.php/Log_Domain_Computations
public static double logAdd(double logX, double logY) {
// 1. make X the max
if (logY > logX) {
double temp = logX;
logX = logY;
logY = temp;
}
// 2. now X is bigger
if (logX == Double.NEGATIVE_INFINITY) {
return logX;
}
// 3. how far "down" (think decibels) is logY from logX?
// if it's really small (20 orders of magnitude smaller), then ignore
double negDiff = logY - logX;
if (negDiff < -20) {
return logX;
}
// 4. otherwise use some nice algebra to stay in the log domain
// (except for negDiff)
return logX + java.lang.Math.log(1.0 + java.lang.Math.exp(negDiff));
}
}
| 42.902174 | 122 | 0.631872 |
c563bde7965c71b699e76c53fccb820dedc2c32a | 2,093 |
package com.example.lotrcharacters.models;
import com.example.lotrcharacters.models.Doc;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
import java.util.List;
@Parcel
public class MyPreciousResponse {
@SerializedName("docs")
@Expose
public List<Doc> docs = null;
@SerializedName("total")
@Expose
public Integer total;
@SerializedName("limit")
@Expose
public Integer limit;
@SerializedName("offset")
@Expose
public Integer offset;
@SerializedName("page")
@Expose
public Integer page;
@SerializedName("pages")
@Expose
public Integer pages;
/**
* No args constructor for use in serialization
*
*/
public MyPreciousResponse() {
}
/**
*
* @param total
* @param pages
* @param docs
* @param offset
* @param limit
* @param page
*/
public MyPreciousResponse(List<Doc> docs, Integer total, Integer limit, Integer offset, Integer page, Integer pages) {
super();
this.docs = docs;
this.total = total;
this.limit = limit;
this.offset = offset;
this.page = page;
this.pages = pages;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
}
| 19.201835 | 122 | 0.59484 |
73ef910101ee1b74e97b36288e362cfd91fbbe62 | 827 | // Joseph Igama
// Solution for problem #1773
import java.util.List;
public class Solution_1773
{
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int matches = 0;
for (int i = 0; i < items.size(); i++)
{
if(ruleKey.equals("type") && ruleValue.equals(items.get(i).get(0)))
{
matches++;
}
if(ruleKey.equals("color") && ruleValue.equals(items.get(i).get(1)))
{
matches++;
}
if(ruleKey.equals("name") && ruleValue.equals(items.get(i).get(2)))
{
matches++;
}
}
return matches;
}
}
}
| 24.323529 | 93 | 0.437727 |
dd25d4eefaa21ae5b4b39f9fbdcb7b05a151467a | 1,142 | //opgave13_1.java
//auteur : Brent Berghmans 1334252
//enigma codering uitbreiding
class taak13_1 {
public static void main (String []args) {
String givenString, encodedString = "";
int i, n;
if (args.length < 2)
return;
givenString = args[0];
n = Integer.parseInt(args[1]);
/*if (n < 0){
n += 26;
n %= 26;
}*/
for (i = 0; i < givenString.length(); i++) {
if (givenString.charAt(i) >= 'a' && givenString.charAt(i) <= 'z' || givenString.charAt(i) >= 'A' && givenString.charAt(i) <= 'Z'){
encodedString += "" + encode(givenString.charAt(i), n);
n = ((n + (encode(givenString.charAt(i), n))) % 97);
}
else {
encodedString += "" + givenString.charAt(i);
n = ((n + givenString.charAt(i)) % 97);
}
}
System.out.println(encodedString);
}
static char encode (char c, int n) {
n %= 26;
if (c >= 'A' && c <= 'Z') {
if (c + n >= 'A' && c + n <= 'Z')
c = (char)((int)c + n);
else
c = (char)( 'A' + ((c + n) - 'Z' - 1 ));
}
else {
if (c + n >= 'a' && c + n <= 'z')
c = (char)((int)c + n);
else
c = (char)( 'a' + ((c + n) - 'z' - 1));
}
return(c);
}
} | 23.791667 | 133 | 0.502627 |
76d6e50d5b8e17f21b05bf9555c54abf662036cb | 757 | package org.songzxdev.leetcode.week05;
//给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。
// 你可以返回满足此条件的任何数组作为答案。
// 示例:
// 输入:[3,1,2,4]
//输出:[2,4,3,1]
//输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
// 提示:
// 1 <= A.length <= 5000
// 0 <= A[i] <= 5000
// Related Topics 数组
public class Solution905 {
/**
* 题目:905.按奇偶排序数组
* 标签:数组 双指针
* @param A
* @return
*/
public int[] sortArrayByParity(int[] A) {
int oddSize = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] % 2 == 1) {
oddSize++;
} else if (oddSize > 0) {
int tmp = A[i - oddSize];
A[i - oddSize] = A[i];
A[i] = tmp;
}
}
return A;
}
}
| 21.628571 | 49 | 0.446499 |
8fdff6f2514ff8662add719e5663250641af0526 | 1,456 | package org.impactready.teamready;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONServices {
private static final String TAG = "JSON Services";
public static JSONArray remove(JSONArray objectsJSON, String id) {
try {
JSONArray newObjectsJSON = new JSONArray();
int len = objectsJSON.length();
for (int i = 0; i < len; i++) {
JSONObject thisObject = objectsJSON.getJSONObject(i);
if (!thisObject.getString("object_id").equals(id)) {
newObjectsJSON.put(thisObject);
}
}
return newObjectsJSON;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
return null;
}
}
public static JSONObject find(JSONArray objectsJSON, String id) {
try {
if (objectsJSON != null) {
int len = objectsJSON.length();
for (int i = 0; i < len; i++) {
JSONObject thisObject = objectsJSON.getJSONObject(i);
if (thisObject.getString("object_id").equals(id)) {
return thisObject;
}
}
}
return null;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
return null;
}
}
}
| 28.54902 | 73 | 0.522665 |
6443bb48d0f0b4a65e844dd781566fbd07038235 | 1,711 | package org.leo.server.panama.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.concurrent.Future;
public abstract class AbstractServer implements Server {
private int port;
private Channel serverChannel;
public AbstractServer(int port) {
this.port = port;
}
@Override
public void start(int maxThread) {
EventLoopGroup mainGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup(maxThread);
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(mainGroup, workGroup).
channel(NioServerSocketChannel.class).
childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
setupPipeline(ch.pipeline());
}
});
try {
serverChannel = serverBootstrap.bind(port).sync().channel();
serverChannel.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int port() {
return port;
}
@Override
public Future shutdown() {
return serverChannel.close();
}
protected abstract void setupPipeline(ChannelPipeline pipeline);
}
| 30.553571 | 86 | 0.66277 |
64449bfa45ebc7a6fc0d83ef7e163695e883c8e2 | 7,607 | package com.spike.giantdataanalysis.jena.rdf;
import java.io.InputStream;
import org.apache.jena.rdf.model.Bag;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.NodeIterator;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.SimpleSelector;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
import org.apache.jena.vocabulary.VCARD;
import com.spike.giantdataanalysis.jena.supports.JenaModels;
/**
* Jena RDF API示例
* @author zhoujiagen
*/
public class ExampleJenaRDF {
// 命名空间
public static final String NS_URI = "http://gda.jena.spike.com/";
public static void main(String[] args) {
// 创建默认模型
Model model = ModelFactory.createDefaultModel();
// 创建资源
Resource ericcartman = model.createResource(NS_URI + "EricCartman")//
.addProperty(VCARD.FN, "Eric")//
.addProperty(VCARD.N, model.createResource()//
.addProperty(VCARD.Given, "Eric")//
.addProperty(VCARD.Family, "Cartman")//
);
System.out.println("Resource: " + ericcartman);
// 遍历语句
// iter_statement(model);
// 输出模型
// output(model);
// 从文件加载模型
// load(model);
// 命名空间前缀
// namespace_prefix(model);
// 模型中导航
// navigate(model);
// 模型查询
// query(model);
// 模型的并, 交和差
// operate();
// 容器: bag(无序), alt(无序, 备选), seq(有序)
// container();
// 字面量
literal();
}
// 字面量
static void literal() {
Model model = ModelFactory.createDefaultModel();
model.createResource()//
.addProperty(RDFS.label, model.createLiteral("chat", "en"))//
.addProperty(RDFS.label, model.createLiteral("chat", "fr"))//
.addProperty(RDFS.label, model.createLiteral("<em>chat</em>", true));
model.write(System.out, "N-TRIPLE");
}
// 容器: bag(无序), alt(无序, 备选), seq(有序)
static void container() {
Model model = ModelFactory.createDefaultModel();
model
.createResource(NS_URI + "BeckySmith")
.addProperty(VCARD.FN, "Becky Smith")
.addProperty(
VCARD.N,
model.createResource().addProperty(VCARD.Given, "Becky")
.addProperty(VCARD.Family, "Smith"));
model
.createResource(NS_URI + "JohnSmith")
.addProperty(VCARD.FN, "John Smith")
.addProperty(
VCARD.N,
model.createResource().addProperty(VCARD.Given, "John")
.addProperty(VCARD.Family, "Smith"));
// 创建bag
Bag smiths = model.createBag();
StmtIterator iter = model.listStatements(new SimpleSelector(null, VCARD.FN, (RDFNode) null) {
public boolean selects(Statement s) {
return s.getString().endsWith("Smith");
}
});
while (iter.hasNext()) {
smiths.add(iter.nextStatement().getSubject());// 添加到bag中
}
model.write(System.out, "N-TRIPLE");
// 遍历bag
NodeIterator nodeIterator = smiths.iterator();
if (nodeIterator.hasNext()) {
while (nodeIterator.hasNext()) {
System.out.println(nodeIterator.next().asResource().getProperty(VCARD.FN).getLiteral());
}
} else {
System.out.println("Bag smiths is empty.");
}
}
// 模型的并, 交和差
static void operate() {
Model model1 = ModelFactory.createDefaultModel();
Model model2 = ModelFactory.createDefaultModel();
model1
.createResource(NS_URI + "JohnSmith")
//
.addProperty(
VCARD.N,
model1.createResource().addProperty(VCARD.Given, "John")
.addProperty(VCARD.Family, "Smith"))//
.addProperty(VCARD.FN, "John Smith");
model2
.createResource(NS_URI + "JohnSmith")
//
.addProperty(
VCARD.EMAIL,
model2.createResource().addProperty(RDF.type, VCARD.Other)
.addLiteral(RDF.value, "[email protected]"))//
.addProperty(VCARD.FN, "John Smith");
// 合并
Model model = model1.union(model2);
model.write(System.out, "N-TRIPLE");
}
// 模型查询
static void query(Model model) {
// 查询具有属性的主题
ResIterator iter = model.listSubjectsWithProperty(VCARD.N);
while (iter.hasNext()) {
System.out.println(iter.next());
}
// 使用选择器
SimpleSelector selector = new SimpleSelector(null, VCARD.FN, (RDFNode) null) {
@Override
public boolean selects(Statement s) {
return s.getObject().asLiteral().toString().endsWith("Eric");
}
};
StmtIterator stmtIterator = model.listStatements(selector);
while (stmtIterator.hasNext()) {
System.out.println(JenaModels.asString(stmtIterator.next()));
}
}
// 模型中导航
static void navigate(Model model) {
Resource resource = model.getResource(NS_URI + "EricCartman");
System.out.println(resource.toString());
Resource N = (Resource) resource.getProperty(VCARD.N).getObject();
System.out.println(N);
// 获取字面量
String givenName = N.getProperty(VCARD.Given).getString();
System.out.println(givenName);
// 允许重复属性
resource.addProperty(VCARD.NICKNAME, "Eric")//
.addProperty(VCARD.NICKNAME, "Cartman");
StmtIterator iter = resource.listProperties(VCARD.NICKNAME);
while (iter.hasNext()) {
System.out.println(iter.next().getObject().asLiteral());
}
}
// 遍历语句
// 语句(statement): 主谓宾(subject, predicate, object)
static void iter_statement(Model model) {
StmtIterator iter = model.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
System.out.println(JenaModels.asString(stmt));
}
}
// 输出模型, 格式:
// Predefined values are "RDF/XML", "RDF/XML-ABBREV", "N-TRIPLE" and "N3".
// The default value is represented by null is "RDF/XML".
static void output(Model model) {
model.write(System.out, "N-TRIPLE");
}
// 从文件加载模型
static void load(Model model) {
String filename = System.getProperty("user.dir") + "/data/sample.rdf";
System.out.println(filename);
InputStream is = FileManager.get().open(filename);
model.read(is, null);
model.write(System.out, "N-TRIPLE");
}
// 命名空间前缀
static void namespace_prefix(Model model) {
String nsA = "http://gda.jena.spike.com/nsA#";
String nsB = "http://gda.jena.spike.com/nsB#";
Resource root = model.createResource(nsA + "root");
Property P = model.createProperty(nsA + "P");
Property Q = model.createProperty(nsB + "Q");
Resource x = model.createResource(nsA + "x");
Resource y = model.createResource(nsA + "y");
Resource z = model.createResource(nsA + "z");
model.add(root, P, x).add(root, P, y).add(y, Q, z);
System.out.println("# ========================== no special prefixes defined");
/** xmlns:j.0="http://gda.jena.spike.com/nsA#" xmlns:j.1="http://gda.jena.spike.com/nsB#" */
model.write(System.out);
System.out.println("# ========================== nsA defined");
/** xmlns:nsA="http://gda.jena.spike.com/nsA#" xmlns:j.0="http://gda.jena.spike.com/nsB#" */
model.setNsPrefix("nsA", nsA);
model.write(System.out);
System.out.println("# ========================== nsA and cat defined");
/** xmlns:nsA="http://gda.jena.spike.com/nsA#" xmlns:cat="http://gda.jena.spike.com/nsB#" */
model.setNsPrefix("cat", nsB);
model.write(System.out);
}
}
| 30.306773 | 97 | 0.632575 |
9c0515a8d386e94bc2a7775ce6f90871fe523782 | 2,925 | package com.androidbegin.parselogintutorial;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
//import com.parse.SignUpCallback;
public class LoginSignupActivity extends Activity {
// Declare Variables
Button loginbutton;
Button signup;
Button signaturebutton;
Button rating;
String usernametxt;
String passwordtxt;
EditText password;
EditText username;
//EditText imei;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from main.xml
setContentView(R.layout.loginsignup);
// Locate EditTexts in main.xml
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
// Locate Buttons in main.xml
loginbutton = (Button) findViewById(R.id.login);
signup = (Button) findViewById(R.id.signup);
signaturebutton = (Button) findViewById(R.id.signature);
// Login Button Click Listener
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
// Sign up Button Click Listener
signup.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(LoginSignupActivity.this,
SignupActivity.class);
startActivity(intent);
finish();
}
});
//Signature Button Click Listener
/*
signaturebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(LoginSignupActivity.this,
Signature.class);
startActivity(intent);
finish();
}
});*/
}
}
| 29.545455 | 72 | 0.66906 |
ae5bde53ec28bedbae6737f577f59afb83416f35 | 3,465 | package Project;
import java.util.Scanner;
/**
*
* @author victoriaswindle
*/
public class tabulator {
private static int WingsOrder = 0;
private static int FriesOrder = 0;
private static int wingTotal = 0;
private static int friesTotal = 0;
private final static double wingPrice = .50;
private final static double friesPrice = 7.09;
private final static double tax = 0.06;
public static void main(String args[]) {
System.out.println(" Welcome To Tabulator!");
menu();
int userOp;
Scanner scanner = new Scanner(System.in);
//switch options
do {
userOp = scanner.nextInt();
switch (userOp) {
case 1:
placeOrder();
break;
case 2:
checkout();
break;
case 3:
break;
}
} while(userOp < 3);
}
//method for wings
public static void wing() {
System.out.println("Enter the nubmer of Wings to order");
Scanner scanner = new Scanner(System.in);
WingsOrder = scanner.nextInt();
System.out.println("Order Placed!");
System.out.println("To place another order press the corresponding letter in");
System.out.println(" w Wing");
System.out.println(" f Fries");
System.out.println(" d Done");
}
//method for fries
public static void fries() {
System.out.println("Enter the nubmer of orders you want of fries");
Scanner scanner = new Scanner(System.in);
FriesOrder = scanner.nextInt();
System.out.println("Order Placed!");
System.out.println("To place another order press the letter");
System.out.println(" w Wing");
System.out.println(" f Fries");
System.out.println(" d Done");
}
//display menu
public static void menu() {
System.out.println("Select a number");
System.out.println("1: Place Order");
System.out.println("2: Checkout");
System.out.println("3: Exit");
} //close menu
//method allows user to place an order
public static void placeOrder() {
System.out.println("To place order press the letter");
System.out.println(" w Wing");
System.out.println(" f Fries");
System.out.println(" d Done");
Scanner scanner = new Scanner(System.in);
int userOp = 0;
String userInput;
//switch
do {
userInput = scanner.next();
switch(userInput) {
case "w":
wing();
break;
case "f":
fries();
break;
case "d":
userOp = 1;
menu();
break;
}
} while(userOp < 1);
}
//method displays receipt
public static void checkout() {
System.out.println("Receipt");
if(WingsOrder >= 1) {
wingTotal = (int) (WingsOrder * wingPrice);
System.out.println("Wings: $" + wingTotal);
}
if(FriesOrder >= 1) {
friesTotal = (int) (FriesOrder * friesPrice);
System.out.println("Fries: $" + friesTotal);
}
//calculates everything
double grandTotal = wingTotal + friesTotal;
System.out.println("Total: $" + grandTotal);
double orderTax = tax * grandTotal;
System.out.println("Tax: $" + orderTax);
grandTotal = grandTotal + orderTax;
System.out.println("Grand Total: $" + grandTotal);
System.out.println(" d Done");
}
}
| 25.858209 | 83 | 0.572294 |
e1472f1b5a5c54e6227fa79cdd32ebb1527366e1 | 11,890 | package org.esupportail.esupsignature.web.controller.user;
import org.esupportail.esupsignature.entity.SignBook;
import org.esupportail.esupsignature.entity.User;
import org.esupportail.esupsignature.entity.Workflow;
import org.esupportail.esupsignature.entity.enums.SignType;
import org.esupportail.esupsignature.exception.EsupSignatureException;
import org.esupportail.esupsignature.exception.EsupSignatureFsException;
import org.esupportail.esupsignature.exception.EsupSignatureMailException;
import org.esupportail.esupsignature.service.*;
import org.esupportail.esupsignature.web.ws.json.JsonMessage;
import org.esupportail.esupsignature.web.ws.json.JsonWorkflowStep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
@RequestMapping("/user/wizard")
@Controller
public class WizardController {
private static final Logger logger = LoggerFactory.getLogger(WizardController.class);
@Resource
private WorkflowService workflowService;
@Resource
private SignBookService signBookService;
@Resource
private LiveWorkflowStepService liveWorkflowStepService;
@Resource
private UserService userService;
@Resource
private SignRequestService signRequestService;
@Resource
private CommentService commentService;
@GetMapping(value = "/wiz-start-by-docs", produces = "text/html")
public String wiz2(@RequestParam(value = "workflowId", required = false) Long workflowId, Model model) {
if (workflowId != null) {
Workflow workflow = workflowService.getById(workflowId);
model.addAttribute("workflow", workflow);
}
return "user/wizard/wiz-start-by-docs";
}
@GetMapping(value = "/wiz-init-steps/{id}")
public String wiz4(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id,
@RequestParam(value = "workflowId", required = false) Long workflowId,
@RequestParam(value = "forceAllSign", required = false) Boolean forceAllSign,
@RequestParam(value = "recipientsCCEmailsWiz", required = false) List<String> recipientsCCEmailsWiz,
@RequestParam(value = "comment", required = false) String comment,
Model model) throws EsupSignatureFsException {
User user = (User) model.getAttribute("user");
SignBook signBook = signBookService.getById(id);
signBook.setForceAllDocsSign(forceAllSign);
if(comment != null && !comment.isEmpty()) {
commentService.create(signBook.getSignRequests().get(0).getId(), comment, 0, 0, 0, null, true, null, userEppn);
}
signBookService.addViewers(id, recipientsCCEmailsWiz);
if(signBook.getCreateBy().getEppn().equals(userEppn)) {
model.addAttribute("signBook", signBook);
if (workflowId != null) {
signBookService.initSignBook(id, workflowId, user);
model.addAttribute("isTempUsers", signRequestService.isTempUsers(signBook.getSignRequests().get(0).getId()));
return "user/wizard/wiz-setup-workflow";
}
}
return "user/wizard/wiz-init-steps";
}
@PostMapping(value = "/wiz-add-step/{id}", produces = "text/html")
public String wizX(@ModelAttribute("userEppn") String userEppn, @ModelAttribute("authUserEppn") String authUserEppn, @PathVariable("id") Long id,
@RequestParam(name="addNew", required = false) Boolean addNew,
@RequestParam(name="userSignFirst", required = false) Boolean userSignFirst,
@RequestParam(name="end", required = false) Boolean end,
@RequestParam(name="close", required = false) Boolean close,
@RequestParam(name="start", required = false) Boolean start,
@RequestBody JsonWorkflowStep step,
Model model) throws EsupSignatureException {
SignBook signBook = signBookService.getById(id);
if(signBook.getCreateBy().getEppn().equals(userEppn)) {
if(step.getRecipientsEmails() != null && step.getRecipientsEmails().size() > 0) {
if (userSignFirst) {
liveWorkflowStepService.addNewStepToSignBook(id, SignType.pdfImageStamp, false, Collections.singletonList(userService.getByEppn(authUserEppn).getEmail()), null, authUserEppn);
}
liveWorkflowStepService.addNewStepToSignBook(id, SignType.valueOf(step.getSignType()), step.getAllSignToComplete(), step.getRecipientsEmails(), step.getExternalUsersInfos(), authUserEppn);
} else {
end = true;
}
model.addAttribute("signBook", signBook);
model.addAttribute("close", close);
if(end != null && end) {
if(signRequestService.startLiveWorkflow(signBook, userEppn, authUserEppn, start)) {
return "user/wizard/wiz-save";
} else {
return "user/wizard/wizend";
}
}
}
return "user/wizard/wiz-init-steps";
}
// @GetMapping(value = "/wiz-save/{id}")
// public String saveForm(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, Model model) {
// SignBook signBook = signBookService.getById(id);
// }
@PostMapping(value = "/wiz-save/{id}")
public String saveWorkflow(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id,
@RequestParam(name="name") String name,
Model model) {
User user = (User) model.getAttribute("user");
SignBook signBook = signBookService.getById(id);
model.addAttribute("signBook", signBook);
try {
workflowService.saveWorkflow(id, name, name, user);
} catch (EsupSignatureException e) {
// eventService.publishEvent(new JsonMessage("error", "Un circuit de signature porte déjà ce nom"), "user", eventService.getClientIdByEppn(userEppn));
return "user/wizard/wiz-save";
}
return "user/wizard/wizend";
}
@GetMapping(value = "/wiz-init-steps-workflow")
public String wizWorkflow(@ModelAttribute("userEppn") String userEppn, Model model) {
return "user/wizard/wiz-init-steps-workflow";
}
@PostMapping(value = "/wiz-add-step-workflow", produces = "text/html")
public String wizXWorkflow(@ModelAttribute("userEppn") String userEppn,
@RequestParam(name="end", required = false) Boolean end,
@RequestBody JsonWorkflowStep step,
Model model) {
User user = (User) model.getAttribute("user");
String[] recipientsEmailsArray = new String[step.getRecipientsEmails().size()];
recipientsEmailsArray = step.getRecipientsEmails().toArray(recipientsEmailsArray);
Workflow workflow = workflowService.addStepToWorkflow(step.getWorkflowId(), SignType.valueOf(step.getSignType()), step.getAllSignToComplete(), recipientsEmailsArray, user);
model.addAttribute("workflow", workflow);
if(end != null && end) {
if(workflow.getWorkflowSteps().size() > 0) {
return "user/wizard/wiz-save-workflow";
}else {
return "user/wizard/wizend";
}
}
return "user/wizard/wiz-init-steps-workflow";
}
@GetMapping(value = "/wiz-save-workflow/{id}")
public String wiz5Workflow(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, Model model) {
Workflow workflow = workflowService.getById(id);
if(workflow.getCreateBy().getEppn().equals(userEppn)) {
model.addAttribute("workflow", workflow);
}
return "user/wizard/wiz-save-workflow";
}
@PostMapping(value = "/wiz-save-workflow/{id}")
public String wiz5Workflow(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, @RequestParam(name="name") String name, Model model) {
User user = (User) model.getAttribute("user");
if(!workflowService.isWorkflowExist(name, userEppn)) {
Workflow workflow = workflowService.initWorkflow(user, id, name);
model.addAttribute("workflow", workflow);
return "user/wizard/wizend";
} else {
Workflow workflow = workflowService.getById(id);
model.addAttribute("workflow", workflow);
// eventService.publishEvent(new JsonMessage("error", "Un circuit de signature porte déjà ce nom"), "user", eventService.getClientIdByEppn(userEppn));
return "user/wizard/wiz-save-workflow";
}
}
@GetMapping(value = "/wizend-workflow/{id}")
public String wizEndWorkflow(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, Model model) throws EsupSignatureException {
Workflow workflow = workflowService.getById(id);
if(workflow.getCreateBy().getEppn().equals(userEppn)) {
model.addAttribute("workflow", workflow);
return "user/wizard/wizend";
} else {
throw new EsupSignatureException("not authorized");
}
}
@PostMapping(value = "/wizend/{id}")
public String wizEnd(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, @RequestParam(name="close") String close, Model model) throws EsupSignatureException, EsupSignatureMailException {
SignBook signBook = signBookService.getById(id);
if(signBook.getCreateBy().getEppn().equals(userEppn)) {
signBookService.sendCCEmail(id, null);
model.addAttribute("signBook", signBook);
model.addAttribute("close", close);
return "user/wizard/wizend";
} else {
throw new EsupSignatureException("not authorized");
}
}
@GetMapping(value = "/wizredirect/{id}")
public String wizRedirect(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, RedirectAttributes redirectAttributes) throws EsupSignatureException {
SignBook signBook = signBookService.getById(id);
if(signBook.getCreateBy().getEppn().equals(userEppn)) {
// signBookService.startLiveWorkflow(signBook, userEppn, userEppn, false);
if(signBook.getLiveWorkflow().getCurrentStep() == null) {
redirectAttributes.addFlashAttribute("message", new JsonMessage("warn", "Après vérification, vous devez confirmer l'envoi pour finaliser la demande"));
}
return "redirect:/user/signrequests/" + signBook.getSignRequests().get(0).getId();
} else {
throw new EsupSignatureException("not authorized");
}
}
@DeleteMapping(value = "/delete-workflow/{id}", produces = "text/html")
public String delete(@ModelAttribute("userEppn") String userEppn, @PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
Workflow workflow = workflowService.getById(id);
if (!workflow.getCreateBy().getEppn().equals(userEppn)) {
redirectAttributes.addFlashAttribute("message", new JsonMessage("error", "Non autorisé"));
} else {
try {
workflowService.delete(workflow);
} catch (EsupSignatureException e) {
redirectAttributes.addFlashAttribute("message", new JsonMessage("error", e.getMessage()));
}
}
return "redirect:/user/";
}
}
| 49.3361 | 213 | 0.653659 |
a612df6f6853b396ee44382d048365f03c887dcb | 5,220 | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.cassandra.lucene.search.condition;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Circle;
import com.stratio.cassandra.lucene.IndexException;
import com.stratio.cassandra.lucene.common.GeoDistance;
import com.stratio.cassandra.lucene.common.GeoDistanceUnit;
import com.stratio.cassandra.lucene.schema.mapping.GeoPointMapper;
import com.stratio.cassandra.lucene.util.GeospatialUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.spatial.SpatialStrategy;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;
import static org.apache.lucene.search.BooleanClause.Occur.FILTER;
import static org.apache.lucene.search.BooleanClause.Occur.MUST_NOT;
/**
* A {@link Condition} that matches documents containing a point contained between two certain circles.
*
* @author Andres de la Pena {@literal <[email protected]>}
*/
public class GeoDistanceCondition extends SingleMapperCondition<GeoPointMapper> {
/** The latitude of the reference point. */
public final double latitude;
/** The longitude of the reference point. */
public final double longitude;
/** The min allowed distance. */
public final GeoDistance minGeoDistance;
/** The max allowed distance. */
public final GeoDistance maxGeoDistance;
/**
* Constructor using the field name and the value to be matched.
*
* @param boost The boost for this query clause. Documents matching this clause will (in addition to the normal
* weightings) have their score multiplied by {@code boost}. If {@code null}, then {@link #DEFAULT_BOOST} is used as
* default.
* @param field the name of the field to be matched
* @param latitude the latitude of the reference point
* @param longitude the longitude of the reference point
* @param minGeoDistance the min allowed distance
* @param maxGeoDistance the max allowed distance
*/
public GeoDistanceCondition(Float boost,
String field,
Double latitude,
Double longitude,
GeoDistance minGeoDistance,
GeoDistance maxGeoDistance) {
super(boost, field, GeoPointMapper.class);
this.latitude = GeospatialUtils.checkLatitude("latitude", latitude);
this.longitude = GeospatialUtils.checkLongitude("longitude", longitude);
if (maxGeoDistance == null) {
throw new IndexException("max_distance must be provided");
}
this.maxGeoDistance = maxGeoDistance;
this.minGeoDistance = minGeoDistance;
if (minGeoDistance != null && minGeoDistance.compareTo(maxGeoDistance) >= 0) {
throw new IndexException("min_distance must be lower than max_distance");
}
}
/** {@inheritDoc} */
@Override
public Query query(GeoPointMapper mapper, Analyzer analyzer) {
SpatialStrategy spatialStrategy = mapper.distanceStrategy;
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(query(maxGeoDistance, spatialStrategy), FILTER);
if (minGeoDistance != null) {
builder.add(query(minGeoDistance, spatialStrategy), MUST_NOT);
}
Query query = builder.build();
query.setBoost(boost);
return query;
}
private Query query(GeoDistance geoDistance, SpatialStrategy spatialStrategy) {
double kms = geoDistance.getValue(GeoDistanceUnit.KILOMETRES);
double distance = DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM);
Circle circle = GeoPointMapper.SPATIAL_CONTEXT.makeCircle(longitude, latitude, distance);
SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);
return spatialStrategy.makeQuery(args);
}
/** {@inheritDoc} */
@Override
public String toString() {
return toStringHelper(this).add("latitude", latitude)
.add("longitude", longitude)
.add("minGeoDistance", minGeoDistance)
.add("maxGeoDistance", maxGeoDistance)
.toString();
}
} | 41.76 | 120 | 0.689464 |
70411e56f1b0211a51749ee588018a973d2de735 | 2,489 | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.rendering.primitives;
import org.joml.Vector3f;
import org.terasology.engine.rendering.assets.mesh.Mesh;
import org.terasology.engine.rendering.assets.mesh.StandardMeshData;
import org.terasology.engine.utilities.Assets;
import org.terasology.engine.world.block.Block;
import org.terasology.engine.world.block.BlockPart;
import org.terasology.engine.world.block.shapes.BlockMeshPart;
import org.terasology.gestalt.assets.ResourceUrn;
import org.terasology.nui.Color;
public abstract class BlockMeshShapeGenerator implements BlockMeshGenerator {
protected Mesh mesh = null;
public abstract Block getBlock();
public abstract ResourceUrn getBaseUrn();
@Override
public Mesh getStandaloneMesh() {
if (mesh == null || mesh.isDisposed()) {
Block block = getBlock();
StandardMeshData meshData = new StandardMeshData();
int nextIndex = 0;
Vector3f light0 = new Vector3f(1, 1, 1);
for (BlockPart dir : BlockPart.allParts()) {
BlockMeshPart part = block.getPrimaryAppearance().getPart(dir);
if (part != null) {
for (int i = 0; i < part.size(); i++) {
meshData.position.put(part.getVertex(i));
meshData.color0.put(Color.white);
meshData.normal.put(part.getNormal(i));
meshData.uv0.put(part.getTexCoord(i));
meshData.light0.put(light0);
}
for (int i = 0; i < part.indicesSize(); ++i) {
meshData.indices.put(nextIndex + part.getIndex(i));
}
if (block.isDoubleSided()) {
for (int i = 0; i < part.indicesSize(); i += 3) {
meshData.indices.put(nextIndex + part.getIndex(i + 1));
meshData.indices.put(nextIndex + part.getIndex(i));
meshData.indices.put(nextIndex + part.getIndex(i + 2));
}
}
nextIndex += part.size();
}
}
mesh = Assets.generateAsset(
new ResourceUrn(getBaseUrn(), block.getURI().toString()), meshData,
Mesh.class);
}
return mesh;
}
}
| 41.483333 | 87 | 0.562475 |
d817ac921a227cbace66841460cd844fa6a226b5 | 1,320 | package com.tappx.a;
import android.content.Context;
import com.tappx.sdk.android.TappxPrivacyManager;
public final class o2 {
private static volatile o2 c;
/* renamed from: a reason: collision with root package name */
private final Context f537a;
private final m2 b = new m2();
private o2(Context context) {
this.f537a = context;
}
public static o2 a(Context context) {
o2 o2Var = c;
if (o2Var == null) {
synchronized (o2.class) {
o2Var = c;
if (o2Var == null) {
c = new o2(context.getApplicationContext());
o2 o2Var2 = c;
return o2Var2;
}
}
}
return o2Var;
}
private c d() {
return c.a(this.f537a);
}
private v e() {
return d().l();
}
private t f() {
return new t(d().j());
}
private i2 g() {
return new i2(e());
}
private q2 h() {
return new q2(d().j());
}
/* access modifiers changed from: package-private */
public m2 b() {
return this.b;
}
public n2 c() {
return new n2(h(), new k2(e(), f()), b(), g());
}
public TappxPrivacyManager a() {
return new r2(c());
}
}
| 20.307692 | 67 | 0.487879 |
0b191d27c3d63b235ae01a519e243b220ae3e23d | 16,915 | /*
* Copyright (c) 2003-2016, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.framework;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.Vector;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.VersionRange;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.packageadmin.RequiredBundle;
/**
* Framework service which allows bundle programmers to inspect the packages
* exported in the framework and eagerly update or uninstall bundles.
*
* If present, there will only be a single instance of this service registered
* in the framework.
*
* <p>
* The term <i>exported package</i> (and the corresponding interface
* {@link ExportedPackage}) refers to a package that has actually been exported
* (as opposed to one that is available for export).
*
* <p>
* Note that the information about exported packages returned by this service is
* valid only until the next time {@link #refreshPackages} is called. If an
* ExportedPackage becomes stale, (that is, the package it references has been
* updated or removed as a result of calling PackageAdmin.refreshPackages()),
* its getName() and getSpecificationVersion() continue to return their old
* values, isRemovalPending() returns true, and getExportingBundle() and
* getImportingBundles() return null.
*
* @see org.osgi.service.packageadmin.PackageAdmin
* @author Jan Stein
* @author Erik Wistrand
* @author Robert Shelley
* @author Philippe Laporte
* @author Mats-Ola Persson
*/
@SuppressWarnings("deprecation")
public class PackageAdminImpl implements PackageAdmin {
final static String SPEC_VERSION = "1.2";
private final FrameworkContext fwCtx;
volatile private Vector<Thread> refreshSync = new Vector<Thread>(1);
PackageAdminImpl(FrameworkContext fw) {
fwCtx = fw;
}
/**
* Gets the packages exported by the specified bundle.
*
* @param bundle The bundle whose exported packages are to be returned, or
* <tt>null</tt> if all the packages currently exported in the
* framework are to be returned. If the specified bundle is the
* system bundle (that is, the bundle with id 0), this method returns
* all the packages on the system classpath whose name does not start
* with "java.". In an environment where the exhaustive list of
* packages on the system classpath is not known in advance, this
* method will return all currently known packages on the system
* classpath, that is, all packages on the system classpath that
* contains one or more classes that have been loaded.
*
* @return The array of packages exported by the specified bundle, or
* <tt>null</tt> if the specified bundle has not exported any
* packages.
*/
public ExportedPackage[] getExportedPackages(Bundle bundle) {
final ArrayList<ExportedPackageImpl> pkgs = new ArrayList<ExportedPackageImpl>();
if (bundle != null) {
for (final Iterator<ExportPkg> i = ((BundleImpl)bundle).getExports(); i.hasNext();) {
final ExportPkg ep = i.next();
if (ep.isExported()) {
pkgs.add(new ExportedPackageImpl(ep));
}
}
} else {
for (final BundleImpl b : fwCtx.bundles.getBundles()) {
for (final Iterator<ExportPkg> i = b.getExports(); i.hasNext();) {
final ExportPkg ep = i.next();
if (ep.isExported()) {
pkgs.add(new ExportedPackageImpl(ep));
}
}
}
}
final int size = pkgs.size();
if (size > 0) {
return pkgs.toArray(new ExportedPackage[size]);
} else {
return null;
}
}
/**
* Gets the exported packages for the specified package name.
*
* @param name The name of the exported packages to be returned.
*
* @return An array of the exported packages, or <code>null</code> if no
* exported packages with the specified name exists.
*/
public ExportedPackage[] getExportedPackages(String name) {
final Pkg pkg = fwCtx.resolver.getPkg(name);
ExportedPackage[] res = null;
if (pkg != null) {
synchronized (pkg) {
final int size = pkg.exporters.size();
if (size > 0) {
res = new ExportedPackage[size];
final Iterator<ExportPkg> i = pkg.exporters.iterator();
for (int pos = 0; pos < size;) {
res[pos++] = new ExportedPackageImpl(i.next());
}
}
}
}
return res;
}
/**
* Gets the ExportedPackage with the specified package name. All exported
* packages will be checked for the specified name. In an environment where
* the exhaustive list of packages on the system classpath is not known in
* advance, this method attempts to see if the named package is on the system
* classpath. This means that this method may discover an ExportedPackage that
* was not present in the list returned by <tt>getExportedPackages()</tt>.
*
* @param name The name of the exported package to be returned.
*
* @return The exported package with the specified name, or <tt>null</tt> if
* no expored package with that name exists.
*/
public ExportedPackage getExportedPackage(String name) {
final Pkg p = fwCtx.resolver.getPkg(name);
if (p != null) {
final ExportPkg ep = p.getBestProvider();
if (ep != null) {
return new ExportedPackageImpl(ep);
}
}
return null;
}
/**
* Forces the update (replacement) or removal of packages exported by the
* specified bundles.
*
* @see org.osgi.service.packageadmin.PackageAdmin#refreshPackages
*/
public void refreshPackages(final Bundle[] bundles) {
refreshPackages(bundles, null);
}
void refreshPackages(final Bundle[] bundles, final FrameworkListener[] fl) {
fwCtx.perm.checkResolveAdminPerm();
boolean restart = false;
if (bundles != null) {
for (int i = 0; i < bundles.length; i++) {
fwCtx.checkOurBundle(bundles[i]);
if (((BundleImpl)bundles[i]).extensionNeedsRestart()) {
restart = true;
break;
}
}
} else {
restart = fwCtx.bundles.checkExtensionBundleRestart();
}
if (restart) {
try {
// will restart the framework.
fwCtx.systemBundle.update();
} catch (final BundleException ignored) {
/* this can't be happening. */
}
return;
}
final PackageAdminImpl thisClass = this;
synchronized (refreshSync) {
final Thread t = new Thread(fwCtx.threadGroup, "RefreshPackages") {
@Override
public void run() {
fwCtx.perm.callRefreshPackages0(thisClass, bundles, fl);
}
};
t.setDaemon(false);
refreshSync.add(t);
t.start();
// Wait for a refresh thread to start
try {
refreshSync.wait(500);
} catch (final InterruptedException ignore) {
}
}
}
/**
*
*/
void refreshPackages0(final Bundle[] bundles, final FrameworkListener...fl) {
if (fwCtx.debug.resolver) {
fwCtx.debug.println("PackageAdminImpl.refreshPackages() starting");
}
final ArrayList<BundleImpl> startList = new ArrayList<BundleImpl>();
BundleImpl [] bi;
synchronized (fwCtx.resolver) {
final TreeSet<Bundle> zombies = fwCtx.resolver.getZombieAffected(bundles);
bi = zombies.toArray(new BundleImpl[zombies.size()]);
synchronized (refreshSync) {
refreshSync.notifyAll();
}
// Stop affected bundles and remove their classloaders
// in reverse start order
for (int bx = bi.length; bx-- > 0;) {
if (bi[bx].state == Bundle.ACTIVE || bi[bx].state == Bundle.STARTING) {
startList.add(0, bi[bx]);
try {
bi[bx].waitOnOperation(fwCtx.resolver, "PackageAdmin.refreshPackages", false);
final Exception be = bi[bx].stop0();
if (be != null) {
fwCtx.frameworkError(bi[bx], be);
}
} catch (final BundleException ignore) {
// Wait failed, we will try again
}
}
}
// Update the affected bundle states in normal start order
int startPos = startList.size() - 1;
BundleImpl nextStart = startPos >= 0 ? startList.get(startPos) : null;
for (int bx = bi.length; bx-- > 0;) {
Exception be = null;
switch (bi[bx].state) {
case Bundle.STARTING:
case Bundle.ACTIVE:
// Bundle must stop before we can continue
// We could hang forever here.
while (true) {
try {
bi[bx].waitOnOperation(fwCtx.resolver, "PackageAdmin.refreshPackages", true);
break;
} catch (final BundleException we) {
if (fwCtx.debug.resolver) {
fwCtx.debug
.println("PackageAdminImpl.refreshPackages() timeout on bundle stop, retry...");
}
fwCtx.frameworkWarning(bi[bx], we);
}
}
be = bi[bx].stop0();
if (be != null) {
fwCtx.frameworkError(bi[bx], be);
}
if (nextStart != bi[bx]) {
startList.add(startPos + 1, bi[bx]);
}
// Fall through...
case Bundle.STOPPING:
case Bundle.RESOLVED:
bi[bx].setStateInstalled(true);
if (bi[bx] == nextStart) {
nextStart = --startPos >= 0 ? startList.get(startPos) : null;
}
// Fall through...
case Bundle.INSTALLED:
case Bundle.UNINSTALLED:
break;
}
bi[bx].purge();
}
}
if (fwCtx.debug.resolver) {
fwCtx.debug.println("PackageAdminImpl.refreshPackages() "
+ "all affected bundles now in state INSTALLED");
}
// Restart previously active bundles in normal start order
startBundles(startList);
final FrameworkEvent fe = new FrameworkEvent(FrameworkEvent.PACKAGES_REFRESHED,
fwCtx.systemBundle, null);
fwCtx.listeners.frameworkEvent(fe, fl);
refreshSync.remove(Thread.currentThread());
if (fwCtx.debug.resolver) {
fwCtx.debug.println("PackageAdminImpl.refreshPackages() done.");
}
}
/**
* Start a list of bundles in order
*
* @param slist Bundles to start.
*/
private void startBundles(List<BundleImpl> slist) {
// Sort in start order
// Resolve first to avoid dead lock
BundleImpl [] triggers = slist.toArray(new BundleImpl[slist.size()]);
for (final BundleImpl rb : slist) {
rb.getUpdatedState(triggers, false);
}
try {
fwCtx.resolverHooks.endResolve(triggers);
} catch (final BundleException be) {
// TODO Fix correct bundle
fwCtx.frameworkError(fwCtx.systemBundle, be);
}
for (final BundleImpl rb : slist) {
if (rb.getState() == Bundle.RESOLVED) {
try {
rb.start();
} catch (final BundleException be) {
fwCtx.frameworkError(rb, be);
}
}
}
}
/**
*
*/
public boolean resolveBundles(Bundle[] bundles) {
fwCtx.perm.checkResolveAdminPerm();
synchronized (fwCtx.resolver) {
fwCtx.resolverHooks.checkResolveBlocked();
List<BundleImpl> bl = new ArrayList<BundleImpl>();
boolean res = true;
if (bundles != null) {
for (final Bundle bundle : bundles) {
if (bundle.getState() == Bundle.INSTALLED) {
bl.add((BundleImpl)bundle);
} else if (bundle.getState() == Bundle.UNINSTALLED) {
res = false;
}
}
} else {
for (final BundleImpl bundle : fwCtx.bundles.getBundles()) {
if (bundle.getState() == Bundle.INSTALLED) {
bl.add(bundle);
}
}
}
if (!bl.isEmpty()) {
final BundleImpl [] triggers = bl.toArray(new BundleImpl[bl.size()]);
// TODO Resolve all at once, so that we can handle resolver abort correctly!
for (final Bundle bundle : bl) {
final BundleImpl b = (BundleImpl)bundle;
if (b.getUpdatedState(triggers, false) == Bundle.INSTALLED) {
res = false;
}
}
try {
fwCtx.resolverHooks.endResolve(triggers);
} catch (BundleException be) {
// TODO Fix correct bundle
fwCtx.frameworkError(fwCtx.systemBundle, be);
}
}
return res;
}
}
public RequiredBundle[] getRequiredBundles(String symbolicName) {
List<BundleGeneration> bgs = fwCtx.bundles.getBundleGenerations(symbolicName);
final ArrayList<RequiredBundleImpl> res = new ArrayList<RequiredBundleImpl>();
for (final BundleGeneration bg : bgs) {
if ((bg.bundle.isResolved() || bg.bundle.getRequiredBy().size() > 0)
&& !bg.isFragment()) {
res.add(new RequiredBundleImpl(bg.bpkgs));
}
}
final int s = res.size();
if (s > 0) {
return res.toArray(new RequiredBundle[s]);
} else {
return null;
}
}
public Bundle[] getBundles(String symbolicName, String versionRange) {
final VersionRange vr = versionRange != null ? new VersionRange(versionRange.trim()) :
null;
final List<BundleGeneration> bgs = fwCtx.bundles.getBundles(symbolicName, vr);
final int size = bgs.size();
if (size > 0) {
final Bundle[] res = new Bundle[size];
final Iterator<BundleGeneration> i = bgs.iterator();
for (int pos = 0; pos < size;) {
res[pos++] = i.next().bundle;
}
return res;
} else {
return null;
}
}
public Bundle[] getFragments(Bundle bundle) {
if (bundle == null) {
return null;
}
final BundleGeneration bg = ((BundleImpl)bundle).current();
if (bg.isFragment()) {
return null;
}
if (bg.isFragmentHost()) {
@SuppressWarnings("unchecked")
final Vector<BundleGeneration> fix = (Vector<BundleGeneration>) bg.fragments.clone();
final Bundle[] r = new Bundle[fix.size()];
for (int i = fix.size() - 1; i >= 0; i--) {
r[i] = fix.get(i).bundle;
}
return r;
} else {
return null;
}
}
public Bundle[] getHosts(Bundle bundle) {
final BundleImpl b = (BundleImpl) bundle;
if (b != null) {
final Vector<BundleGeneration> h = b.getHosts(false);
if (h != null) {
final Bundle[] r = new Bundle[h.size()];
int pos = 0;
for (final BundleGeneration bg : h) {
r[pos++] = bg.bundle;
}
return r;
}
}
return null;
}
public Bundle getBundle(@SuppressWarnings("rawtypes") Class clazz) {
final ClassLoader cl = clazz.getClassLoader();
if (cl instanceof BundleClassLoader) {
return ((BundleClassLoader)cl).getBundle();
} else {
return null;
}
}
public int getBundleType(Bundle bundle) {
final BundleGeneration bg = ((BundleImpl)bundle).current();
return bg.isFragment() && !bg.isExtension() ? BUNDLE_TYPE_FRAGMENT : 0;
}
}
| 33.695219 | 100 | 0.628791 |
06e58493e60d3d450974fa2576a39312820b52a8 | 1,384 | package de.immomio.mailsender;
import de.immomio.config.ApplicationMessageSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.tools.generic.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
/**
* @author Johannes Hiemer.
* @author Bastian Bliemeister
*/
@Slf4j
@Service
public class VelocityInternalizationLoader {
@Autowired
private ApplicationMessageSource messageSource;
@Autowired
private VelocityEngine velocityEngine;
public String merge(String templateLocation, String encoding, Map<String, Object> data) {
if (data == null) {
data = new HashMap<>();
}
data.put("date", new DateTool());
data.put("messages", this.messageSource);
VelocityContext context = new VelocityContext(data);
StringWriter sw = new StringWriter();
boolean bool = velocityEngine.mergeTemplate(templateLocation, "UTF-8", context, sw);
if (!bool) {
throw new VelocityException("Error merging template -> " + templateLocation);
}
return sw.toString();
}
}
| 27.68 | 93 | 0.717486 |
0ec848e959c218abcc1ef8cd6cff00bbb519fe82 | 3,370 | /*
* (C) Copyright 2014-2015 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Benoit Delbosc
* Florent Guillaume
*/
package org.nuxeo.elasticsearch.core;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.elasticsearch.action.search.SearchResponse;
import org.nuxeo.ecm.core.api.IterableQueryResult;
import org.nuxeo.ecm.core.schema.types.Type;
/**
* Iterable query result of the results of an Elasticsearch query.
* <p>
* Loads all results in memory.
*
* @since 7.2
*/
public class EsResultSetImpl implements IterableQueryResult, Iterator<Map<String, Serializable>> {
private final SearchResponse response;
private final Map<String, Type> selectFieldsAndTypes;
protected List<Map<String, Serializable>> maps;
protected long size;
boolean closed;
private long pos;
public EsResultSetImpl(SearchResponse response, Map<String, Type> selectFieldsAndTypes) {
this.response = response;
this.selectFieldsAndTypes = selectFieldsAndTypes;
maps = buildMaps();
size = maps.size();
}
protected List<Map<String, Serializable>> buildMaps() {
return new EsSearchHitConverter(selectFieldsAndTypes).convert(response.getHits().getHits());
}
@Override
public void close() {
closed = true;
pos = -1;
}
@Override
public boolean isLife() {
return !closed;
}
@Override
public boolean mustBeClosed() {
return false; // holds no resources
}
/**
* Returns the number of results available in the iterator. Note that before 9.1 this method was returning the
* totalSize.
*
* @since 9.1
*/
@Override
public long size() {
return size;
}
/**
* Returns the total number of result that match the query.
*
* @since 9.1
*/
public long totalSize() {
return response.getHits().getTotalHits().value;
}
@Override
public long pos() {
return pos;
}
@Override
public void skipTo(long pos) {
if (pos < 0) {
pos = 0;
} else if (pos > size) {
pos = size;
}
this.pos = pos;
}
@Override
public Iterator<Map<String, Serializable>> iterator() {
return this; // NOSONAR this iterable does not support multiple traversals
}
@Override
public boolean hasNext() {
return pos < size;
}
@Override
public Map<String, Serializable> next() {
if (closed || pos == size) {
throw new NoSuchElementException();
}
Map<String, Serializable> map = maps.get((int) pos);
pos++;
return map;
}
}
| 24.779412 | 114 | 0.64184 |
9f99414748028cd60203b29772a9953ca7099c3e | 1,201 | package com.xeiam.xchange.cryptsy.dto.marketdata;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author ObsessiveOrange
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CryptsyOrderBook {
private final int marketId;
private final List<CryptsyBuyOrder> buyOrders;
private final List<CryptsySellOrder> sellOrders;
/**
* Constructor
*/
@JsonCreator
public CryptsyOrderBook(@JsonProperty("marketid") int marketId, @JsonProperty("buyorders") List<CryptsyBuyOrder> buyOrders, @JsonProperty("sellorders") List<CryptsySellOrder> sellOrders) {
this.marketId = marketId;
this.buyOrders = buyOrders;
this.sellOrders = sellOrders;
}
public int marketId() {
return marketId;
}
public List<CryptsyBuyOrder> buyOrders() {
return buyOrders;
}
public List<CryptsySellOrder> sellOrders() {
return sellOrders;
}
@Override
public String toString() {
return "CryptsyOrderBook [Market ID='" + marketId + "',Buy Orders='" + buyOrders + "',Sell Orders=" + sellOrders + "]";
}
}
| 22.660377 | 190 | 0.729392 |
88c6a02c3e8a3c86379eafa509451b464a9923d1 | 3,276 | package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EXERCISE_WEIGHT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_REPS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_SETS;
import java.util.Optional;
import java.util.stream.Stream;
import seedu.address.logic.commands.AddExerciseCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.exercise.Exercise;
import seedu.address.model.exercise.ExerciseDate;
import seedu.address.model.exercise.ExerciseName;
import seedu.address.model.exercise.ExerciseReps;
import seedu.address.model.exercise.ExerciseSets;
import seedu.address.model.exercise.ExerciseWeight;
/**
* Parses input arguments and creates a new AddExerciseCommand object
*/
public class AddExerciseCommandParser implements Parser<AddExerciseCommand> {
/**
* Parses the given {@code String} of arguments in the context of the
* AddExerciseCommand and returns an AddExerciseCommand object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public AddExerciseCommand parse(String args) throws ParseException {
ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_REPS,
PREFIX_EXERCISE_WEIGHT, PREFIX_SETS, PREFIX_DATE);
if (!arePrefixesPresent(argMultimap, PREFIX_NAME, PREFIX_DATE)) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddExerciseCommand.MESSAGE_USAGE));
}
ExerciseName name = ParserUtil.parseExerciseName(argMultimap.getValue(PREFIX_NAME).get());
Optional<String> repsString = argMultimap.getValue(PREFIX_REPS);
ExerciseReps reps = repsString.isPresent()
? ParserUtil.parseExerciseReps(argMultimap.getValue(PREFIX_REPS).get())
: new ExerciseReps("");
Optional<String> exerciseWeightString = argMultimap.getValue(PREFIX_EXERCISE_WEIGHT);
ExerciseWeight exerciseWeight = exerciseWeightString.isPresent()
? ParserUtil.parseExerciseWeight(argMultimap.getValue(PREFIX_EXERCISE_WEIGHT).get())
: new ExerciseWeight("");
Optional<String> setsString = argMultimap.getValue(PREFIX_SETS);
ExerciseSets sets = setsString.isPresent()
? ParserUtil.parseExerciseSets(argMultimap.getValue(PREFIX_SETS).get())
: new ExerciseSets("");
ExerciseDate date = ParserUtil.parseExerciseDate(argMultimap.getValue(PREFIX_DATE).get());
Exercise exercise = new Exercise(name, reps, sets, exerciseWeight, date);
return new AddExerciseCommand(exercise);
}
/*
* Returns true if none of the prefixes contains empty {@code Optional} values
* in the given {@code ArgumentMultimap}.
*/
private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) {
return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent());
}
}
| 44.876712 | 118 | 0.75641 |
0fdb7ea40d668f80acc32c587c98108f9cbd17d7 | 9,054 | /*
* 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.spotify.reaper;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import org.apache.cassandra.repair.RepairParallelism;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.spotify.reaper.AppContext;
import com.spotify.reaper.ReaperApplicationConfiguration;
import com.spotify.reaper.ReaperApplicationConfiguration.JmxCredentials;
import com.spotify.reaper.ReaperException;
import com.spotify.reaper.cassandra.JmxConnectionFactory;
import com.spotify.reaper.resources.ClusterResource;
import com.spotify.reaper.resources.PingResource;
import com.spotify.reaper.resources.ReaperHealthCheck;
import com.spotify.reaper.resources.RepairRunResource;
import com.spotify.reaper.resources.RepairScheduleResource;
import com.spotify.reaper.service.RepairManager;
import com.spotify.reaper.service.SchedulingManager;
import com.spotify.reaper.storage.CassandraStorage;
import com.spotify.reaper.storage.IStorage;
import com.spotify.reaper.storage.MemoryStorage;
import com.spotify.reaper.storage.PostgresStorage;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ReaperApplication extends Application<ReaperApplicationConfiguration> {
static final Logger LOG = LoggerFactory.getLogger(ReaperApplication.class);
private AppContext context;
public ReaperApplication() {
super();
LOG.info("default ReaperApplication constructor called");
this.context = new AppContext();
}
@VisibleForTesting
public ReaperApplication(AppContext context) {
super();
LOG.info("ReaperApplication constructor called with custom AppContext");
this.context = context;
}
public static void main(String[] args) throws Exception {
new ReaperApplication().run(args);
}
@Override
public String getName() {
return "cassandra-reaper";
}
/**
* Before a Dropwizard application can provide the command-line interface, parse a configuration
* file, or run as a server, it must first go through a bootstrapping phase. You can add Bundles,
* Commands, or register Jackson modules to allow you to include custom types as part of your
* configuration class.
*/
@Override
public void initialize(Bootstrap<ReaperApplicationConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets/", "/webui", "index.html"));
}
@Override
public void run(ReaperApplicationConfiguration config,
Environment environment) throws Exception {
// Using UTC times everywhere as default. Affects only Yoda time.
DateTimeZone.setDefault(DateTimeZone.UTC);
checkConfiguration(config);
context.config = config;
addSignalHandlers(); // SIGHUP, etc.
LOG.info("initializing runner thread pool with {} threads", config.getRepairRunThreadCount());
context.repairManager = new RepairManager();
context.repairManager.initializeThreadPool(
config.getRepairRunThreadCount(),
config.getHangingRepairTimeoutMins(), TimeUnit.MINUTES,
30, TimeUnit.SECONDS);
if (context.storage == null) {
LOG.info("initializing storage of type: {}", config.getStorageType());
context.storage = initializeStorage(config, environment);
} else {
LOG.info("storage already given in context, not initializing a new one");
}
if (context.jmxConnectionFactory == null) {
LOG.info("no JMX connection factory given in context, creating default");
context.jmxConnectionFactory = new JmxConnectionFactory();
}
// read jmx host/port mapping from config and provide to jmx con.factory
Map<String, Integer> jmxPorts = config.getJmxPorts();
if (jmxPorts != null) {
LOG.debug("using JMX ports mapping: " + jmxPorts);
context.jmxConnectionFactory.setJmxPorts(jmxPorts);
}
// Enable cross-origin requests for using external GUI applications.
if (config.isEnableCrossOrigin() || System.getProperty("enableCrossOrigin") != null) {
final FilterRegistration.Dynamic cors = environment.servlets()
.addFilter("crossOriginRequests", CrossOriginFilter.class);
cors.setInitParameter("allowedOrigins", "*");
cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
JmxCredentials jmxAuth = config.getJmxAuth();
if (jmxAuth != null) {
LOG.debug("using specified JMX credentials for authentication");
context.jmxConnectionFactory.setJmxAuth(jmxAuth);
}
LOG.info("creating and registering health checks");
// Notice that health checks are registered under the admin application on /healthcheck
final ReaperHealthCheck healthCheck = new ReaperHealthCheck(context);
environment.healthChecks().register("reaper", healthCheck);
environment.jersey().register(healthCheck);
LOG.info("creating resources and registering endpoints");
final PingResource pingResource = new PingResource();
environment.jersey().register(pingResource);
final ClusterResource addClusterResource = new ClusterResource(context);
environment.jersey().register(addClusterResource);
final RepairRunResource addRepairRunResource = new RepairRunResource(context);
environment.jersey().register(addRepairRunResource);
final RepairScheduleResource addRepairScheduleResource = new RepairScheduleResource(context);
environment.jersey().register(addRepairScheduleResource);
Thread.sleep(1000);
SchedulingManager.start(context);
LOG.info("resuming pending repair runs");
context.repairManager.resumeRunningRepairRuns(context);
}
private IStorage initializeStorage(ReaperApplicationConfiguration config,
Environment environment) throws ReaperException {
IStorage storage;
if ("memory".equalsIgnoreCase(config.getStorageType())) {
storage = new MemoryStorage();
} else if ("database".equalsIgnoreCase(config.getStorageType())) {
storage = new PostgresStorage(config, environment);
}else if ("cassandra".equalsIgnoreCase(config.getStorageType())) {
storage = new CassandraStorage(config, environment);
} else {
LOG.error("invalid storageType: {}", config.getStorageType());
throw new ReaperException("invalid storage type: " + config.getStorageType());
}
assert storage.isStorageConnected() : "Failed to connect storage";
return storage;
}
private void checkConfiguration(ReaperApplicationConfiguration config) {
LOG.debug("repairIntensity: " + config.getRepairIntensity());
LOG.debug("incrementalRepair:" + config.getIncrementalRepair());
LOG.debug("repairRunThreadCount: " + config.getRepairRunThreadCount());
LOG.debug("segmentCount: " + config.getSegmentCount());
LOG.debug("repairParallelism: " + config.getRepairParallelism());
LOG.debug("hangingRepairTimeoutMins: " + config.getHangingRepairTimeoutMins());
LOG.debug("jmxPorts: " + config.getJmxPorts());
}
public static void checkRepairParallelismString(String givenRepairParallelism)
throws ReaperException {
try {
RepairParallelism.valueOf(givenRepairParallelism.toUpperCase());
} catch (java.lang.IllegalArgumentException ex) {
throw new ReaperException(
"invalid repair parallelism given \"" + givenRepairParallelism
+ "\", must be one of: " + Arrays.toString(RepairParallelism.values()));
}
}
void reloadConfiguration() {
// TODO: reload configuration, but how?
LOG.warn("SIGHUP signal dropped, missing implementation for configuration reload");
}
private void addSignalHandlers() {
if(!System.getProperty("os.name").toLowerCase().contains("win")) {
LOG.debug("adding signal handler for SIGHUP");
Signal.handle(new Signal("HUP"), new SignalHandler() {
@Override
public void handle(Signal signal) {
LOG.info("received SIGHUP signal: {}", signal);
reloadConfiguration();
}
});
}
}
}
| 39.537118 | 99 | 0.744312 |
e0fed36be862c37c7dc447fb5fa44244859f33bd | 1,021 | package id.franspratama.geol.view;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsxView;
import id.franspratama.geol.core.pojo.DailyRegionAvailability;
public class DailyAvailabilityExcelView extends AbstractXlsxView{
@Override
protected void buildExcelDocument(Map<String, Object> data, Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DailyAvailabilityExcelBuilder excelBuilder = new DailyAvailabilityExcelBuilder();
@SuppressWarnings("unchecked")
List<DailyRegionAvailability> neDown = (List<DailyRegionAvailability>) data.get("data");
excelBuilder.createWorkbook(workbook, neDown);
response.setHeader("Content-Disposition", "attachment; filename=\"DAILYNAV_EXPORT.xls\"");
workbook.write( response.getOutputStream() );
}
}
| 32.935484 | 107 | 0.799216 |
78c5bb2d21fd7a559468d110434aebe2c426c0a0 | 65,162 | /**
*/
package top.artifact;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import top.base.BasePackage;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see top.artifact.Artifact_Factory
* @model kind="package"
* @generated
*/
public interface Artifact_Package extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "artifact";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://www.deis-project.eu/ode/mergedODE/sacm/artifact";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "artifact_";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
Artifact_Package eINSTANCE = top.artifact.impl.Artifact_PackageImpl.init();
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactGroupImpl <em>Artifact Group</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactGroupImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactGroup()
* @generated
*/
int ARTIFACT_GROUP = 0;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__GID = BasePackage.ARTIFACT_ELEMENT__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__IS_CITATION = BasePackage.ARTIFACT_ELEMENT__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__IS_ABSTRACT = BasePackage.ARTIFACT_ELEMENT__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__CITED_ELEMENT = BasePackage.ARTIFACT_ELEMENT__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__ABSTRACT_FORM = BasePackage.ARTIFACT_ELEMENT__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__NAME = BasePackage.ARTIFACT_ELEMENT__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__DESCRIPTION = BasePackage.ARTIFACT_ELEMENT__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__IMPLEMENTATION_CONSTRAINT = BasePackage.ARTIFACT_ELEMENT__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__NOTE = BasePackage.ARTIFACT_ELEMENT__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__TAGGED_VALUE = BasePackage.ARTIFACT_ELEMENT__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Element</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP__ARTIFACT_ELEMENT = BasePackage.ARTIFACT_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Artifact Group</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP_FEATURE_COUNT = BasePackage.ARTIFACT_ELEMENT_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Artifact Group</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_GROUP_OPERATION_COUNT = BasePackage.ARTIFACT_ELEMENT_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactPackageImpl <em>Artifact Package</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactPackageImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactPackage()
* @generated
*/
int ARTIFACT_PACKAGE = 1;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__GID = BasePackage.ARTIFACT_ELEMENT__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__IS_CITATION = BasePackage.ARTIFACT_ELEMENT__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__IS_ABSTRACT = BasePackage.ARTIFACT_ELEMENT__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__CITED_ELEMENT = BasePackage.ARTIFACT_ELEMENT__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__ABSTRACT_FORM = BasePackage.ARTIFACT_ELEMENT__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__NAME = BasePackage.ARTIFACT_ELEMENT__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__DESCRIPTION = BasePackage.ARTIFACT_ELEMENT__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__IMPLEMENTATION_CONSTRAINT = BasePackage.ARTIFACT_ELEMENT__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__NOTE = BasePackage.ARTIFACT_ELEMENT__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__TAGGED_VALUE = BasePackage.ARTIFACT_ELEMENT__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Element</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE__ARTIFACT_ELEMENT = BasePackage.ARTIFACT_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Artifact Package</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_FEATURE_COUNT = BasePackage.ARTIFACT_ELEMENT_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Artifact Package</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_OPERATION_COUNT = BasePackage.ARTIFACT_ELEMENT_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactPackageBindingImpl <em>Artifact Package Binding</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactPackageBindingImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactPackageBinding()
* @generated
*/
int ARTIFACT_PACKAGE_BINDING = 2;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__GID = ARTIFACT_PACKAGE__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__IS_CITATION = ARTIFACT_PACKAGE__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__IS_ABSTRACT = ARTIFACT_PACKAGE__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__CITED_ELEMENT = ARTIFACT_PACKAGE__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__ABSTRACT_FORM = ARTIFACT_PACKAGE__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__NAME = ARTIFACT_PACKAGE__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__DESCRIPTION = ARTIFACT_PACKAGE__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__IMPLEMENTATION_CONSTRAINT = ARTIFACT_PACKAGE__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__NOTE = ARTIFACT_PACKAGE__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__TAGGED_VALUE = ARTIFACT_PACKAGE__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Element</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__ARTIFACT_ELEMENT = ARTIFACT_PACKAGE__ARTIFACT_ELEMENT;
/**
* The feature id for the '<em><b>Participant Package</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING__PARTICIPANT_PACKAGE = ARTIFACT_PACKAGE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Artifact Package Binding</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING_FEATURE_COUNT = ARTIFACT_PACKAGE_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Artifact Package Binding</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_BINDING_OPERATION_COUNT = ARTIFACT_PACKAGE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactPackageInterfaceImpl <em>Artifact Package Interface</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactPackageInterfaceImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactPackageInterface()
* @generated
*/
int ARTIFACT_PACKAGE_INTERFACE = 3;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__GID = ARTIFACT_PACKAGE__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__IS_CITATION = ARTIFACT_PACKAGE__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__IS_ABSTRACT = ARTIFACT_PACKAGE__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__CITED_ELEMENT = ARTIFACT_PACKAGE__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__ABSTRACT_FORM = ARTIFACT_PACKAGE__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__NAME = ARTIFACT_PACKAGE__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__DESCRIPTION = ARTIFACT_PACKAGE__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__IMPLEMENTATION_CONSTRAINT = ARTIFACT_PACKAGE__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__NOTE = ARTIFACT_PACKAGE__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__TAGGED_VALUE = ARTIFACT_PACKAGE__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Element</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__ARTIFACT_ELEMENT = ARTIFACT_PACKAGE__ARTIFACT_ELEMENT;
/**
* The feature id for the '<em><b>Implements</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE__IMPLEMENTS = ARTIFACT_PACKAGE_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Artifact Package Interface</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE_FEATURE_COUNT = ARTIFACT_PACKAGE_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Artifact Package Interface</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_PACKAGE_INTERFACE_OPERATION_COUNT = ARTIFACT_PACKAGE_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactAssetImpl <em>Artifact Asset</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactAssetImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactAsset()
* @generated
*/
int ARTIFACT_ASSET = 4;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__GID = BasePackage.ARTIFACT_ELEMENT__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__IS_CITATION = BasePackage.ARTIFACT_ELEMENT__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__IS_ABSTRACT = BasePackage.ARTIFACT_ELEMENT__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__CITED_ELEMENT = BasePackage.ARTIFACT_ELEMENT__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__ABSTRACT_FORM = BasePackage.ARTIFACT_ELEMENT__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__NAME = BasePackage.ARTIFACT_ELEMENT__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__DESCRIPTION = BasePackage.ARTIFACT_ELEMENT__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT = BasePackage.ARTIFACT_ELEMENT__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__NOTE = BasePackage.ARTIFACT_ELEMENT__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__TAGGED_VALUE = BasePackage.ARTIFACT_ELEMENT__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET__ARTIFACT_PROPERTY = BasePackage.ARTIFACT_ELEMENT_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Artifact Asset</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_FEATURE_COUNT = BasePackage.ARTIFACT_ELEMENT_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Artifact Asset</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_OPERATION_COUNT = BasePackage.ARTIFACT_ELEMENT_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.PropertyImpl <em>Property</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.PropertyImpl
* @see top.artifact.impl.Artifact_PackageImpl#getProperty()
* @generated
*/
int PROPERTY = 5;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The number of structural features of the '<em>Property</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Property</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PROPERTY_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.TechniqueImpl <em>Technique</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.TechniqueImpl
* @see top.artifact.impl.Artifact_PackageImpl#getTechnique()
* @generated
*/
int TECHNIQUE = 6;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The number of structural features of the '<em>Technique</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Technique</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int TECHNIQUE_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ParticipantImpl <em>Participant</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ParticipantImpl
* @see top.artifact.impl.Artifact_PackageImpl#getParticipant()
* @generated
*/
int PARTICIPANT = 7;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The number of structural features of the '<em>Participant</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Participant</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARTICIPANT_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ActivityImpl <em>Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ActivityImpl
* @see top.artifact.impl.Artifact_PackageImpl#getActivity()
* @generated
*/
int ACTIVITY = 8;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The feature id for the '<em><b>Start Time</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__START_TIME = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>End Time</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY__END_TIME = ARTIFACT_ASSET_FEATURE_COUNT + 1;
/**
* The number of structural features of the '<em>Activity</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 2;
/**
* The number of operations of the '<em>Activity</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ACTIVITY_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.EventImpl <em>Event</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.EventImpl
* @see top.artifact.impl.Artifact_PackageImpl#getEvent()
* @generated
*/
int EVENT = 9;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The feature id for the '<em><b>Occurence</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT__OCCURENCE = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The number of structural features of the '<em>Event</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 1;
/**
* The number of operations of the '<em>Event</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int EVENT_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ResourceImpl <em>Resource</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ResourceImpl
* @see top.artifact.impl.Artifact_PackageImpl#getResource()
* @generated
*/
int RESOURCE = 10;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The number of structural features of the '<em>Resource</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The number of operations of the '<em>Resource</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RESOURCE_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactImpl <em>Artifact</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifact()
* @generated
*/
int ARTIFACT = 11;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The feature id for the '<em><b>Version</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__VERSION = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Date</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT__DATE = ARTIFACT_ASSET_FEATURE_COUNT + 1;
/**
* The number of structural features of the '<em>Artifact</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 2;
/**
* The number of operations of the '<em>Artifact</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* The meta object id for the '{@link top.artifact.impl.ArtifactAssetRelationshipImpl <em>Artifact Asset Relationship</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactAssetRelationshipImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactAssetRelationship()
* @generated
*/
int ARTIFACT_ASSET_RELATIONSHIP = 12;
/**
* The feature id for the '<em><b>Gid</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__GID = ARTIFACT_ASSET__GID;
/**
* The feature id for the '<em><b>Is Citation</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__IS_CITATION = ARTIFACT_ASSET__IS_CITATION;
/**
* The feature id for the '<em><b>Is Abstract</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__IS_ABSTRACT = ARTIFACT_ASSET__IS_ABSTRACT;
/**
* The feature id for the '<em><b>Cited Element</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__CITED_ELEMENT = ARTIFACT_ASSET__CITED_ELEMENT;
/**
* The feature id for the '<em><b>Abstract Form</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__ABSTRACT_FORM = ARTIFACT_ASSET__ABSTRACT_FORM;
/**
* The feature id for the '<em><b>Name</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__NAME = ARTIFACT_ASSET__NAME;
/**
* The feature id for the '<em><b>Description</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__DESCRIPTION = ARTIFACT_ASSET__DESCRIPTION;
/**
* The feature id for the '<em><b>Implementation Constraint</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__IMPLEMENTATION_CONSTRAINT = ARTIFACT_ASSET__IMPLEMENTATION_CONSTRAINT;
/**
* The feature id for the '<em><b>Note</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__NOTE = ARTIFACT_ASSET__NOTE;
/**
* The feature id for the '<em><b>Tagged Value</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__TAGGED_VALUE = ARTIFACT_ASSET__TAGGED_VALUE;
/**
* The feature id for the '<em><b>Artifact Property</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__ARTIFACT_PROPERTY = ARTIFACT_ASSET__ARTIFACT_PROPERTY;
/**
* The feature id for the '<em><b>Source</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__SOURCE = ARTIFACT_ASSET_FEATURE_COUNT + 0;
/**
* The feature id for the '<em><b>Target</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP__TARGET = ARTIFACT_ASSET_FEATURE_COUNT + 1;
/**
* The number of structural features of the '<em>Artifact Asset Relationship</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP_FEATURE_COUNT = ARTIFACT_ASSET_FEATURE_COUNT + 2;
/**
* The number of operations of the '<em>Artifact Asset Relationship</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ARTIFACT_ASSET_RELATIONSHIP_OPERATION_COUNT = ARTIFACT_ASSET_OPERATION_COUNT + 0;
/**
* Returns the meta object for class '{@link top.artifact.ArtifactGroup <em>Artifact Group</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact Group</em>'.
* @see top.artifact.ArtifactGroup
* @generated
*/
EClass getArtifactGroup();
/**
* Returns the meta object for the reference list '{@link top.artifact.ArtifactGroup#getArtifactElement <em>Artifact Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Artifact Element</em>'.
* @see top.artifact.ArtifactGroup#getArtifactElement()
* @see #getArtifactGroup()
* @generated
*/
EReference getArtifactGroup_ArtifactElement();
/**
* Returns the meta object for class '{@link top.artifact.ArtifactPackage <em>Artifact Package</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact Package</em>'.
* @see top.artifact.ArtifactPackage
* @generated
*/
EClass getArtifactPackage();
/**
* Returns the meta object for the containment reference list '{@link top.artifact.ArtifactPackage#getArtifactElement <em>Artifact Element</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Artifact Element</em>'.
* @see top.artifact.ArtifactPackage#getArtifactElement()
* @see #getArtifactPackage()
* @generated
*/
EReference getArtifactPackage_ArtifactElement();
/**
* Returns the meta object for class '{@link top.artifact.ArtifactPackageBinding <em>Artifact Package Binding</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact Package Binding</em>'.
* @see top.artifact.ArtifactPackageBinding
* @generated
*/
EClass getArtifactPackageBinding();
/**
* Returns the meta object for the reference list '{@link top.artifact.ArtifactPackageBinding#getParticipantPackage <em>Participant Package</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Participant Package</em>'.
* @see top.artifact.ArtifactPackageBinding#getParticipantPackage()
* @see #getArtifactPackageBinding()
* @generated
*/
EReference getArtifactPackageBinding_ParticipantPackage();
/**
* Returns the meta object for class '{@link top.artifact.ArtifactPackageInterface <em>Artifact Package Interface</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact Package Interface</em>'.
* @see top.artifact.ArtifactPackageInterface
* @generated
*/
EClass getArtifactPackageInterface();
/**
* Returns the meta object for the reference '{@link top.artifact.ArtifactPackageInterface#getImplements <em>Implements</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Implements</em>'.
* @see top.artifact.ArtifactPackageInterface#getImplements()
* @see #getArtifactPackageInterface()
* @generated
*/
EReference getArtifactPackageInterface_Implements();
/**
* Returns the meta object for class '{@link top.artifact.ArtifactAsset <em>Artifact Asset</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact Asset</em>'.
* @see top.artifact.ArtifactAsset
* @generated
*/
EClass getArtifactAsset();
/**
* Returns the meta object for the reference list '{@link top.artifact.ArtifactAsset#getArtifactProperty <em>Artifact Property</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Artifact Property</em>'.
* @see top.artifact.ArtifactAsset#getArtifactProperty()
* @see #getArtifactAsset()
* @generated
*/
EReference getArtifactAsset_ArtifactProperty();
/**
* Returns the meta object for class '{@link top.artifact.Property <em>Property</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Property</em>'.
* @see top.artifact.Property
* @generated
*/
EClass getProperty();
/**
* Returns the meta object for class '{@link top.artifact.Technique <em>Technique</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Technique</em>'.
* @see top.artifact.Technique
* @generated
*/
EClass getTechnique();
/**
* Returns the meta object for class '{@link top.artifact.Participant <em>Participant</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Participant</em>'.
* @see top.artifact.Participant
* @generated
*/
EClass getParticipant();
/**
* Returns the meta object for class '{@link top.artifact.Activity <em>Activity</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Activity</em>'.
* @see top.artifact.Activity
* @generated
*/
EClass getActivity();
/**
* Returns the meta object for the attribute '{@link top.artifact.Activity#getStartTime <em>Start Time</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Start Time</em>'.
* @see top.artifact.Activity#getStartTime()
* @see #getActivity()
* @generated
*/
EAttribute getActivity_StartTime();
/**
* Returns the meta object for the attribute '{@link top.artifact.Activity#getEndTime <em>End Time</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>End Time</em>'.
* @see top.artifact.Activity#getEndTime()
* @see #getActivity()
* @generated
*/
EAttribute getActivity_EndTime();
/**
* Returns the meta object for class '{@link top.artifact.Event <em>Event</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Event</em>'.
* @see top.artifact.Event
* @generated
*/
EClass getEvent();
/**
* Returns the meta object for the attribute '{@link top.artifact.Event#getOccurence <em>Occurence</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Occurence</em>'.
* @see top.artifact.Event#getOccurence()
* @see #getEvent()
* @generated
*/
EAttribute getEvent_Occurence();
/**
* Returns the meta object for class '{@link top.artifact.Resource <em>Resource</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Resource</em>'.
* @see top.artifact.Resource
* @generated
*/
EClass getResource();
/**
* Returns the meta object for class '{@link top.artifact.Artifact <em>Artifact</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact</em>'.
* @see top.artifact.Artifact
* @generated
*/
EClass getArtifact();
/**
* Returns the meta object for the attribute '{@link top.artifact.Artifact#getVersion <em>Version</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Version</em>'.
* @see top.artifact.Artifact#getVersion()
* @see #getArtifact()
* @generated
*/
EAttribute getArtifact_Version();
/**
* Returns the meta object for the attribute '{@link top.artifact.Artifact#getDate <em>Date</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Date</em>'.
* @see top.artifact.Artifact#getDate()
* @see #getArtifact()
* @generated
*/
EAttribute getArtifact_Date();
/**
* Returns the meta object for class '{@link top.artifact.ArtifactAssetRelationship <em>Artifact Asset Relationship</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Artifact Asset Relationship</em>'.
* @see top.artifact.ArtifactAssetRelationship
* @generated
*/
EClass getArtifactAssetRelationship();
/**
* Returns the meta object for the reference list '{@link top.artifact.ArtifactAssetRelationship#getSource <em>Source</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Source</em>'.
* @see top.artifact.ArtifactAssetRelationship#getSource()
* @see #getArtifactAssetRelationship()
* @generated
*/
EReference getArtifactAssetRelationship_Source();
/**
* Returns the meta object for the reference list '{@link top.artifact.ArtifactAssetRelationship#getTarget <em>Target</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Target</em>'.
* @see top.artifact.ArtifactAssetRelationship#getTarget()
* @see #getArtifactAssetRelationship()
* @generated
*/
EReference getArtifactAssetRelationship_Target();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
Artifact_Factory getArtifact_Factory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactGroupImpl <em>Artifact Group</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactGroupImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactGroup()
* @generated
*/
EClass ARTIFACT_GROUP = eINSTANCE.getArtifactGroup();
/**
* The meta object literal for the '<em><b>Artifact Element</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_GROUP__ARTIFACT_ELEMENT = eINSTANCE.getArtifactGroup_ArtifactElement();
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactPackageImpl <em>Artifact Package</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactPackageImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactPackage()
* @generated
*/
EClass ARTIFACT_PACKAGE = eINSTANCE.getArtifactPackage();
/**
* The meta object literal for the '<em><b>Artifact Element</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_PACKAGE__ARTIFACT_ELEMENT = eINSTANCE.getArtifactPackage_ArtifactElement();
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactPackageBindingImpl <em>Artifact Package Binding</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactPackageBindingImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactPackageBinding()
* @generated
*/
EClass ARTIFACT_PACKAGE_BINDING = eINSTANCE.getArtifactPackageBinding();
/**
* The meta object literal for the '<em><b>Participant Package</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_PACKAGE_BINDING__PARTICIPANT_PACKAGE = eINSTANCE.getArtifactPackageBinding_ParticipantPackage();
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactPackageInterfaceImpl <em>Artifact Package Interface</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactPackageInterfaceImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactPackageInterface()
* @generated
*/
EClass ARTIFACT_PACKAGE_INTERFACE = eINSTANCE.getArtifactPackageInterface();
/**
* The meta object literal for the '<em><b>Implements</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_PACKAGE_INTERFACE__IMPLEMENTS = eINSTANCE.getArtifactPackageInterface_Implements();
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactAssetImpl <em>Artifact Asset</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactAssetImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactAsset()
* @generated
*/
EClass ARTIFACT_ASSET = eINSTANCE.getArtifactAsset();
/**
* The meta object literal for the '<em><b>Artifact Property</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_ASSET__ARTIFACT_PROPERTY = eINSTANCE.getArtifactAsset_ArtifactProperty();
/**
* The meta object literal for the '{@link top.artifact.impl.PropertyImpl <em>Property</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.PropertyImpl
* @see top.artifact.impl.Artifact_PackageImpl#getProperty()
* @generated
*/
EClass PROPERTY = eINSTANCE.getProperty();
/**
* The meta object literal for the '{@link top.artifact.impl.TechniqueImpl <em>Technique</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.TechniqueImpl
* @see top.artifact.impl.Artifact_PackageImpl#getTechnique()
* @generated
*/
EClass TECHNIQUE = eINSTANCE.getTechnique();
/**
* The meta object literal for the '{@link top.artifact.impl.ParticipantImpl <em>Participant</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ParticipantImpl
* @see top.artifact.impl.Artifact_PackageImpl#getParticipant()
* @generated
*/
EClass PARTICIPANT = eINSTANCE.getParticipant();
/**
* The meta object literal for the '{@link top.artifact.impl.ActivityImpl <em>Activity</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ActivityImpl
* @see top.artifact.impl.Artifact_PackageImpl#getActivity()
* @generated
*/
EClass ACTIVITY = eINSTANCE.getActivity();
/**
* The meta object literal for the '<em><b>Start Time</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ACTIVITY__START_TIME = eINSTANCE.getActivity_StartTime();
/**
* The meta object literal for the '<em><b>End Time</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ACTIVITY__END_TIME = eINSTANCE.getActivity_EndTime();
/**
* The meta object literal for the '{@link top.artifact.impl.EventImpl <em>Event</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.EventImpl
* @see top.artifact.impl.Artifact_PackageImpl#getEvent()
* @generated
*/
EClass EVENT = eINSTANCE.getEvent();
/**
* The meta object literal for the '<em><b>Occurence</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute EVENT__OCCURENCE = eINSTANCE.getEvent_Occurence();
/**
* The meta object literal for the '{@link top.artifact.impl.ResourceImpl <em>Resource</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ResourceImpl
* @see top.artifact.impl.Artifact_PackageImpl#getResource()
* @generated
*/
EClass RESOURCE = eINSTANCE.getResource();
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactImpl <em>Artifact</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifact()
* @generated
*/
EClass ARTIFACT = eINSTANCE.getArtifact();
/**
* The meta object literal for the '<em><b>Version</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ARTIFACT__VERSION = eINSTANCE.getArtifact_Version();
/**
* The meta object literal for the '<em><b>Date</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ARTIFACT__DATE = eINSTANCE.getArtifact_Date();
/**
* The meta object literal for the '{@link top.artifact.impl.ArtifactAssetRelationshipImpl <em>Artifact Asset Relationship</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see top.artifact.impl.ArtifactAssetRelationshipImpl
* @see top.artifact.impl.Artifact_PackageImpl#getArtifactAssetRelationship()
* @generated
*/
EClass ARTIFACT_ASSET_RELATIONSHIP = eINSTANCE.getArtifactAssetRelationship();
/**
* The meta object literal for the '<em><b>Source</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_ASSET_RELATIONSHIP__SOURCE = eINSTANCE.getArtifactAssetRelationship_Source();
/**
* The meta object literal for the '<em><b>Target</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ARTIFACT_ASSET_RELATIONSHIP__TARGET = eINSTANCE.getArtifactAssetRelationship_Target();
}
} //Artifact_Package
| 28.233102 | 148 | 0.640496 |
9e78724f0fbd90df7dfa60b3c9e7f49893143d06 | 2,286 | package com.hrLDA.doc;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class StripXLSContent extends Document{
public StripXLSContent(){}
/**
*
* @param .xls file
* @return text content
* @throws IOException
*/
public StripXLSContent readContent(File file){
try{
StringBuffer stringBuffer = new StringBuffer();
FileInputStream is=new FileInputStream(file);
HSSFWorkbook wbHssfWorkbook=new HSSFWorkbook(new POIFSFileSystem(is));
//open excel
HSSFSheet sheet=wbHssfWorkbook.getSheetAt(0);
HSSFRow row=null;
String cell;
// fetch data from each row
for (int i = 0; i <=sheet.getLastRowNum(); i++) {
row =sheet.getRow(i);
// fetch data from each coloum
for (int j = 0; j <= row.getLastCellNum(); j++) {
if (row.getCell(j) != null){
cell = row.getCell(j).toString();
// append the text when it contains English letters
if (cell.matches("[\\p{L}_\\s]+") && !cell.matches("\\s+")){
stringBuffer.append(cell+"\n");
}
}
}// end of for (int j = 0; j <= row.getLastCellNum(); j++) {
}// end of for (int i = 0; i <=sheet.getLastRowNum(); i++) {
if (!stringBuffer.toString().matches("")){
this.setCont(stringBuffer.toString());
return this;
}else return null;
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
Document stripXLSContent = new StripXLSContent();
File file = new File ("/Users/xiaofengzhu/Documents/Intel/Materials/wikippts/Wiki0/testXls.xls");
stripXLSContent.readContent(file);
System.out.println(stripXLSContent.getCont());
}
}
| 32.197183 | 100 | 0.547244 |
ab378871f6726850f8677bf45dac2f1d93aedaad | 778 | package chapter2.project;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class CountWords {
public static HashMap<String, Integer> counts(List<String> listString){
HashMap<String, Integer> retHashMap = new HashMap<String, Integer>();
for (String text : listString) {
Integer count = retHashMap.get(text);
if (count == null) {
retHashMap.put(text, 1);
} else {
retHashMap.put(text, count.intValue() + 1);
}
}
return retHashMap;
}
public static void main(String[] args) {
Scanner sIn = new Scanner(System.in).useDelimiter("\r\n");
String data = sIn.next();
List<String> listData = Arrays.asList(data.split(" "));
System.out.println(counts(listData));
sIn.close();
}
}
| 24.3125 | 72 | 0.683805 |
bfb1b1bf1ba5c9743db28ed48acce59a32de43ee | 1,862 | package br.com.caelum.eventos.dominio;
import static java.util.Arrays.asList;
import java.util.List;
public class Agenda {
private final ListaDePalestras listaDePalestras;
public Agenda(ListaDePalestras palestras){
this.listaDePalestras = palestras;
}
public List<Trilha> prepararTrilhas() {
SessaoDaManha umaSessaoDaManha = new SessaoDaManha();
SessaoDaManha outraSessaoDaManha = new SessaoDaManha();
SessaoDaTarde umaSessaoDaTarde = new SessaoDaTarde();
SessaoDaTarde outraSessaoDaTarde = new SessaoDaTarde();
adicionarPalestrasSePossivel(umaSessaoDaManha, listaDePalestras);
adicionarPalestrasSePossivel(outraSessaoDaManha, listaDePalestras);
adicionarPalestrasSePossivel(umaSessaoDaTarde, listaDePalestras);
adicionarPalestrasSePossivel(outraSessaoDaTarde, listaDePalestras);
final String nomeDaTrilha1 = "PaPo ReTo";
Trilha trilha1 = new Trilha(nomeDaTrilha1, umaSessaoDaManha, umaSessaoDaTarde);
String nomeDaTrilha2 = "DiGiTal";
Trilha trilha2 = new Trilha(nomeDaTrilha2, outraSessaoDaManha, outraSessaoDaTarde);
return asList(trilha1, trilha2);
}
private void adicionarPalestrasSePossivel(Sessao sessao, ListaDePalestras palestras){
boolean sessaoOk = false;
while(!sessaoOk){
sessaoOk = adicionarPalestras(sessao, palestras);
if(!sessaoOk){
ListaDePalestras palestrasCanceladas = sessao.cancelar();
palestras.devolver(palestrasCanceladas);
palestras.embaralhar();
}
}
}
private boolean adicionarPalestras(Sessao sessao, ListaDePalestras listaDePalestras){
boolean adicionou = true;
while(adicionou && !listaDePalestras.estaVazia()){
Palestra novaPalestra = listaDePalestras.obterProxima();
adicionou = sessao.adicionar(novaPalestra);
if(!adicionou){
listaDePalestras.devolver(novaPalestra);
}
}
return sessao.estaDevidamentePreenchida();
}
}
| 31.559322 | 86 | 0.782492 |
8fb8ad2c7f4482109e8167393ac6faca45f50ef1 | 211 | package com.github.jszeluga.generators;
public abstract class AbstractGenerator<T> implements Generator<T> {
@Override
public void initialize() throws Exception {
//stub implementation
}
}
| 21.1 | 68 | 0.720379 |
4f9613665686796ce0bf11e6ecab4179e3ec83da | 309 | package com.app;
import org.junit.Test;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertTrue;
@WebAppConfiguration
public class AppTests extends BaseTest {
@Test
public void contextLoads() {
assertTrue("Context Loads", true);
}
}
| 18.176471 | 64 | 0.7411 |
0eccc9f741758cd18207fea2e67bb009e5529f17 | 1,341 | /*
* @lc app=leetcode.cn id=836 lang=java
*
* [836] 矩形重叠
*/
// @lc code=start
class Solution {
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
Rectangle recA = new Rectangle(rec1);
Rectangle recB = new Rectangle(rec2);
if (recA.isValid() || recB.isValid()) {
return false;
}
Rectangle left = Rectangle.getLeft(recA, recB);
Rectangle right = Rectangle.getRight(recA, recB);
// 两个矩形水平无交集 必定不相交
if (left.rightX <= right.leftX) {
return false;
}
// 水平有交集 但垂直无交集
if (right.bottomY >= left.topY || right.topY <= left.bottomY) {
return false;
}
return true;
}
}
class Rectangle {
final int leftX, bottomY, rightX, topY;
Rectangle(int[] rec) {
this.leftX = rec[0];
this.bottomY = rec[1];
this.rightX = rec[2];
this.topY = rec[3];
}
// 获取两个矩形中左边的矩形
static Rectangle getLeft(Rectangle r1, Rectangle r2) {
return r1.leftX < r2.leftX ? r1 : r2;
}
// 获取两个矩形中右边的矩形
static Rectangle getRight(Rectangle r1, Rectangle r2) {
return r1.leftX < r2.leftX ? r2 : r1;
}
// 矩形是否有效
boolean isValid() {
return this.rightX <= this.leftX || this.topY <= this.bottomY;
}
}
// @lc code=end
| 21.629032 | 71 | 0.552573 |
c61eea0baf7111986bf9f5ef840c0b6ee1835ff4 | 939 | package PruebasColecciones;
import java.util.ArrayList;
/**
* Material del libro Big Java, Student Edition - http://bcs.wiley.com/he-bcs/Books?action=sitemap&itemId=0471697036&bcsId=2291
* ¡Lo tenéis en la biblioteca!
*
This program tests the ArrayList class.
*/
public class ArrayListTester
{
public static void main(String[] args)
{
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
accounts.add(new BankAccount(1001));
accounts.add(new BankAccount(1015));
accounts.add(new BankAccount(1729));
accounts.add(1, new BankAccount(1008));
accounts.remove(0);
System.out.println("size=" + accounts.size());
BankAccount first = accounts.get(0);
System.out.println("first account number=" + first.getAccountNumber());
BankAccount last = accounts.get(accounts.size() - 1);
System.out.println("last account number=" + last.getAccountNumber());
}
}
| 32.37931 | 127 | 0.691161 |
0f8b5aecfc9f54a3cc32389f589980ff61b6e5a4 | 1,811 | package multithreading.threads;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
/**
* @author Bischev Ramil
* @since 2020-06-10
* Download file with speed limit.
* Limit on bytes.
*/
public class Wget {
public static void main(String[] args) {
String file = args[0];
int speed = Integer.parseInt(args[1]);
new Wget().download(file, speed);
}
private void download(String file, int speed) {
try (BufferedInputStream in = new BufferedInputStream(new URL(file).openStream());
FileOutputStream fileOutputStream = new FileOutputStream("pom_temp.xml")) {
byte[] dataBuffer = new byte[speed];
int bytesRead;
long startDownload = System.currentTimeMillis();
int downloaded = 0;
long startForOutput = startDownload;
long endForOutput = 0;
while ((bytesRead = in.read(dataBuffer, 0, speed)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
long timeOfDownload = System.currentTimeMillis();
endForOutput = timeOfDownload;
downloaded += bytesRead;
if (timeOfDownload - startDownload < 1000) {
try {
Thread.sleep(1000 - (timeOfDownload - startDownload));
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
startDownload = System.currentTimeMillis();
}
System.out.format("Скачано %d байт за %d секунд", downloaded, (endForOutput - startForOutput) / 1000);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 36.22 | 114 | 0.575925 |
922b096108d81a548a8bba1bb9d50498090f095c | 1,251 | package com.hencoder.hencoderpracticedraw2.practice;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class Practice09StrokeCapView extends View {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Practice09StrokeCapView(Context context) {
super(context);
}
public Practice09StrokeCapView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public Practice09StrokeCapView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
paint.setStrokeWidth(40);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 使用 Paint.setStrokeCap() 来设置端点形状
// 第一个:BUTT
paint.setStrokeCap(Paint.Cap.BUTT);
canvas.drawLine(50, 50, 400, 50, paint);
// 第二个:ROUND
paint.setStrokeCap(Paint.Cap.ROUND);
canvas.drawLine(50, 150, 400, 150, paint);
// 第三个:SQUARE
paint.setStrokeCap(Paint.Cap.SQUARE);
canvas.drawLine(50, 250, 400, 250, paint);
}
}
| 26.0625 | 101 | 0.678657 |
913d094134c634aa0aa4b5dd06d9403febbcfd65 | 4,543 | package __orm__;
public class Constants {
public static final String DEVICE_STATE_IDLE = "i";
public static final String DEVICE_STATE_LOCKED = "l";
public static final String DEVICE_STATE_RUNNING = "r";
public static final String DEVICE_STATE_ERROR = "e";
public static final String DEVICE_STATE_DONE = "d";
/**
* 任务状态
*/
public static final String TASK_STATE_INIT = "i";
public static final String TASK_STATE_ERROR = "e";
public static final String TASK_STATE_DONE = "d";
/**
* 任务范围
*/
public static final String TASK_SCOPE_EXTERNAL = "1";
public static final String TASK_SCOPE_INTERNAL = "2";
public static final String TASK_SCOPE_NORMAL = "3";
/**
* 匹配度最大值
*/
public static final int IRIS_MATCH_MAX = 16384;
/**
* 匹配度合格值
*/
public static final int IRIS_MATCH_OK = 6225;
/**
* 客户模版书计算倍数
*/
public static final int CLIENT_IRIS_CAPACITY_SIZE = 1000;
/**
* 每次数据库的数目
*/
public static final int DEFAULT_DB_PAGESIZE_PERLOAD = 1000;
/**
* 最大队列循环
*/
public static final int DEFAULT_QUEUE_MAX_SIZE = 1000;
/**
* 队列事件间隔
*/
public static final int DEFAULT_QUEUE_SLEEP_MICRO_SECOND = 10;
public static final int DEFAULT_TOMCAT_PORT = 8080;
/**
* 默认队列值
*/
public static final int QUEUE_TICKET_SIZE = 1000;
public static final String E_CODE_OK = "ok";//无错误
public static final String E_CODE_UNKNOWN = "E0000";//未知错误
// public static final String E_CODE_TIMEOUT = "E0001";//操作超时
public static final String E_CODE_NEED_LOGIN = "E0001";//操作超时
public static final String E_CODE_FORM = "E0010";//表单错误
public static final String E_CODE_CACHE = "E0011";//
public static final String E_CODE_PARAM = "E0012";//
public static final String E_CODE_ROLE = "E0014";//用户无权限
public static final String E_CODE_PARAM_UID = "E0011";//操作客户ID
public static final String E_CODE_PARAM_SIGN = "E0012";//操作签名
public static final String E_CODE_PARAM_TOKEN = "E0013";//需要token
public static final String E_CODE_PARAM_DEV = "E0014";//需要设备号
public static final String E_CODE_PARAM_DATA = "E0015";//需要模版文件
public static final String E_CODE_PARAM_IMG = "E0016";//需要图像文件
public static final String E_CODE_PARAM_UNKNOWN = "E0099";//未知参数
public static final String E_CODE_TASK_UNKNOWN = "E0100";//未知后端任务错误
public static final String E_CODE_TASK_TOKEN = "E0101";//获取TOKEN有误
public static final String E_CODE_TASK_ENCODE = "E0102";//编码错误
public static final String E_CODE_TASK_MATCH = "E0103";//比对错误
public static final String E_CODE_NO_DEVICE = "E1001";//无有效设备
public static final String E_CODE_NO_DATA = "E1002";//无有效数据
public static final String E_CODE_NO_UID = "E1003";//无有效数据
public static final String E_CODE_NO_TYPE = "E1004";//无有效任务授权
public static final String E_CODE_DISPATCH = "E1005";//无法分发任务
public static final String E_CODE_CLIENT_UNAUTH = "E2000";//客户未授权
public static final String E_CODE_APP_UNAUTH = "E2001";//应用未授权
public static final String E_CODE_CLIENT_IRIS_FULL = "E2002";//数据达到上限
public static final String E_CODE_CLIENT_PERSON_FULL = "E2003";//人数达到上限
public static final String DB_ORACLE = "ORACLE";//
public static final String DB_MYSQL = "MYSQL";//
public static final String DB_SQLSERVER = "SQLSERVER";//
public static final String DB_SQLITE = "SQLITE";//
/**
* 返回结果分离器
*/
public static String SP_TASK_RESULT_DATA_0 = "@@";
public static String SP_TASK_RESULT_DATA_1 = "##";
public static String SP_TASK_RESULT_UID = ",";
public static String SP_DATE = "-";
public static String SP_DEV_ID = "_";
public static final String LOGIN_ID = "__hs_login_sess__";
public static final String ROLE_ADMIN = "admin";//高级管理员
public static final String ROLE_STAFF = "staff";//普通操作员
public static final String ROLE_GUEST = "guest";//访客
public static final String LOG_TYPE_LOGIN = "login";//登陆
public static final String LOG_TYPE_ADD = "add";//添加资源
public static final String LOG_TYPE_EDIT = "update";//编辑资源
public static final String LOG_TYPE_DELETE = "delete";//删除资源
/**
* 默认的客户和应用
*/
public static final String DEFAULT_CLIENT_ID = "default_client";
public static final String DEFAULT_APP_ID = "default_app";
public static final String RKEY_IDX = "hsrq_";//
public static final String RKEY_TOKEN_SEED = "hsts_";//
}
| 32.219858 | 75 | 0.691834 |
cbc17b295fffeb74caac9eb3477e3f732870924a | 2,299 | /** Copyright by Barry G. Becker, 2000-2011. Licensed under MIT License: http://www.opensource.org/licenses/MIT */
package com.barrybecker4.game.twoplayer.common.search.strategy.integration;
import com.barrybecker4.game.twoplayer.common.TwoPlayerMove;
import com.barrybecker4.game.twoplayer.common.search.Progress;
/**
* The expected moves for a given game for each combination of game progress and player.
* @author Barry Becker
*/
public class ExpectedMoveMatrix {
private MoveInfo beginningP1;
private MoveInfo beginningP2;
private MoveInfo middleP1;
private MoveInfo middleP2;
private MoveInfo endP1;
private MoveInfo endP2;
public ExpectedMoveMatrix(MoveInfo beginningPlayer1, MoveInfo beginningPlayer2,
MoveInfo middlePlayer1, MoveInfo middlePlayer2,
MoveInfo endPlayer1, MoveInfo endPlayer2) {
beginningP1 = beginningPlayer1;
beginningP2 = beginningPlayer2;
middleP1 = middlePlayer1;
middleP2 = middlePlayer2;
endP1 = endPlayer1;
endP2 = endPlayer2;
}
/**
* Use this constructor if you do not have the numMovesConsidered info to include.
*/
public ExpectedMoveMatrix(TwoPlayerMove beginningPlayer1, TwoPlayerMove beginningPlayer2,
TwoPlayerMove middlePlayer1, TwoPlayerMove middlePlayer2,
TwoPlayerMove endPlayer1, TwoPlayerMove endPlayer2) {
beginningP1 = new MoveInfo(beginningPlayer1);
beginningP2 = new MoveInfo(beginningPlayer2);
middleP1 = new MoveInfo(middlePlayer1);
middleP2 = new MoveInfo(middlePlayer2);
endP1 = new MoveInfo(endPlayer1);
endP2 = new MoveInfo(endPlayer2);
}
public MoveInfo getExpectedMove(Progress progress, boolean player1) {
MoveInfo expectedMove = null;
switch (progress) {
case BEGINNING :
expectedMove = player1 ? beginningP1 : beginningP2;
break;
case MIDDLE :
expectedMove = player1 ? middleP1 : middleP2;
break;
case END :
expectedMove = player1 ? endP1 : endP2;
break;
}
return expectedMove;
}
}
| 37.080645 | 115 | 0.648543 |
0999a1b1a08fb41a2ef53264d89c2f65642a2c17 | 9,550 | package edu.ithaca;
import java.util.*;
import edu.ithaca.QualatativeStats.*;
public class EnemyRecommenderReflex {
public Enemy recommendEnemy(Party party){
//QUANT STAT: moveSpeed, AC, hp, con, str, wis, intel, dex, cha
int partySize = party.getPartySize();
int combinedMS = 0;
int combinedAC = 0;
int combinedHP = 0;
int combinedCON = 0;
int combinedSTR = 0;
int combinedWIS = 0;
int combinedINTEL = 0;
int combinedDEX = 0;
int combinedCHA = 0;
for (int i = 0; i <= party.getPartySize()-1; i++){
PartyMember curMember = party.getCharacter(i);
combinedMS += curMember.getMoveSpeed();
combinedAC += curMember.getArmorClass();
combinedHP += curMember.getHP();
combinedCON += curMember.getCon();
combinedSTR += curMember.getStr();
combinedWIS += curMember.getWis();
combinedINTEL += curMember.getIntel();
combinedDEX += curMember.getDex();
combinedCHA += curMember.getCha();
}
combinedMS = combinedMS/partySize;
combinedAC = combinedAC/partySize;
combinedHP = combinedHP/partySize;
combinedCON = combinedCON/partySize;
combinedSTR = combinedSTR/partySize;
combinedWIS = combinedWIS/partySize;
combinedINTEL = combinedINTEL/partySize;
combinedDEX = combinedDEX/partySize;
combinedCHA = combinedCHA/partySize;
//Small Enemy Database
ArrayList<Enemy> possibleEnemies = new ArrayList<>();
ArrayList<QualatativeStats> possibleEnemiesQuals = new ArrayList<>();
Enemy yeti = new Enemy(false, false, Terrain.ARCTIC, MovementType.GROUND, null, null);
QualatativeStats qualYeti = new QualatativeStats(Alignment.LAWFULEVIL, Size.LARGE, "Yeti, Undercommon", ',');
possibleEnemies.add(yeti);
possibleEnemiesQuals.add(qualYeti);
Enemy aarakocra = new Enemy(false, false, Terrain.MOUNTAIN, MovementType.FLY, null, null);
QualatativeStats qualAarakocra = new QualatativeStats(Alignment.LAWFULEVIL, Size.LARGE, "Auran, Common", ',');
possibleEnemies.add(aarakocra);
possibleEnemiesQuals.add(qualAarakocra);
Enemy dragon = new Enemy(false, true, Terrain.MOUNTAIN, MovementType.FLY, null, null);
QualatativeStats qualDragon = new QualatativeStats(Alignment.NEUTRALEVIL, Size.HUGE, "Draconic", ',');
possibleEnemies.add(dragon);
possibleEnemiesQuals.add(qualDragon);
Enemy owlbear = new Enemy(false, false, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualOwlbear = new QualatativeStats(Alignment.LAWFULEVIL, Size.MEDIUM, "None", ',');
possibleEnemies.add(owlbear);
possibleEnemiesQuals.add(qualOwlbear);
Enemy gelatinousCube = new Enemy(false, false, Terrain.GRASSLAND, MovementType.GROUND, null, null);
QualatativeStats qualgelatinousCube = new QualatativeStats(Alignment.TRUENEUTRAL, Size.MEDIUM, "None", ',');
possibleEnemies.add(gelatinousCube);
possibleEnemiesQuals.add(qualgelatinousCube);
Enemy beholder = new Enemy(false, true, Terrain.UNDERDARK, MovementType.FLY, null, null);
QualatativeStats qualBeholder = new QualatativeStats(Alignment.LAWFULEVIL, Size.LARGE, "Beholder, Undercommon", ',');
possibleEnemies.add(beholder);
possibleEnemiesQuals.add(qualBeholder);
Enemy aboleth = new Enemy(false, false, Terrain.COAST, MovementType.SWIM, null, null);
QualatativeStats qualAboleth = new QualatativeStats(Alignment.LAWFULEVIL, Size.GARGANTUAN, "Aboleth, Aquan, Deep speech", ',');
possibleEnemies.add(aboleth);
possibleEnemiesQuals.add(qualAboleth);
Enemy banshee = new Enemy(false, false, Terrain.UNDERDARK, MovementType.FLY, null, null);
QualatativeStats qualBanshee = new QualatativeStats(Alignment.LAWFULEVIL, Size.MEDIUM, "Common, Elvish", ',');
possibleEnemies.add(banshee);
possibleEnemiesQuals.add(qualBanshee);
Enemy bandit = new Enemy(true, false, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualBandit = new QualatativeStats(Alignment.CHAOTICEVIL, Size.MEDIUM, "Common", ',');
possibleEnemies.add(bandit);
possibleEnemiesQuals.add(qualBandit);
Enemy goblin = new Enemy(false, false, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualGoblin = new QualatativeStats(Alignment.LAWFULEVIL, Size.SMALL, "Ghukliak", ',');
possibleEnemies.add(goblin);
possibleEnemiesQuals.add(qualGoblin);
Enemy orc = new Enemy(false, false, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualOrc = new QualatativeStats(Alignment.LAWFULEVIL, Size.LARGE, "Orcish, Common", ',');
possibleEnemies.add(orc);
possibleEnemiesQuals.add(qualOrc);
Enemy zombie = new Enemy(false, false, Terrain.UNDERDARK, MovementType.GROUND, null, null);
QualatativeStats qualZombie= new QualatativeStats(Alignment.NEUTRALEVIL, Size.MEDIUM, "None", ',');
possibleEnemies.add(zombie);
possibleEnemiesQuals.add(qualZombie);
Enemy werewolf = new Enemy(false, false, Terrain.MOUNTAIN, MovementType.GROUND, null, null);
QualatativeStats qualWerewolf = new QualatativeStats(Alignment.NEUTRALEVIL, Size.MEDIUM, "Common", ',');
possibleEnemies.add(werewolf);
possibleEnemiesQuals.add(qualWerewolf);
Enemy giantRat = new Enemy(false, false, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualGiantRat = new QualatativeStats(Alignment.NEUTRALEVIL, Size.SMALL, "None", ',');
possibleEnemies.add(giantRat);
possibleEnemiesQuals.add(qualGiantRat);
Enemy arachnid = new Enemy(false, false, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualArachnid = new QualatativeStats(Alignment.NEUTRALEVIL, Size.SMALL, "None", ',');
possibleEnemies.add(arachnid);
possibleEnemiesQuals.add(qualArachnid);
Enemy rustMonster = new Enemy(false, false, Terrain.SWAMP, MovementType.GROUND, null, null);
QualatativeStats qualRustMonster = new QualatativeStats(Alignment.LAWFULEVIL, Size.MEDIUM, "Undercommon", ',');
possibleEnemies.add(rustMonster);
possibleEnemiesQuals.add(qualRustMonster);
Enemy cultist = new Enemy(true, true, Terrain.FOREST, MovementType.GROUND, null, null);
QualatativeStats qualCultist = new QualatativeStats(Alignment.LAWFULEVIL, Size.MEDIUM, "Common", ',');
possibleEnemies.add(cultist);
possibleEnemiesQuals.add(qualCultist);
//Randomly choose from the enemy database
int rnd = new Random().nextInt(possibleEnemies.size());
Enemy chosenEnemy = possibleEnemies.get(rnd);
QualatativeStats chosenQuals = possibleEnemiesQuals.get(rnd);
EnemyQuantStats enemyQuant = new EnemyQuantStats(6, 30, combinedMS, combinedAC, combinedHP, combinedCON, combinedSTR, combinedWIS, combinedINTEL, combinedDEX, combinedCHA);
Enemy recommendedEnemy = new Enemy(chosenEnemy.getIsHumanoid(), chosenEnemy.getIsMagicUser(), chosenEnemy.getTerrain(), chosenEnemy.getMovementType(), chosenQuals, enemyQuant);
return recommendedEnemy;
}
public void main(String args[]){
QuantativeStats quantKemi = new QuantativeStats(30, 17, 32, 15, 17, 11, 12, 10, 15);
QualatativeStats qualKemi = new QualatativeStats(Alignment.LAWFULGOOD, Size.MEDIUM, "common, elvish, sylvan", ',');
QuantativeStats quantEmma = new QuantativeStats(1, 2, 3, 4, 5, 6, 7, 8, 9);
QualatativeStats qualEmma = new QualatativeStats(Alignment.CHAOTICGOOD, Size.TINY, "common, elvish", ',');
QuantativeStats quantKelsey = new QuantativeStats(25, 14, 13, 14, 13, 11, 13, 14, 9);
QualatativeStats qualKelsey = new QualatativeStats(Alignment.CHAOTICNEUTRAL, Size.LARGE, "celestial, common", ',');
QuantativeStats quantToby = new QuantativeStats(20, 12, 11, 8, 10, 13, 12, 13, 16);
QualatativeStats qualToby = new QualatativeStats(Alignment.CHAOTICEVIL, Size.SMALL, "common, draconic", ',');
ArrayList<PartyMember> characters = new ArrayList<>();
PartyMember kemi = new PartyMember("kemi", CharacterClass.BARD, CharacterRace.ELF, qualKemi, quantKemi);
PartyMember emma = new PartyMember("emma", CharacterClass.PALADIN, CharacterRace.HALFELF, qualEmma, quantEmma);
PartyMember kelsey = new PartyMember("kelsey", CharacterClass.DRUID, CharacterRace.HALFORC, qualKelsey, quantKelsey);
PartyMember toby = new PartyMember("toby", CharacterClass.WIZARD, CharacterRace.DRAGONBORNE, qualToby, quantToby);
characters.add(kemi);
characters.add(emma);
characters.add(kelsey);
characters.add(toby);
Party newParty = new Party(characters, characters.size());
Enemy recommendedEnemy1 = recommendEnemy(newParty);
Enemy recommendedEnemy2 = recommendEnemy(newParty);
Enemy recommendedEnemy3 = recommendEnemy(newParty);
System.out.println("Here are three recommended enemies: " + "\n" );
System.out.println(recommendedEnemy1 + "\n");
System.out.println(recommendedEnemy2 + "\n");
System.out.println(recommendedEnemy3 + "\n");
}
}
| 50.263158 | 184 | 0.686597 |
3d897e343a0af0fa754f26958ad879512426f8c8 | 62,164 | package org.opensrp.web.rest;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.http.entity.ContentType;
import org.hamcrest.core.StringStartsWith;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.opensrp.TestFileContent;
import org.opensrp.domain.IdVersionTuple;
import org.opensrp.domain.Manifest;
import org.opensrp.domain.postgres.ClientForm;
import org.opensrp.domain.postgres.ClientFormMetadata;
import org.opensrp.service.ClientFormService;
import org.opensrp.service.ManifestService;
import org.opensrp.util.DateTimeDeserializer;
import org.opensrp.util.DateTimeSerializer;
import org.opensrp.web.Constants;
import org.opensrp.web.config.security.filter.CrossSiteScriptingPreventionFilter;
import org.opensrp.web.rest.it.TestWebContextLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.server.MockMvc;
import org.springframework.test.web.server.MvcResult;
import org.springframework.test.web.server.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;
@RunWith (SpringJUnit4ClassRunner.class)
@ContextConfiguration (loader = TestWebContextLoader.class, locations = {"classpath:test-webmvc-config.xml",})
@ActiveProfiles (profiles = { "jedis", "postgres", "basic_auth" })
public class ClientFormResourceTest {
@Autowired
protected WebApplicationContext webApplicationContext;
@SuppressWarnings("deprecation")
protected ObjectMapper mapper = new ObjectMapper().enableDefaultTyping();
private MockMvc mockMvc;
private ClientFormService clientFormService;
private ManifestService manifestService;
private final String BASE_URL = "/rest/clientForm/";
@Before
public void setUp() {
clientFormService = mock(ClientFormService.class);
manifestService = mock(ManifestService.class);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setDateFormat(DateFormat.getDateTimeInstance());
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
clientFormResource.setClientFormService(clientFormService, manifestService);
clientFormResource.setObjectMapper(mapper);
mockMvc = MockMvcBuilders.webApplicationContextSetup(webApplicationContext).
addFilter(new CrossSiteScriptingPreventionFilter(), "/*").build();
SimpleModule dateTimeModule = new SimpleModule("DateTimeModule");
dateTimeModule.addDeserializer(DateTime.class, new DateTimeDeserializer());
dateTimeModule.addSerializer(DateTime.class, new DateTimeSerializer());
mapper.registerModule(dateTimeModule);
}
@Test
public void testSearchForFormByFormVersionShouldReturnSpecificJsonFormVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.0.3";
String currentFormVersion = "0.0.1";
ClientForm clientForm = new ClientForm();
clientForm.setJson("{}");
clientForm.setId(3L);
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(clientFormService.isClientFormExists(formIdentifier, false)).thenReturn(true);
when(clientFormService.getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, false)).thenReturn(clientFormMetadata);
when(clientFormService.getClientFormById(3L)).thenReturn(clientForm);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("current_form_version", currentFormVersion)
.param("strict", "true"))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
JsonNode jsonNode = mapper.readTree(responseString);
assertEquals("{}", jsonNode.get("clientForm").get("json").textValue());
assertEquals("opd/reg.json", jsonNode.get("clientFormMetadata").get("identifier").textValue());
assertEquals("0.0.3", jsonNode.get("clientFormMetadata").get("version").textValue());
}
@Test
public void testSearchForFormByFormVersionShouldReturnSpecificJsonValidatorVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.0.3";
String currentFormVersion = "0.0.1";
ClientForm clientForm = new ClientForm();
clientForm.setJson("{}");
clientForm.setId(3L);
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIsJsonValidator(true);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(clientFormService.isClientFormExists(formIdentifier, true)).thenReturn(true);
when(clientFormService.getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, true)).thenReturn(clientFormMetadata);
when(clientFormService.getClientFormById(3L)).thenReturn(clientForm);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("current_form_version", currentFormVersion)
.param("strict", "true")
.param("is_json_validator", "true"))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
JsonNode jsonNode = mapper.readTree(responseString);
assertEquals("{}", jsonNode.get("clientForm").get("json").textValue());
assertEquals("opd/reg.json", jsonNode.get("clientFormMetadata").get("identifier").textValue());
assertEquals("0.0.3", jsonNode.get("clientFormMetadata").get("version").textValue());
}
@Test
public void testSearchForFormByFormVersionShouldReturnNoContentWhenVersionHasntChangedAndStrictIsTrue() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String currentFormVersion = "0.0.3";
List<IdVersionTuple> idVersionTuples = new ArrayList<>();
idVersionTuples.add(new IdVersionTuple(1, "0.0.1"));
idVersionTuples.add(new IdVersionTuple(2, "0.0.2"));
idVersionTuples.add(new IdVersionTuple(3, "0.0.3"));
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(clientFormService.isClientFormExists(formIdentifier, false)).thenReturn(true);
when(clientFormService.getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, false)).thenReturn(null);
when(clientFormService.getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, false)).thenReturn(idVersionTuples);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("strict", "True")
.param("current_form_version", currentFormVersion))
.andExpect(status().isNoContent())
.andReturn();
String responseString = result.getResponse().getContentAsString();
assertEquals("", responseString);
}
@Test
public void testSearchForFormByFormVersionShouldReturn404WhenStrictIsTrueAndCurrentFormVersionIsOutOfDate() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String currentFormVersion = "0.0.2";
List<IdVersionTuple> idVersionTuples = new ArrayList<>();
idVersionTuples.add(new IdVersionTuple(1, "0.0.1"));
idVersionTuples.add(new IdVersionTuple(2, "0.0.2"));
idVersionTuples.add(new IdVersionTuple(3, "0.0.3"));
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(clientFormService.isClientFormExists(formIdentifier, false)).thenReturn(true);
when(clientFormService.getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, false)).thenReturn(null);
when(clientFormService.getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, false)).thenReturn(idVersionTuples);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("strict", "True")
.param("current_form_version", currentFormVersion))
.andExpect(status().isNotFound())
.andReturn();
assertEquals("", result.getResponse().getContentAsString());
verify(clientFormService).isClientFormExists(formIdentifier, false);
verify(clientFormService).getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, false);
verify(clientFormService).getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, false);
verify(clientFormService).getClientFormMetadataById(3L);
}
@Test
public void testSearchForFormByFormVersionShouldReturnNextJsonFormVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String currentFormVersion = "0.0.1";
List<IdVersionTuple> idVersionTuples = new ArrayList<>();
idVersionTuples.add(new IdVersionTuple(1, "0.0.1"));
idVersionTuples.add(new IdVersionTuple(2, "0.0.2"));
idVersionTuples.add(new IdVersionTuple(3, "0.0.3"));
ClientForm clientForm = new ClientForm();
clientForm.setJson("{}");
clientForm.setId(3L);
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(clientFormService.isClientFormExists(formIdentifier, false)).thenReturn(true);
when(clientFormService.getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, false)).thenReturn(null);
when(clientFormService.getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, false)).thenReturn(idVersionTuples);
when(clientFormService.getClientFormById(3L)).thenReturn(clientForm);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("current_form_version", currentFormVersion))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
JsonNode jsonNode = mapper.readTree(responseString);
assertEquals("{}", jsonNode.get("clientForm").get("json").textValue());
assertEquals("opd/reg.json", jsonNode.get("clientFormMetadata").get("identifier").textValue());
assertEquals("0.0.3", jsonNode.get("clientFormMetadata").get("version").textValue());
verify(clientFormService).isClientFormExists(formIdentifier, false);
verify(clientFormService).getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, false);
verify(clientFormService).getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, false);
verify(clientFormService).getClientFormById(3L);
verify(clientFormService).getClientFormMetadataById(3L);
}
@Test
public void testSearchForFormByFormVersionShouldReturnNextJsonValidatorVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String currentFormVersion = "0.0.1";
List<IdVersionTuple> idVersionTuples = new ArrayList<>();
idVersionTuples.add(new IdVersionTuple(1, "0.0.1"));
idVersionTuples.add(new IdVersionTuple(2, "0.0.2"));
idVersionTuples.add(new IdVersionTuple(3, "0.0.3"));
ClientForm clientForm = new ClientForm();
clientForm.setJson("{}");
clientForm.setId(3L);
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIsJsonValidator(true);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(clientFormService.isClientFormExists(formIdentifier, true)).thenReturn(true);
when(clientFormService.getClientFormMetadataByIdentifierAndVersion(formIdentifier, formVersion, true)).thenReturn(null);
when(clientFormService.getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, true)).thenReturn(idVersionTuples);
when(clientFormService.getClientFormById(3L)).thenReturn(clientForm);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("current_form_version", currentFormVersion)
.param("is_json_validator", "true"))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
JsonNode jsonNode = mapper.readTree(responseString);
assertEquals("{}", jsonNode.get("clientForm").get("json").textValue());
assertEquals("opd/reg.json", jsonNode.get("clientFormMetadata").get("identifier").textValue());
assertEquals("0.0.3", jsonNode.get("clientFormMetadata").get("version").textValue());
assertTrue(jsonNode.get("clientFormMetadata").get("isJsonValidator").booleanValue());
}
@Test
public void testAddClientFormWhenGivenJSON() throws Exception {
String formIdentifier = "opd/reg.json";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestList());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.2", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONAndFormVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "10.0.1";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestList());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals(formVersion, clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONValidatorFile() throws Exception {
String formIdentifier = "opd/reg.json";
String formName = "REGISTRATION FORM VALIDATOR";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_VALIDATOR_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(new ArrayList<>());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName)
.param("is_json_validator", "true"))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(),
clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_VALIDATOR_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.1", clientFormMetadata.getVersion());
assertTrue(clientFormMetadata.getIsJsonValidator());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONAndNoPreviousManifest() throws Exception {
String formIdentifier = "opd/reg.json";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(new ArrayList<>());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.1", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONValidatorFileAndFormVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "10.0.1";
String formName = "REGISTRATION FORM VALIDATOR";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_VALIDATOR_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(new ArrayList<>());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName)
.param("is_json_validator", "true"))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verifyNoInteractions(manifestService);
assertEquals(TestFileContent.JSON_VALIDATOR_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals(formVersion, clientFormMetadata.getVersion());
assertTrue(clientFormMetadata.getIsJsonValidator());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONAndWithMinorVersionGreaterThan999() throws Exception {
String formIdentifier = "opd/reg.json";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestMinorVersionGreaterThan1000());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("1.0.0", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONAndWithNoFormVersion() throws Exception {
String formIdentifier = "opd/reg.json";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestWithNoForMVersion());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService, times(4)).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.1", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenJSONAndWithPatchVersionGreaterThan999() throws Exception {
String formIdentifier = "opd/reg.json";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestPatchVersionGreaterThan1000());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.2.0", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
private List<Manifest> getManifestList() {
Manifest manifest = new Manifest();
manifest.setAppId("org.smartregister.anc");
manifest.setAppVersion("1.2.13");
manifest.setCreatedAt(DateTime.now());
manifest.setJson("{\"forms_version\":\"0.0.1\",\n" +
" \"identifiers\":[\n" +
" \"anc/member_registration.json\",\n" +
" \"anc/pregnancy_outcome.json\"]}");
manifest.setIdentifier("0.0.1");
List<Manifest> manifestList = new ArrayList<>();
manifestList.add(manifest);
return manifestList;
}
private List<Manifest> getManifestMinorVersionGreaterThan1000() {
Manifest manifest1 = new Manifest();
manifest1.setAppId("org.smartregister.anc");
manifest1.setAppVersion("1.2.13");
manifest1.setCreatedAt(DateTime.now());
manifest1.setJson("{\"forms_version\":\"0.1000.1000\",\n" +
" \"identifiers\":[\n" +
" \"anc/member_registration.json\",\n" +
" \"anc/pregnancy_outcome.json\"]}");
manifest1.setIdentifier("0.0.1");
List<Manifest> manifestList = new ArrayList<>();
manifestList.add(manifest1);
return manifestList;
}
private List<Manifest> getManifestPatchVersionGreaterThan1000() {
Manifest manifest1 = new Manifest();
manifest1.setAppId("org.smartregister.anc");
manifest1.setAppVersion("1.2.13");
manifest1.setCreatedAt(DateTime.now());
manifest1.setJson("{\"forms_version\":\"0.1.1000\",\n" +
" \"identifiers\":[\n" +
" \"anc/member_registration.json\",\n" +
" \"anc/pregnancy_outcome.json\"]}");
manifest1.setIdentifier("0.0.1");
List<Manifest> manifestList = new ArrayList<>();
manifestList.add(manifest1);
return manifestList;
}
private List<Manifest> getManifestWithNoForMVersion() {
Manifest manifest1 = new Manifest();
manifest1.setAppId("org.smartregister.anc");
manifest1.setAppVersion("1.2.13");
manifest1.setCreatedAt(DateTime.now());
manifest1.setJson("{\"form_version\":\"0.1.1000\",\n" +
" \"identifiers\":[\n" +
" \"anc/member_registration.json\",\n" +
" \"anc/pregnancy_outcome.json\"]}");
manifest1.setIdentifier("0.0.1");
List<Manifest> manifestList = new ArrayList<>();
manifestList.add(manifest1);
return manifestList;
}
@Test
public void testAddClientFormWhenGivenJSONWithMissingReferencesShouldReturn400() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.PHYSICAL_EXAM_FORM_FILE.getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
MvcResult mvcResult = mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isBadRequest())
.andReturn();
verify(clientFormService, times(16)).isClientFormExists(anyString());
String errorMessage = mvcResult.getResponse().getContentAsString();
assertTrue(errorMessage.contains("physical-exam-relevance-rules.yml"));
assertTrue(errorMessage.contains("physical-exam-calculations-rules.yml"));
}
@Test
public void testAddClientFormWhenGivenInvalidJSONShouldReturn400() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.substring(0, 20).getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
MvcResult result = mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isBadRequest())
.andReturn();
verifyNoInteractions(clientFormService);
String errorMessage = result.getResponse().getContentAsString();
assertEquals("File content error:", errorMessage.substring(0, 19));
}
@SuppressWarnings("deprecation")
@Test
public void testAddClientFormWhenGivenJSONWithMissingFieldsShouldReturn400() throws Exception {
String formIdentifier = "opd/reg.json";
String formVersion = "0.1.1";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
ClientForm formValidator = new ClientForm();
formValidator.setJson("\"{\"cannot_remove\":{\"title\":\"Fields you cannot remove\",\"fields\":[\"reaction_vaccine_duration\",\"reaction_vaccine_dosage\",\"aefi_form\"]}}\"");
Mockito.doReturn(formValidator)
.when(clientFormService).getMostRecentFormValidator(formIdentifier);
MvcResult mvcResult = mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isBadRequest())
.andReturn();
verify(clientFormService, times(0)).addClientForm(any(ClientForm.class), any(ClientFormMetadata.class));
String response = mvcResult.getResponse().getContentAsString();
assertThat(response, StringStartsWith.startsWith("Kindly make sure that the following fields are still in the form : "));
assertTrue(response.contains("reaction_vaccine_duration"));
assertTrue(response.contains("reaction_vaccine_dosage"));
}
@Test
public void testAddClientFormWhenGivenRulesYaml() throws Exception {
String formIdentifier = "opd/calculation.yaml";
String formName = "Calculation file";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/calculation.yaml",
"application/x-yaml", TestFileContent.CALCULATION_YAML_FILE_CONTENT.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestList());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.CALCULATION_YAML_FILE_CONTENT, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.2", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenYamlWithPropertiesReference() throws Exception {
String formIdentifier = "opd/attention_flag.yml";
String formName = "Relevance file";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/attention_flag.yml",
"application/x-yaml", TestFileContent.ATTENTION_FLAGS_YAML_FILE.getBytes());
Mockito.doReturn(true).when(clientFormService).isClientFormExists("attention_flags.properties");
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestList());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.ATTENTION_FLAGS_YAML_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.2", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenYamlWithMissingPropertiesReferenceReturns400() throws Exception {
String formIdentifier = "opd/attention_flag.yml";
String formName = "Relevance file";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/attention_flag.yml",
"application/x-yaml", TestFileContent.ATTENTION_FLAGS_YAML_FILE.getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
MvcResult result = mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isBadRequest())
.andReturn();
verify(clientFormService, times(2)).isClientFormExists(anyString());
String errorMessage = result.getResponse().getContentAsString();
assertTrue(errorMessage.contains("attention_flags"));
}
@Test
public void testAddClientFormWhenGivenInvalidYamlShouldReturn400() throws Exception {
String formIdentifier = "opd/calculation.yaml";
String formVersion = "0.1.1";
String formName = "Calculation file";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/calculation.yaml",
"application/x-yaml", TestFileContent.INVALID_YAML_FILE_CONTENT.getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
MvcResult result = mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isBadRequest())
.andReturn();
verifyNoInteractions(clientFormService);
String errorMessage = result.getResponse().getContentAsString();
assertEquals("File content error:", errorMessage.substring(0, 19));
}
@Test
public void testAddClientFormWhenGivenPropertiesFile() throws Exception {
String formIdentifier = "opd/opd_register.properties";
String formName = "Registration properties file";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/opd_register.properties",
"application/octet-stream", TestFileContent.JMAG_PROPERTIES_FILE_CONTENT.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestList());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JMAG_PROPERTIES_FILE_CONTENT, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.2", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testAddClientFormWhenGivenInvalidPropertiesFileShouldReturn400() throws Exception {
String formIdentifier = "opd/opd_register.properties";
String formVersion = "0.1.1";
String formName = "Registration properties file";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/opd_register.properties",
"application/octet-stream", (TestFileContent.JMAG_PROPERTIES_FILE_CONTENT + "\\uxxxx").getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
MvcResult result = mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_identifier", formIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isBadRequest())
.andReturn();
verifyNoInteractions(clientFormService);
String errorMessage = result.getResponse().getContentAsString();
assertEquals("File content error:", errorMessage.substring(0, 19));
}
@Test
public void testAddClientFormWithoutIdentifierDefaultsToFilenameAsIdentifier() throws Exception {
String formIdentifier = "reg.json";
String formName = "REGISTRATION FORM";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/reg.json",
"application/json", TestFileContent.JSON_FORM_FILE.getBytes());
when(manifestService.getAllManifest(anyInt())).thenReturn(getManifestList());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
verify(manifestService).getAllManifest(anyInt());
assertEquals(TestFileContent.JSON_FORM_FILE, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(formIdentifier, clientFormMetadata.getIdentifier());
assertEquals("0.0.2", clientFormMetadata.getVersion());
assertEquals(formName, clientFormMetadata.getLabel());
assertNull(clientFormMetadata.getModule());
}
@Test
public void testGetAllFilesRelatedToReleaseWithoutIdentifier() throws Exception {
MvcResult result = mockMvc.perform(get(BASE_URL + "release-related-files")
.param("identifier", ""))
.andExpect(status().isBadRequest())
.andReturn();
assertEquals("Request parameter cannot be empty", result.getResponse().getContentAsString());
}
@Test
public void testGetAllFilesRelatedToReleaseWithIdentifierAndNoValidManifest() throws Exception {
String identifier = "0.0.5";
when(manifestService.getManifest(identifier)).thenReturn(new Manifest());
MvcResult result = mockMvc.perform(get(BASE_URL + "release-related-files")
.param("identifier", identifier))
.andExpect(status().isNotFound())
.andReturn();
assertEquals("This manifest does not have any files related to it", result.getResponse().getContentAsString());
}
@Test
public void testGetAllFilesRelatedToReleaseWithIdentifierAndNoFormIdentifierInManifest() throws Exception {
String identifier = "0.0.5";
when(manifestService.getManifest(identifier)).thenReturn(initTestManifest());
MvcResult result = mockMvc.perform(get(BASE_URL + "release-related-files")
.param("identifier", identifier))
.andExpect(status().isNoContent())
.andReturn();
assertEquals("This manifest does not have any files related to it", result.getResponse().getContentAsString());
}
@Test
public void testGetAllFilesRelatedToReleaseWithIdentifierAndEmptyFormIdentifierList() throws Exception {
String identifier = "0.0.5";
when(manifestService.getManifest(identifier)).thenReturn(initTestManifest2());
MvcResult result = mockMvc.perform(get(BASE_URL + "release-related-files")
.param("identifier", identifier))
.andExpect(status().isNoContent())
.andReturn();
assertEquals("This manifest does not have any files related to it", result.getResponse().getContentAsString());
}
@Test
public void testGetAllFilesRelatedToRelease() throws Exception {
String identifier = "0.0.5";
String formIdentifier = "opd/reg.json";
List<IdVersionTuple> idVersionTuples = new ArrayList<>();
idVersionTuples.add(new IdVersionTuple(1, "0.0.1"));
idVersionTuples.add(new IdVersionTuple(2, "0.0.2"));
idVersionTuples.add(new IdVersionTuple(3, "0.0.3"));
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId(3L);
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0.3");
when(manifestService.getManifest(identifier)).thenReturn(initTestManifest3());
when(clientFormService.getAvailableClientFormMetadataVersionByIdentifier(formIdentifier, false)).thenReturn(idVersionTuples);
when(clientFormService.getClientFormMetadataById(3L)).thenReturn(clientFormMetadata);
MvcResult result = mockMvc.perform(get(BASE_URL + "release-related-files")
.param("identifier", identifier))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
JsonNode jsonNode = mapper.readTree(responseString);
assertEquals("opd/reg.json", jsonNode.get(0).get("identifier").textValue());
assertEquals("0.0.3", jsonNode.get(0).get("version").textValue());
}
private static Manifest initTestManifest() {
Manifest manifest = new Manifest();
String identifier = "mani1234";
String appVersion = "1234234";
String json = "{\"name\":\"test\"}";
String appId = "1234567op";
manifest.setAppId(appId);
manifest.setAppVersion(appVersion);
manifest.setIdentifier(identifier);
manifest.setJson(json);
return manifest;
}
private static Manifest initTestManifest2() {
Manifest manifest = new Manifest();
String identifier = "mani1234";
String appVersion = "1234234";
String json = "{\"forms_version\":\"0.0.1\",\n"
+ " \"identifiers\":[]}";
String appId = "1234567op";
manifest.setAppId(appId);
manifest.setAppVersion(appVersion);
manifest.setIdentifier(identifier);
manifest.setJson(json);
return manifest;
}
private static Manifest initTestManifest3() {
Manifest manifest = new Manifest();
String identifier = "mani1234";
String appVersion = "1234234";
String json = "{\"forms_version\":\"0.0.1\",\"identifiers\":[\"opd/reg.json\"]}";
String appId = "1234567op";
manifest.setAppId(appId);
manifest.setAppVersion(appVersion);
manifest.setIdentifier(identifier);
manifest.setJson(json);
return manifest;
}
@Test
public void testCanAddClientFormWithRelation() throws Exception{
String relatedJsonIdentifier = "json.form/child-registration.json";
String formVersion = "0.1.1";
String formName = "CHILD CALCULATION";
MockMultipartFile file = new MockMultipartFile("form", "path/to/opd/calculation.yml",
"application/x-yaml", TestFileContent.CALCULATION_YAML_FILE_CONTENT.getBytes());
when(clientFormService.addClientForm(any(ClientForm.class), any(ClientFormMetadata.class))).thenReturn(mock(ClientFormService.CompleteClientForm.class));
mockMvc.perform(
fileUpload(BASE_URL)
.file(file)
.param("form_relation", relatedJsonIdentifier)
.param("form_version", formVersion)
.param("form_name", formName))
.andExpect(status().isCreated())
.andReturn();
ArgumentCaptor<ClientForm> clientFormArgumentCaptor = ArgumentCaptor.forClass(ClientForm.class);
ArgumentCaptor<ClientFormMetadata> clientFormMetadataArgumentCaptor = ArgumentCaptor.forClass(ClientFormMetadata.class);
verify(clientFormService).addClientForm(clientFormArgumentCaptor.capture(), clientFormMetadataArgumentCaptor.capture());
assertEquals(TestFileContent.CALCULATION_YAML_FILE_CONTENT, clientFormArgumentCaptor.getValue().getJson().toString());
ClientFormMetadata clientFormMetadata = clientFormMetadataArgumentCaptor.getValue();
assertEquals(relatedJsonIdentifier, clientFormMetadata.getRelation());
}
@Test
public void testIsClientFormContentTypeValidShouldReturnTrueWhenGivenJSON() throws Exception {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertTrue(clientFormResource.isClientFormContentTypeValid(ContentType.APPLICATION_JSON.getMimeType()));
}
@Test
public void testIsClientFormContentTypeValidShouldReturnTrueWhenGivenApplicationYaml() throws Exception {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertTrue(clientFormResource.isClientFormContentTypeValid(Constants.ContentType.APPLICATION_YAML));
}
@Test
public void testIsClientFormContentTypeValidShouldReturnTrueWhenGivenTextYamlContentTypeForYamlFile() throws Exception {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertTrue(clientFormResource.isClientFormContentTypeValid(Constants.ContentType.TEXT_YAML));
}
@Test
public void testIsPropertiesFileShouldReturnTrue() {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertTrue(clientFormResource.isPropertiesFile("application/octet-stream", "anc_register.properties"));
}
@Test
public void testIsPropertiesFileShouldReturnFalse() {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertFalse(clientFormResource.isPropertiesFile("application/octet-stream", "anc_register"));
}
@Test
public void testCheckValidContentShouldReturnErrorMessageWhenGivenInvalidJSONStructure() {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertNotNull(clientFormResource.checkValidJsonYamlPropertiesStructure(TestFileContent.JSON_FORM_FILE.substring(0, 10), "application/json"));
}
@Test
public void testCheckValidJsonYamlPropertiesStructureShouldReturnErrorMessageWhenGivenInvalidYamlStructure() {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertNotNull(clientFormResource.checkValidJsonYamlPropertiesStructure(TestFileContent.INVALID_YAML_FILE_CONTENT, "application/x-yaml"));
}
@Test
public void testCheckValidJsonYamlPropertiesStructureShouldReturnErrorMessageWhenGivenInvalidPropertiesStructure() {
ClientFormResource clientFormResource = webApplicationContext.getBean(ClientFormResource.class);
assertNotNull(clientFormResource.checkValidJsonYamlPropertiesStructure(TestFileContent.JMAG_PROPERTIES_FILE_CONTENT.substring(0, 378) + "\\uxxxx", ContentType.APPLICATION_OCTET_STREAM.getMimeType()));
}
@Test
public void testGetClientFormMetadataListShouldReturnAllForms() throws Exception {
int count = 11;
String formIdentifier = "opd/opd_register.properties";
List<ClientFormMetadata> clientFormMetadataList = new ArrayList<>();
for (int i = 0; i < count; i++) {
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId((long) (i + 1));
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setVersion("0.0." + (i + 1));
clientFormMetadataList.add(clientFormMetadata);
}
when(clientFormService.getAllClientFormMetadata()).thenReturn(clientFormMetadataList);
MvcResult result = mockMvc.perform(get(BASE_URL + "metadata"))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
ArrayNode arrayNode = (ArrayNode) mapper.readTree(responseString);
assertEquals(count, arrayNode.size());
assertEquals(1L, arrayNode.get(0).get("id").longValue());
assertEquals("0.0.1", arrayNode.get(0).get("version").textValue());
}
@Test
public void testGetClientFormMetadataListShouldReturnDraftForms() throws Exception {
int count = 7;
String formIdentifier = "opd/opd_register.properties";
List<ClientFormMetadata> clientFormMetadataList = new ArrayList<>();
for (int i = 0; i < count; i++) {
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId((long) (i + 1));
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setIsDraft(true);
clientFormMetadata.setVersion("0.0." + (i + 1));
clientFormMetadataList.add(clientFormMetadata);
}
when(clientFormService.getDraftsClientFormMetadata(true)).thenReturn(clientFormMetadataList);
MvcResult result = mockMvc.perform(get(BASE_URL + "metadata")
.param("is_draft", "true"))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
ArrayNode arrayNode = (ArrayNode) mapper.readTree(responseString);
assertEquals(count, arrayNode.size());
assertEquals(1L, arrayNode.get(0).get("id").longValue());
assertEquals("0.0.1", arrayNode.get(0).get("version").textValue());
assertTrue(arrayNode.get(0).get("isDraft").booleanValue());
}
@Test
public void testGetClientFormMetadataListShouldReturnJsonWidgetValidators() throws Exception {
int count = 7;
String formIdentifier = "opd/opd_register.properties";
List<ClientFormMetadata> clientFormMetadataList = new ArrayList<>();
for (int i = 0; i < count; i++) {
ClientFormMetadata clientFormMetadata = new ClientFormMetadata();
clientFormMetadata.setId((long) (i + 1));
clientFormMetadata.setIdentifier(formIdentifier);
clientFormMetadata.setIsDraft(true);
clientFormMetadata.setIsJsonValidator(true);
clientFormMetadata.setVersion("0.0." + (i + 1));
clientFormMetadataList.add(clientFormMetadata);
}
when(clientFormService.getJsonWidgetValidatorClientFormMetadata(true)).thenReturn(clientFormMetadataList);
MvcResult result = mockMvc.perform(get(BASE_URL + "metadata")
.param("is_json_validator", "true"))
.andExpect(status().isOk())
.andReturn();
String responseString = result.getResponse().getContentAsString();
ArrayNode arrayNode = (ArrayNode) mapper.readTree(responseString);
assertEquals(count, arrayNode.size());
assertEquals(1L, arrayNode.get(0).get("id").longValue());
assertEquals("0.0.1", arrayNode.get(0).get("version").textValue());
assertTrue(arrayNode.get(0).get("isJsonValidator").booleanValue());
}
}
| 50.457792 | 208 | 0.701194 |
29abfdf2979b9e7f23122285030b602a1db1dd6a | 635 | package com.stc.trawl.voice.data.preprocess;
import com.stc.trawl.voice.data.dto.PreprocessorResultDto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
import java.net.URI;
import java.util.List;
@Data
@AllArgsConstructor
public class SamplerData implements Serializable {
private static final long serialVersionUID = -8250709868129220226L;
private URI audio;
private List<PreprocessorResultDto> results;
private ChannelType channel_type;
public SamplerData(URI audio, ChannelType channel_type) {
this.audio = audio;
this.channel_type = channel_type;
}
}
| 25.4 | 71 | 0.770079 |
8cafed643c79efcef438d6cf15b83f894730fc8c | 247 | package info.globalbus.oraclewrapper;
import java.util.List;
public interface ProcedureCaller<T> {
String OUTPUT_PARAM = "output";
String INPUT_PARAM = "input";
List<T> mapList(Object... input);
T mapObject(Object... input);
}
| 19 | 37 | 0.696356 |
cbf1d26bbb942043649f193bd1f74a685af21fb4 | 989 | package com.example.web.servlet.threads;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/chvalue")
public class ChangeSessionValueServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String name = req.getParameter("name");
String value = req.getParameter("value");
HttpSession session = req.getSession();
synchronized (session) {
if (name != null) {
req.getSession().setAttribute(name, value);
out.format("Set session attribute %s=%s", name, value);
}
}
}
}
| 30.90625 | 113 | 0.700708 |
40e4d8817d61a18e65dda804cd5aacf98f112672 | 57,487 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: crypto/models.proto
package crypto;
public final class Models {
private Models() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface PublicKeyOrBuilder extends
// @@protoc_insertion_point(interface_extends:crypto.PublicKey)
com.google.protobuf.MessageOrBuilder {
/**
* <code>bytes ed25519 = 1;</code>
*/
com.google.protobuf.ByteString getEd25519();
public crypto.Models.PublicKey.PubCase getPubCase();
}
/**
* Protobuf type {@code crypto.PublicKey}
*/
public static final class PublicKey extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:crypto.PublicKey)
PublicKeyOrBuilder {
private static final long serialVersionUID = 0L;
// Use PublicKey.newBuilder() to construct.
private PublicKey(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PublicKey() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private PublicKey(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
pubCase_ = 1;
pub_ = input.readBytes();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return crypto.Models.internal_static_crypto_PublicKey_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return crypto.Models.internal_static_crypto_PublicKey_fieldAccessorTable
.ensureFieldAccessorsInitialized(
crypto.Models.PublicKey.class, crypto.Models.PublicKey.Builder.class);
}
private int pubCase_ = 0;
private java.lang.Object pub_;
public enum PubCase
implements com.google.protobuf.Internal.EnumLite {
ED25519(1),
PUB_NOT_SET(0);
private final int value;
private PubCase(int value) {
this.value = value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static PubCase valueOf(int value) {
return forNumber(value);
}
public static PubCase forNumber(int value) {
switch (value) {
case 1: return ED25519;
case 0: return PUB_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public PubCase
getPubCase() {
return PubCase.forNumber(
pubCase_);
}
public static final int ED25519_FIELD_NUMBER = 1;
/**
* <code>bytes ed25519 = 1;</code>
*/
public com.google.protobuf.ByteString getEd25519() {
if (pubCase_ == 1) {
return (com.google.protobuf.ByteString) pub_;
}
return com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (pubCase_ == 1) {
output.writeBytes(
1, (com.google.protobuf.ByteString) pub_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (pubCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(
1, (com.google.protobuf.ByteString) pub_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof crypto.Models.PublicKey)) {
return super.equals(obj);
}
crypto.Models.PublicKey other = (crypto.Models.PublicKey) obj;
if (!getPubCase().equals(other.getPubCase())) return false;
switch (pubCase_) {
case 1:
if (!getEd25519()
.equals(other.getEd25519())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
switch (pubCase_) {
case 1:
hash = (37 * hash) + ED25519_FIELD_NUMBER;
hash = (53 * hash) + getEd25519().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static crypto.Models.PublicKey parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.PublicKey parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.PublicKey parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.PublicKey parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.PublicKey parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.PublicKey parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.PublicKey parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static crypto.Models.PublicKey parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static crypto.Models.PublicKey parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static crypto.Models.PublicKey parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static crypto.Models.PublicKey parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static crypto.Models.PublicKey parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(crypto.Models.PublicKey prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code crypto.PublicKey}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:crypto.PublicKey)
crypto.Models.PublicKeyOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return crypto.Models.internal_static_crypto_PublicKey_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return crypto.Models.internal_static_crypto_PublicKey_fieldAccessorTable
.ensureFieldAccessorsInitialized(
crypto.Models.PublicKey.class, crypto.Models.PublicKey.Builder.class);
}
// Construct using crypto.Models.PublicKey.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
pubCase_ = 0;
pub_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return crypto.Models.internal_static_crypto_PublicKey_descriptor;
}
@java.lang.Override
public crypto.Models.PublicKey getDefaultInstanceForType() {
return crypto.Models.PublicKey.getDefaultInstance();
}
@java.lang.Override
public crypto.Models.PublicKey build() {
crypto.Models.PublicKey result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public crypto.Models.PublicKey buildPartial() {
crypto.Models.PublicKey result = new crypto.Models.PublicKey(this);
if (pubCase_ == 1) {
result.pub_ = pub_;
}
result.pubCase_ = pubCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof crypto.Models.PublicKey) {
return mergeFrom((crypto.Models.PublicKey)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(crypto.Models.PublicKey other) {
if (other == crypto.Models.PublicKey.getDefaultInstance()) return this;
switch (other.getPubCase()) {
case ED25519: {
setEd25519(other.getEd25519());
break;
}
case PUB_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
crypto.Models.PublicKey parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (crypto.Models.PublicKey) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int pubCase_ = 0;
private java.lang.Object pub_;
public PubCase
getPubCase() {
return PubCase.forNumber(
pubCase_);
}
public Builder clearPub() {
pubCase_ = 0;
pub_ = null;
onChanged();
return this;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public com.google.protobuf.ByteString getEd25519() {
if (pubCase_ == 1) {
return (com.google.protobuf.ByteString) pub_;
}
return com.google.protobuf.ByteString.EMPTY;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public Builder setEd25519(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
pubCase_ = 1;
pub_ = value;
onChanged();
return this;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public Builder clearEd25519() {
if (pubCase_ == 1) {
pubCase_ = 0;
pub_ = null;
onChanged();
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:crypto.PublicKey)
}
// @@protoc_insertion_point(class_scope:crypto.PublicKey)
private static final crypto.Models.PublicKey DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new crypto.Models.PublicKey();
}
public static crypto.Models.PublicKey getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PublicKey>
PARSER = new com.google.protobuf.AbstractParser<PublicKey>() {
@java.lang.Override
public PublicKey parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PublicKey(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PublicKey> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PublicKey> getParserForType() {
return PARSER;
}
@java.lang.Override
public crypto.Models.PublicKey getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface PrivateKeyOrBuilder extends
// @@protoc_insertion_point(interface_extends:crypto.PrivateKey)
com.google.protobuf.MessageOrBuilder {
/**
* <code>bytes ed25519 = 1;</code>
*/
com.google.protobuf.ByteString getEd25519();
public crypto.Models.PrivateKey.PrivCase getPrivCase();
}
/**
* Protobuf type {@code crypto.PrivateKey}
*/
public static final class PrivateKey extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:crypto.PrivateKey)
PrivateKeyOrBuilder {
private static final long serialVersionUID = 0L;
// Use PrivateKey.newBuilder() to construct.
private PrivateKey(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PrivateKey() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private PrivateKey(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
privCase_ = 1;
priv_ = input.readBytes();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return crypto.Models.internal_static_crypto_PrivateKey_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return crypto.Models.internal_static_crypto_PrivateKey_fieldAccessorTable
.ensureFieldAccessorsInitialized(
crypto.Models.PrivateKey.class, crypto.Models.PrivateKey.Builder.class);
}
private int privCase_ = 0;
private java.lang.Object priv_;
public enum PrivCase
implements com.google.protobuf.Internal.EnumLite {
ED25519(1),
PRIV_NOT_SET(0);
private final int value;
private PrivCase(int value) {
this.value = value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static PrivCase valueOf(int value) {
return forNumber(value);
}
public static PrivCase forNumber(int value) {
switch (value) {
case 1: return ED25519;
case 0: return PRIV_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public PrivCase
getPrivCase() {
return PrivCase.forNumber(
privCase_);
}
public static final int ED25519_FIELD_NUMBER = 1;
/**
* <code>bytes ed25519 = 1;</code>
*/
public com.google.protobuf.ByteString getEd25519() {
if (privCase_ == 1) {
return (com.google.protobuf.ByteString) priv_;
}
return com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (privCase_ == 1) {
output.writeBytes(
1, (com.google.protobuf.ByteString) priv_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (privCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(
1, (com.google.protobuf.ByteString) priv_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof crypto.Models.PrivateKey)) {
return super.equals(obj);
}
crypto.Models.PrivateKey other = (crypto.Models.PrivateKey) obj;
if (!getPrivCase().equals(other.getPrivCase())) return false;
switch (privCase_) {
case 1:
if (!getEd25519()
.equals(other.getEd25519())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
switch (privCase_) {
case 1:
hash = (37 * hash) + ED25519_FIELD_NUMBER;
hash = (53 * hash) + getEd25519().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static crypto.Models.PrivateKey parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.PrivateKey parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.PrivateKey parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.PrivateKey parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.PrivateKey parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.PrivateKey parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.PrivateKey parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static crypto.Models.PrivateKey parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static crypto.Models.PrivateKey parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static crypto.Models.PrivateKey parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static crypto.Models.PrivateKey parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static crypto.Models.PrivateKey parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(crypto.Models.PrivateKey prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code crypto.PrivateKey}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:crypto.PrivateKey)
crypto.Models.PrivateKeyOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return crypto.Models.internal_static_crypto_PrivateKey_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return crypto.Models.internal_static_crypto_PrivateKey_fieldAccessorTable
.ensureFieldAccessorsInitialized(
crypto.Models.PrivateKey.class, crypto.Models.PrivateKey.Builder.class);
}
// Construct using crypto.Models.PrivateKey.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
privCase_ = 0;
priv_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return crypto.Models.internal_static_crypto_PrivateKey_descriptor;
}
@java.lang.Override
public crypto.Models.PrivateKey getDefaultInstanceForType() {
return crypto.Models.PrivateKey.getDefaultInstance();
}
@java.lang.Override
public crypto.Models.PrivateKey build() {
crypto.Models.PrivateKey result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public crypto.Models.PrivateKey buildPartial() {
crypto.Models.PrivateKey result = new crypto.Models.PrivateKey(this);
if (privCase_ == 1) {
result.priv_ = priv_;
}
result.privCase_ = privCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof crypto.Models.PrivateKey) {
return mergeFrom((crypto.Models.PrivateKey)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(crypto.Models.PrivateKey other) {
if (other == crypto.Models.PrivateKey.getDefaultInstance()) return this;
switch (other.getPrivCase()) {
case ED25519: {
setEd25519(other.getEd25519());
break;
}
case PRIV_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
crypto.Models.PrivateKey parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (crypto.Models.PrivateKey) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int privCase_ = 0;
private java.lang.Object priv_;
public PrivCase
getPrivCase() {
return PrivCase.forNumber(
privCase_);
}
public Builder clearPriv() {
privCase_ = 0;
priv_ = null;
onChanged();
return this;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public com.google.protobuf.ByteString getEd25519() {
if (privCase_ == 1) {
return (com.google.protobuf.ByteString) priv_;
}
return com.google.protobuf.ByteString.EMPTY;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public Builder setEd25519(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
privCase_ = 1;
priv_ = value;
onChanged();
return this;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public Builder clearEd25519() {
if (privCase_ == 1) {
privCase_ = 0;
priv_ = null;
onChanged();
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:crypto.PrivateKey)
}
// @@protoc_insertion_point(class_scope:crypto.PrivateKey)
private static final crypto.Models.PrivateKey DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new crypto.Models.PrivateKey();
}
public static crypto.Models.PrivateKey getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PrivateKey>
PARSER = new com.google.protobuf.AbstractParser<PrivateKey>() {
@java.lang.Override
public PrivateKey parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PrivateKey(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PrivateKey> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PrivateKey> getParserForType() {
return PARSER;
}
@java.lang.Override
public crypto.Models.PrivateKey getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface SignatureOrBuilder extends
// @@protoc_insertion_point(interface_extends:crypto.Signature)
com.google.protobuf.MessageOrBuilder {
/**
* <code>bytes ed25519 = 1;</code>
*/
com.google.protobuf.ByteString getEd25519();
public crypto.Models.Signature.SigCase getSigCase();
}
/**
* Protobuf type {@code crypto.Signature}
*/
public static final class Signature extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:crypto.Signature)
SignatureOrBuilder {
private static final long serialVersionUID = 0L;
// Use Signature.newBuilder() to construct.
private Signature(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Signature() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Signature(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
sigCase_ = 1;
sig_ = input.readBytes();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return crypto.Models.internal_static_crypto_Signature_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return crypto.Models.internal_static_crypto_Signature_fieldAccessorTable
.ensureFieldAccessorsInitialized(
crypto.Models.Signature.class, crypto.Models.Signature.Builder.class);
}
private int sigCase_ = 0;
private java.lang.Object sig_;
public enum SigCase
implements com.google.protobuf.Internal.EnumLite {
ED25519(1),
SIG_NOT_SET(0);
private final int value;
private SigCase(int value) {
this.value = value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SigCase valueOf(int value) {
return forNumber(value);
}
public static SigCase forNumber(int value) {
switch (value) {
case 1: return ED25519;
case 0: return SIG_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public SigCase
getSigCase() {
return SigCase.forNumber(
sigCase_);
}
public static final int ED25519_FIELD_NUMBER = 1;
/**
* <code>bytes ed25519 = 1;</code>
*/
public com.google.protobuf.ByteString getEd25519() {
if (sigCase_ == 1) {
return (com.google.protobuf.ByteString) sig_;
}
return com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (sigCase_ == 1) {
output.writeBytes(
1, (com.google.protobuf.ByteString) sig_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (sigCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(
1, (com.google.protobuf.ByteString) sig_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof crypto.Models.Signature)) {
return super.equals(obj);
}
crypto.Models.Signature other = (crypto.Models.Signature) obj;
if (!getSigCase().equals(other.getSigCase())) return false;
switch (sigCase_) {
case 1:
if (!getEd25519()
.equals(other.getEd25519())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
switch (sigCase_) {
case 1:
hash = (37 * hash) + ED25519_FIELD_NUMBER;
hash = (53 * hash) + getEd25519().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static crypto.Models.Signature parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.Signature parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.Signature parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.Signature parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.Signature parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static crypto.Models.Signature parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static crypto.Models.Signature parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static crypto.Models.Signature parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static crypto.Models.Signature parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static crypto.Models.Signature parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static crypto.Models.Signature parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static crypto.Models.Signature parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(crypto.Models.Signature prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code crypto.Signature}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:crypto.Signature)
crypto.Models.SignatureOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return crypto.Models.internal_static_crypto_Signature_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return crypto.Models.internal_static_crypto_Signature_fieldAccessorTable
.ensureFieldAccessorsInitialized(
crypto.Models.Signature.class, crypto.Models.Signature.Builder.class);
}
// Construct using crypto.Models.Signature.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
sigCase_ = 0;
sig_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return crypto.Models.internal_static_crypto_Signature_descriptor;
}
@java.lang.Override
public crypto.Models.Signature getDefaultInstanceForType() {
return crypto.Models.Signature.getDefaultInstance();
}
@java.lang.Override
public crypto.Models.Signature build() {
crypto.Models.Signature result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public crypto.Models.Signature buildPartial() {
crypto.Models.Signature result = new crypto.Models.Signature(this);
if (sigCase_ == 1) {
result.sig_ = sig_;
}
result.sigCase_ = sigCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof crypto.Models.Signature) {
return mergeFrom((crypto.Models.Signature)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(crypto.Models.Signature other) {
if (other == crypto.Models.Signature.getDefaultInstance()) return this;
switch (other.getSigCase()) {
case ED25519: {
setEd25519(other.getEd25519());
break;
}
case SIG_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
crypto.Models.Signature parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (crypto.Models.Signature) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int sigCase_ = 0;
private java.lang.Object sig_;
public SigCase
getSigCase() {
return SigCase.forNumber(
sigCase_);
}
public Builder clearSig() {
sigCase_ = 0;
sig_ = null;
onChanged();
return this;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public com.google.protobuf.ByteString getEd25519() {
if (sigCase_ == 1) {
return (com.google.protobuf.ByteString) sig_;
}
return com.google.protobuf.ByteString.EMPTY;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public Builder setEd25519(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
sigCase_ = 1;
sig_ = value;
onChanged();
return this;
}
/**
* <code>bytes ed25519 = 1;</code>
*/
public Builder clearEd25519() {
if (sigCase_ == 1) {
sigCase_ = 0;
sig_ = null;
onChanged();
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:crypto.Signature)
}
// @@protoc_insertion_point(class_scope:crypto.Signature)
private static final crypto.Models.Signature DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new crypto.Models.Signature();
}
public static crypto.Models.Signature getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Signature>
PARSER = new com.google.protobuf.AbstractParser<Signature>() {
@java.lang.Override
public Signature parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Signature(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Signature> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Signature> getParserForType() {
return PARSER;
}
@java.lang.Override
public crypto.Models.Signature getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_crypto_PublicKey_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_crypto_PublicKey_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_crypto_PrivateKey_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_crypto_PrivateKey_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_crypto_Signature_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_crypto_Signature_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\023crypto/models.proto\022\006crypto\"%\n\tPublicK" +
"ey\022\021\n\007ed25519\030\001 \001(\014H\000B\005\n\003pub\"\'\n\nPrivateK" +
"ey\022\021\n\007ed25519\030\001 \001(\014H\000B\006\n\004priv\"%\n\tSignatu" +
"re\022\021\n\007ed25519\030\001 \001(\014H\000B\005\n\003sigb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_crypto_PublicKey_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_crypto_PublicKey_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_crypto_PublicKey_descriptor,
new java.lang.String[] { "Ed25519", "Pub", });
internal_static_crypto_PrivateKey_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_crypto_PrivateKey_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_crypto_PrivateKey_descriptor,
new java.lang.String[] { "Ed25519", "Priv", });
internal_static_crypto_Signature_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_crypto_Signature_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_crypto_Signature_descriptor,
new java.lang.String[] { "Ed25519", "Sig", });
}
// @@protoc_insertion_point(outer_class_scope)
}
| 32.663068 | 93 | 0.64418 |
e48e8e5c1b0c58dcce21de435bc486a7d848c8dd | 1,862 | /*
* Copyright (c) 2017, 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.carbon.appmgt.mdm.restconnector.authorization.client.dto;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/admin/applications")
/**
* This interface provided the definition of the application management service.
*/
public interface ApplicationManagementAdminService {
/**
* Install application.
*
* @param applicationWrapper {@link ApplicationWrapper} object
* @return {@link Activity} object
*/
@POST
@Path("/install-application")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
Activity installApplication(ApplicationWrapper applicationWrapper);
/**
* Uninstall application.
*
* @param applicationWrapper {@link ApplicationWrapper} object
* @return {@link Activity} object
*/
@POST
@Path("/uninstall-application")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
Activity uninstallApplication(ApplicationWrapper applicationWrapper);
} | 31.559322 | 80 | 0.73362 |
a400afd51f94db8fdd4025b5965b9b768ba73f9b | 5,698 | /*
* Copyright (c) 2017 Kiall Mac Innes <[email protected]>
*
* 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 ie.macinnes.tvheadend.player;
import android.media.tv.TvTrackInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.util.MimeTypes;
import java.util.Locale;
class ExoPlayerUtils {
private static final String TAG = ExoPlayerUtils.class.getName();
public static TvTrackInfo buildTvTrackInfo(Format format) {
String trackName = ExoPlayerUtils.buildTrackName(format);
Log.d(TAG, "Processing track: " + trackName);
if (format.id == null) {
Log.e(TAG, "Track ID invalid, skipping track " + trackName);
return null;
}
TvTrackInfo.Builder builder;
int trackType = MimeTypes.getTrackType(format.sampleMimeType);
switch (trackType) {
case C.TRACK_TYPE_VIDEO:
builder = new TvTrackInfo.Builder(TvTrackInfo.TYPE_VIDEO, format.id);
builder.setVideoFrameRate(format.frameRate);
if (format.width != Format.NO_VALUE && format.height != Format.NO_VALUE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
builder.setVideoWidth(format.width);
builder.setVideoHeight(format.height);
builder.setVideoPixelAspectRatio(format.pixelWidthHeightRatio);
} else {
builder.setVideoWidth((int) (format.width * format.pixelWidthHeightRatio));
builder.setVideoHeight(format.height);
}
}
break;
case C.TRACK_TYPE_AUDIO:
builder = new TvTrackInfo.Builder(TvTrackInfo.TYPE_AUDIO, format.id);
builder.setAudioChannelCount(format.channelCount);
builder.setAudioSampleRate(format.sampleRate);
break;
case C.TRACK_TYPE_TEXT:
builder = new TvTrackInfo.Builder(TvTrackInfo.TYPE_SUBTITLE, format.id);
break;
default:
Log.w(TAG, "Unsupported track type: " + format.sampleMimeType + " / " + trackName);
return null;
}
if (!TextUtils.isEmpty(format.language)
&& !format.language.equals("und")
&& !format.language.equals("nar")
&& !format.language.equals("syn")
&& !format.language.equals("mis")) {
builder.setLanguage(format.language);
}
// TODO: Determine where the Description is used..
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// builder.setDescription(ExoPlayerUtils.buildTrackName(format));
// }
return builder.build();
}
// Track name construction.
private static String buildTrackName(Format format) {
String trackName;
if (MimeTypes.isVideo(format.sampleMimeType)) {
trackName = joinWithSeparator(joinWithSeparator(buildResolutionString(format),
buildBitrateString(format)), buildTrackIdString(format));
} else if (MimeTypes.isAudio(format.sampleMimeType)) {
trackName = joinWithSeparator(joinWithSeparator(joinWithSeparator(buildLanguageString(format),
buildAudioPropertyString(format)), buildBitrateString(format)),
buildTrackIdString(format));
} else {
trackName = joinWithSeparator(joinWithSeparator(buildLanguageString(format),
buildBitrateString(format)), buildTrackIdString(format));
}
return trackName.length() == 0 ? "unknown" : trackName;
}
private static String buildResolutionString(Format format) {
return format.width == Format.NO_VALUE || format.height == Format.NO_VALUE
? "" : format.width + "x" + format.height;
}
private static String buildAudioPropertyString(Format format) {
return format.channelCount == Format.NO_VALUE || format.sampleRate == Format.NO_VALUE
? "" : format.channelCount + "ch, " + format.sampleRate + "Hz";
}
private static String buildLanguageString(Format format) {
return TextUtils.isEmpty(format.language) || "und".equals(format.language) ? ""
: format.language;
}
private static String buildBitrateString(Format format) {
return format.bitrate == Format.NO_VALUE ? ""
: String.format(Locale.US, "%.2fMbit", format.bitrate / 1000000f);
}
private static String buildTrackIdString(Format format) {
return format.id == null ? "" : ("id:" + format.id);
}
private static String joinWithSeparator(String first, String second) {
if (first.length() == 0) {
return second;
} else if (second.length() == 0) {
return first;
} else {
return first + ", " + second;
}
}
private ExoPlayerUtils() {
}
}
| 38.5 | 106 | 0.620393 |
6c64801499336df7f377aaed7ea37beefb978121 | 7,133 | // Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.classlookup;
import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import com.android.tools.r8.CompilationFailedException;
import com.android.tools.r8.R8TestCompileResult;
import com.android.tools.r8.TestBase;
import com.android.tools.r8.TestParameters;
import com.android.tools.r8.TestParametersCollection;
import com.android.tools.r8.jasmin.JasminBuilder;
import com.android.tools.r8.utils.codeinspector.CodeInspector;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
// This test used to test R8 errors/warnings when library class extends program class. Before
// the change fixing b/120884788, that could easily happen as lookup would lookup in program
// classes before library classes, and the Android library included parts of JUnit, which could
// also easily end up as program classes when JUnit was used by a program.
//
// Now that library classes are looked up before program classes these JUnit classes will be
// found in the library and the ones in program will be ignored and not end up in the output.
//
// For a D8 compilation any class passed as input will end up in the output.
@RunWith(Parameterized.class)
public class LibraryClassExtendsProgramClassTest extends TestBase {
private static List<byte[]> junitClasses;
@BeforeClass
public static void setUp() throws Exception {
JasminBuilder builder = new JasminBuilder();
builder.addClass("junit.framework.TestCase");
junitClasses = builder.buildClasses();
}
private final TestParameters parameters;
@Parameterized.Parameters(name = "{0}")
public static TestParametersCollection data() {
return getTestParameters().withAllRuntimes().withAllApiLevels().build();
}
public LibraryClassExtendsProgramClassTest(TestParameters parameters) {
this.parameters = parameters;
}
private void checkClassesInResult(CodeInspector inspector) {
if (parameters.isDexRuntime()) {
noClassesInResult(inspector);
} else {
testCaseClassInResult(inspector);
}
}
private void noClassesInResult(CodeInspector inspector) {
assertEquals(1, inspector.allClasses().size());
assertThat(inspector.clazz(TestClass.class), isPresent());
}
private void testCaseClassInResult(CodeInspector inspector) {
assertEquals(2, inspector.allClasses().size());
assertThat(inspector.clazz("junit.framework.TestCase"), isPresent());
assertThat(inspector.clazz(TestClass.class), isPresent());
}
@Test
public void testFullMode() throws Exception {
testForR8(parameters.getBackend())
.setMinApi(parameters.getApiLevel())
.addProgramClasses(TestClass.class)
.addProgramClassFileData(junitClasses)
.addKeepAllClassesRule()
// TODO(120884788): Remove when this is the default.
.addOptionsModification(options -> options.lookupLibraryBeforeProgram = true)
.compile()
.inspect(this::checkClassesInResult)
.assertNoMessages();
}
@Test
public void testCompatibilityMode() throws Exception {
testForR8Compat(parameters.getBackend())
.setMinApi(parameters.getApiLevel())
.addProgramClasses(TestClass.class)
.addProgramClassFileData(junitClasses)
.addKeepAllClassesRule()
// TODO(120884788): Remove when this is the default.
.addOptionsModification(options -> options.lookupLibraryBeforeProgram = true)
.compile()
.inspect(this::checkClassesInResult)
.assertNoMessages();
}
@Test
public void testD8() throws Exception {
assumeTrue("Only run D8 for Dex backend", parameters.isDexRuntime());
testForD8()
.setMinApi(parameters.getApiLevel())
.addProgramClasses(TestClass.class)
.addProgramClassFileData(junitClasses)
.compile()
.inspect(this::testCaseClassInResult)
.assertNoMessages();
}
@Test
public void testFullModeError() {
assumeTrue("Only run for Dex backend", parameters.isDexRuntime());
try {
testForR8(parameters.getBackend())
.setMinApi(parameters.getApiLevel())
.addProgramClasses(TestClass.class)
.addProgramClassFileData(junitClasses)
.addKeepAllClassesRule()
.addOptionsModification(options -> options.lookupLibraryBeforeProgram = false)
.compile();
fail("Succeeded in full mode");
} catch (CompilationFailedException e) {
// Ignore.
}
}
@Test
public void testCompatibilityModeWarning() throws Exception {
assumeTrue("Only run for Dex backend", parameters.isDexRuntime());
R8TestCompileResult result =
testForR8Compat(parameters.getBackend())
.setMinApi(parameters.getApiLevel())
.addProgramClasses(TestClass.class)
.addProgramClassFileData(junitClasses)
.addKeepAllClassesRule()
.addOptionsModification(options -> options.lookupLibraryBeforeProgram = false)
.compile()
.assertOnlyWarnings();
String[] libraryClassesExtendingTestCase = new String[]{
"android.test.InstrumentationTestCase",
"android.test.AndroidTestCase",
"android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests"
};
result.getDiagnosticMessages().assertWarningsCount(libraryClassesExtendingTestCase.length);
for (String name : libraryClassesExtendingTestCase) {
result
.assertWarningMessageThatMatches(
containsString(
"Library class " + name + " extends program class junit.framework.TestCase"));
}
}
@Test
public void testWithDontWarn() throws Exception {
assumeTrue("Only run for Dex backend", parameters.isDexRuntime());
testForR8(parameters.getBackend())
.setMinApi(parameters.getApiLevel())
.addProgramClassFileData(junitClasses)
.addKeepAllClassesRule()
.addKeepRules("-dontwarn android.test.**")
.addOptionsModification(options -> options.lookupLibraryBeforeProgram = false)
.compile()
.assertNoMessages();
}
static class TestClass {
public static void main(String[] args) throws Exception {
// Ensure that the problematic library types are actually live.
Class.forName("android.test.InstrumentationTestCase").getDeclaredConstructor().newInstance();
Class.forName("android.test.AndroidTestCase").getDeclaredConstructor().newInstance();
Class.forName("android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests")
.getDeclaredConstructor()
.newInstance();
}
}
}
| 37.740741 | 99 | 0.722697 |
cd04c335d2e8496b34e81da6ea5fb444c3141e16 | 3,451 | package cronapi.rest;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import cronapi.QueryManager;
import cronapi.util.Operations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/js/system-events.js")
public class ImportEventsREST {
private static JsonObject JSON;
static {
JSON = loadJSON();
}
private static JsonObject loadJSON() {
ClassLoader classLoader = QueryManager.class.getClassLoader();
try (InputStream stream = classLoader.getResourceAsStream("META-INF/events.json")) {
InputStreamReader reader = new InputStreamReader(stream);
JsonElement jsonElement = new JsonParser().parse(reader);
return jsonElement.getAsJsonObject();
}
catch(Exception e) {
return new JsonObject();
}
}
private static JsonObject getJSON() {
if(Operations.IS_DEBUG) {
return loadJSON();
}
else {
return JSON;
}
}
private static boolean isNull(JsonElement value) {
return value == null || value.isJsonNull();
}
@RequestMapping(method = RequestMethod.GET)
public void listEvents(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/javascript");
PrintWriter out = response.getWriter();
out.println("window.blockly = window.blockly || {};");
out.println("window.blockly.events = window.blockly.events || {};");
for(Map.Entry<String, JsonElement> entry : getJSON().entrySet()) {
if(!isNull(entry.getValue())) {
JsonObject customObj = entry.getValue().getAsJsonObject();
if (customObj.get("type") != null && !customObj.get("type").isJsonNull() && customObj.get("type").getAsString().equals("client")) {
write(out, entry.getKey(), customObj);
}
}
}
}
private void write(PrintWriter out, String eventName, JsonObject eventObj) {
String namespace = "window.blockly.events." + eventName;
// Try to set the 'window.blockly.events.{eventName}' with the blockly method reference
StringBuilder sb = new StringBuilder("try{ ");
sb.append(namespace);
if (!isNull(eventObj.get("blockly"))) {
String blocklyNamespace = eventObj.get("blockly").getAsJsonObject().get("namespace").getAsString();
String method = Operations.safeNameForMethodBlockly(eventObj.get("blocklyMethod").getAsString());
sb.append(" = blockly.").append(blocklyNamespace).append(".").append(method).append(";");
sb.append(" } catch(ex){ ");
// If it is not possible to add the reference (Blockly not found due to be from other project - mobile/web) set the reference as String
sb.append(namespace).append(" = 'blockly.").append(blocklyNamespace).append(".").append(method).append("';");
sb.append(" }");
} else {
// No event to be added
sb.append(" = {}; } catch(ex){ }");
}
out.println(sb.toString());
}
}
| 36.326316 | 141 | 0.700377 |
9597cf24ebf6c768f06e351d9388f5d3b99683f8 | 244 | package com.github.mikesafonov.smpp.core.exceptions;
/**
* @author Mike Safonov
*/
public class ResponseClientBindException extends RuntimeException {
public ResponseClientBindException(String message) {
super(message);
}
}
| 20.333333 | 67 | 0.741803 |
6e502770ad51feee93b25d595c84964b91a8a849 | 600 | /**
* A grafikus valtozathoz tartozo Main osztaly, mely tartalmazza a main() fuggvenyt.
*/
public class Main {
public static void main(String[] args) {
View view = new View();
Game game = new Game();
GameMap gameMap = new GameMap();
Timer timer = Timer.instance();
timer.setGamemap(gameMap);
timer.setGame(game);
timer.setView(view);
GameFrame gf = new GameFrame(gameMap, game, view, timer);
timer.setGameFrame(gf);
game.setGameFrame(gf);
Menu menu = new Menu(game, gf, timer);
timer.Tick();
}
} | 25 | 84 | 0.596667 |
3bdf7bcd5045710a670181278b4359c33e457566 | 5,514 | package echodot.mode.listen;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
/**
*
* @author 650016706
*
* This thread-safe singleton acts as a microphone controller, being able to
* enable/disable and to record audio input.
*/
public class Microphone {
private static volatile Microphone instance;
private static final String FILE_FORMAT = ".wav";
private static final String OUTPUT_DIRECTORY = "recordings/";
private static final int SAMPLE_RATE = 16000; // MHz
private static final int SAMPLE_SIZE = 16; // bits
private static final int SAMPLE_CHANNELS = 1; // mono
private Microphone(){}
/**
* Synchronized method which makes sure only one instance of this class
* can be created.
*
* @return an instance of the Microphone class
*/
public static Microphone getInstance(){
if(instance == null){
synchronized(Microphone.class){
if(instance == null){
instance = new Microphone();
}
}
}
return instance;
}
/**
* Sets the audio format and tries to set up an audio input stream.
*
* @return the microphone input stream or null if no device is available
*/
private static synchronized AudioInputStream setupStream(){
try{
AudioFormat audioFormat = new AudioFormat(SAMPLE_RATE,
SAMPLE_SIZE,
SAMPLE_CHANNELS
, true, true);
Info info = new Info(TargetDataLine.class, audioFormat);
TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
AudioInputStream stream = new AudioInputStream(line);
line.open(audioFormat);
line.start();
return stream;
} catch(LineUnavailableException e){
System.out.println(e);
return null;
}
}
/**
* Reads an audio input stream and puts its raw contents into an output stream.
*
* @param timer the intended duration for the sound
* @param inputStream contains the stream for the audio input
* @return
*/
private static synchronized ByteArrayOutputStream readStream(int timer,
AudioInputStream inputStream){
try{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int bufferSize = SAMPLE_RATE * inputStream.getFormat().getFrameSize();
byte buffer[] = new byte[bufferSize];
for(int counter = timer; counter > 0; counter--){
int rawSound = inputStream.read(buffer, 0, buffer.length);
if(rawSound > 0){
outputStream.write(buffer, 0, rawSound);
}
else{
break;
}
}
return outputStream;
} catch(Exception e){
System.out.println(e);
return null;
}
}
/**
* Records sound from a byte array stream and writes its contents to a wav
* file which name is given by the current timestamp.
*
* @param stream
*/
private static synchronized String recordSound(ByteArrayOutputStream stream){
try{
File file;
File outputDirectory = new File(OUTPUT_DIRECTORY);
AudioFormat audioFormat = new AudioFormat(SAMPLE_RATE,
SAMPLE_SIZE,
SAMPLE_CHANNELS
, true, true);
byte[] byteArray = stream.toByteArray();
InputStream inputStream = new ByteArrayInputStream(byteArray);
AudioInputStream audioInputStream = new AudioInputStream(inputStream,
audioFormat,
byteArray.length);
String outputFileName = new SimpleDateFormat("dd-MM-YYYY--HH-mm-ss")
.format(new java.util.Date());
outputFileName = OUTPUT_DIRECTORY + outputFileName;
outputFileName += FILE_FORMAT;
outputDirectory.mkdir();
file = new File(outputFileName);
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, file);
return outputFileName;
} catch(IOException e){
System.out.println(e);
return null;
}
}
public synchronized String getSound(int timer){
AudioInputStream stream = setupStream();
return recordSound(readStream(timer, stream));
}
}
| 36.76 | 87 | 0.551505 |
659831f9c7e359d7bed3a222b403881a8461ba46 | 253 | package ru.job4j.professionsuse;
public class House {
int height;
int lenght;
int width;
public House(int height, int lenght, int width) {
this.height = height;
this.lenght = lenght;
this.width = width;
}
}
| 18.071429 | 53 | 0.604743 |
081dcf62ab0b4bfe31a640c4b2e9fe2a540cf831 | 445 | package io.microservices.demo.referencemanagement.repository;
import io.microservices.demo.referencemanagement.domain.PaperCollectionId;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the PaperCollectionId entity.
*/
@SuppressWarnings("unused")
@Repository
public interface PaperCollectionIdRepository extends JpaRepository<PaperCollectionId, Long> {
}
| 29.666667 | 93 | 0.833708 |
1f3a31d7418ad6e58768f70042421a457ce4a373 | 880 | import java.util.Scanner;
/**
* Created by George-Lenovo on 4/5/2017.
*/
public class VowelOrDigit {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char ch = in.next().charAt(0);
if (isCharVowel(ch)) {
System.out.println("vowel");
} else if (isCharDigit(ch)) {
System.out.println("digit");
} else
System.out.println("other");
}
private static boolean isCharDigit(char ch) {
if ((int) ch >= 48 && (int) ch <= 57)
return true;
return false;
}
private static boolean isCharVowel(char ch) {
if ((int) ch == 97 || (int) ch == 65 || (int) ch == 101 || (int) ch == 105 || (int) ch == 73 || (int) ch == 111 || (int) ch == 79 || (int) ch == 117 || (int) ch == 85)
return true;
return false;
}
}
| 27.5 | 175 | 0.5125 |
22c28ae23f4c3a2ac7f0a9fd78f10fe154f55dcf | 9,818 | package com.luneruniverse.minecraft.mod.nbteditor.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import com.google.gson.JsonParseException;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.network.packet.c2s.play.CreativeInventoryActionC2SPacket;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.ClickEvent.Action;
import net.minecraft.text.MutableText;
import net.minecraft.text.StringVisitable.StyledVisitor;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Formatting;
import net.minecraft.util.Hand;
import net.minecraft.util.Identifier;
public class MainUtil {
public static final MinecraftClient client = MinecraftClient.getInstance();
public static Map.Entry<Hand, ItemStack> getHeldItem(ClientPlayerEntity player, Predicate<ItemStack> isAllowed, Text failText) throws CommandSyntaxException {
ItemStack item = player.getMainHandStack();
Hand hand = Hand.MAIN_HAND;
if (item == null || item.isEmpty() || !isAllowed.test(item)) {
item = player.getOffHandStack();
hand = Hand.OFF_HAND;
}
if (item == null || item.isEmpty() || !isAllowed.test(item))
throw new SimpleCommandExceptionType(failText).create();
return Map.entry(hand, item);
}
public static Map.Entry<Hand, ItemStack> getHeldItem(ClientPlayerEntity player) throws CommandSyntaxException {
return getHeldItem(player, item -> true, Text.translatable("nbteditor.noitem"));
}
public static void saveItem(Hand hand, ItemStack item) {
client.player.setStackInHand(hand, item.copy());
if (client.interactionManager.getCurrentGameMode().isCreative())
client.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(hand == Hand.OFF_HAND ? 45 : client.player.getInventory().selectedSlot + 36, item));
}
public static void saveItem(EquipmentSlot equipment, ItemStack item) {
if (equipment == EquipmentSlot.MAINHAND)
saveItem(Hand.MAIN_HAND, item);
else if (equipment == EquipmentSlot.OFFHAND)
saveItem(Hand.OFF_HAND, item);
else {
client.player.getInventory().armor.set(equipment.getEntitySlotId(), item.copy());
client.interactionManager.clickCreativeStack(item, 8 - equipment.getEntitySlotId());
}
}
public static void saveItem(int slot, ItemStack item) {
client.player.getInventory().setStack(slot, item.copy());
client.interactionManager.clickCreativeStack(item, slot < 9 ? slot + 36 : slot);
}
public static void saveItemInvSlot(int slot, ItemStack item) {
saveItem(slot == 45 ? 45 : (slot >= 36 ? slot - 36 : slot), item);
}
private static final Identifier LOGO = new Identifier("nbteditor", "textures/logo.png");
public static void renderLogo(MatrixStack matrices) {
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderTexture(0, LOGO);
Screen.drawTexture(matrices, 16, 16, 0, 0, 32, 32, 32, 32);
}
public static void drawWrappingString(MatrixStack matrices, TextRenderer renderer, String text, int x, int y, int maxWidth, int color, boolean centerHorizontal, boolean centerVertical) {
// Split into breaking spots
List<String> parts = new ArrayList<>();
List<Integer> spaces = new ArrayList<>();
StringBuilder currentPart = new StringBuilder();
boolean wasUpperCase = false;
for (char c : text.toCharArray()) {
if (c == ' ') {
wasUpperCase = false;
parts.add(currentPart.toString());
currentPart.setLength(0);
spaces.add(parts.size());
continue;
}
boolean upperCase = Character.isUpperCase(c);
if (upperCase != wasUpperCase && !currentPart.isEmpty()) { // Handle NBTEditor; output NBT, Editor; not N, B, T, Editor AND Handle MinionYT; output Minion YT
if (wasUpperCase) {
parts.add(currentPart.substring(0, currentPart.length() - 1));
currentPart.delete(0, currentPart.length() - 1);
} else {
parts.add(currentPart.toString());
currentPart.setLength(0);
}
}
wasUpperCase = upperCase;
currentPart.append(c);
}
if (!currentPart.isEmpty())
parts.add(currentPart.toString());
// Generate lines, maximizing the number of parts per line
List<String> lines = new ArrayList<>();
String line = "";
int i = 0;
for (String part : parts) {
String partAddition = (!line.isEmpty() && spaces.contains(i) ? " " : "") + part;
if (renderer.getWidth(line + partAddition) > maxWidth) {
if (!line.isEmpty()) {
lines.add(line);
line = "";
}
if (renderer.getWidth(part) > maxWidth) {
while (true) {
int numChars = 1;
while (renderer.getWidth(part.substring(0, numChars)) < maxWidth)
numChars++;
numChars--;
lines.add(part.substring(0, numChars));
part = part.substring(numChars);
if (renderer.getWidth(part) < maxWidth) {
line = part;
break;
}
}
} else
line = part;
} else
line += partAddition;
i++;
}
if (!line.isEmpty())
lines.add(line);
// Draw the lines
for (i = 0; i < lines.size(); i++) {
line = lines.get(i);
int offsetY = i * renderer.fontHeight + (centerVertical ? -renderer.fontHeight * lines.size() / 2 : 0);
if (centerHorizontal)
Screen.drawCenteredTextWithShadow(matrices, renderer, Text.of(line).asOrderedText(), x, y + offsetY, color);
else
Screen.drawTextWithShadow(matrices, renderer, Text.of(line), x, y + offsetY, color);
}
}
public static String colorize(String text) {
StringBuilder output = new StringBuilder();
boolean colorCode = false;
for (char c : text.toCharArray()) {
if (c == '&')
colorCode = true;
else {
if (colorCode) {
colorCode = false;
if ((c + "").replaceAll("[0-9a-fA-Fk-oK-OrR]", "").isEmpty())
output.append('§');
else
output.append('&');
}
output.append(c);
}
}
if (colorCode)
output.append('&');
return output.toString();
}
public static String stripColor(String text) {
return text.replaceAll("\\xA7[0-9a-fA-Fk-oK-OrR]", "");
}
public static Text getItemNameSafely(ItemStack item) {
NbtCompound nbtCompound = item.getSubNbt(ItemStack.DISPLAY_KEY);
if (nbtCompound != null && nbtCompound.contains(ItemStack.NAME_KEY, 8)) {
try {
MutableText text = Text.Serializer.fromJson(nbtCompound.getString(ItemStack.NAME_KEY));
if (text != null) {
return text;
}
}
catch (JsonParseException text) {
}
}
return item.getItem().getName(item);
}
public static MutableText getLongTranslatableText(String key) {
MutableText output = Text.translatable(key + "_1");
for (int i = 2; true; i++) {
Text line = Text.translatable(key + "_" + i);
String str = line.getString();
if (str.equals(key + "_" + i) || i > 50)
break;
if (str.startsWith("[LINK] ")) {
String url = str.substring("[LINK] ".length());
line = Text.literal(url).styled(style -> style.withClickEvent(new ClickEvent(Action.OPEN_URL, url))
.withUnderline(true).withItalic(true).withColor(Formatting.GOLD));
}
output.append("\n").append(line);
}
return output;
}
public static DyeColor getDyeColor(Formatting color) {
switch (color) {
case AQUA:
return DyeColor.LIGHT_BLUE;
case BLACK:
return DyeColor.BLACK;
case BLUE:
return DyeColor.BLUE;
case DARK_AQUA:
return DyeColor.CYAN;
case DARK_BLUE:
return DyeColor.BLUE;
case DARK_GRAY:
return DyeColor.GRAY;
case DARK_GREEN:
return DyeColor.GREEN;
case DARK_PURPLE:
return DyeColor.PURPLE;
case DARK_RED:
return DyeColor.RED;
case GOLD:
return DyeColor.ORANGE;
case GRAY:
return DyeColor.LIGHT_GRAY;
case GREEN:
return DyeColor.LIME;
case LIGHT_PURPLE:
return DyeColor.PINK;
case RED:
return DyeColor.RED;
case WHITE:
return DyeColor.WHITE;
case YELLOW:
return DyeColor.YELLOW;
default:
return DyeColor.BROWN;
}
}
public static Text substring(Text text, int start, int end) {
MutableText output = Text.literal("");
text.visit(new StyledVisitor<Boolean>() {
private int i;
@Override
public Optional<Boolean> accept(Style style, String str) {
if (i + str.length() <= start) {
i += str.length();
return Optional.empty();
}
if (i >= start) {
if (end >= 0 && i + str.length() > end)
return accept(style, str.substring(0, end - i));
output.append(Text.literal(str).fillStyle(style));
i += str.length();
if (end >= 0 && i == end)
return Optional.of(true);
return Optional.empty();
} else {
str = str.substring(start - i);
i = start;
accept(style, str);
return Optional.empty();
}
}
}, Style.EMPTY);
return output;
}
public static Text substring(Text text, int start) {
return substring(text, start, -1);
}
}
| 32.61794 | 188 | 0.656447 |
ebc7e487603fd4c049aa4fc4d01eaf8fc9d0cafc | 762 | package ca.bc.gov.educ.api.edx.repository;
import ca.bc.gov.educ.api.edx.model.v1.EdxActivationCodeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface EdxActivationCodeRepository extends JpaRepository<EdxActivationCodeEntity, UUID> {
List<EdxActivationCodeEntity> findEdxActivationCodeByActivationCodeInAndMincode(List<String> activationCode, String mincode);
List<EdxActivationCodeEntity> findEdxActivationCodeEntitiesByValidationCode(UUID userActivationValidationCode);
Optional<EdxActivationCodeEntity> findEdxActivationCodeEntitiesByMincodeAndIsPrimaryTrue(String mincode);
}
| 38.1 | 127 | 0.862205 |
3abd6af96201e42590c212bfb1dc013bfab0c9e3 | 204 | package com.works.repositories;
import com.works.model.Vendor;
import org.springframework.data.jpa.repository.JpaRepository;
public interface VendorRepository extends JpaRepository<Vendor,Integer> {
}
| 22.666667 | 73 | 0.833333 |
a005b06a81d30ab48dc972850adfb293b012bfc1 | 4,806 | package ui;
import java.util.List;
import dao.PosedujeDAO;
import model.Klijent;
import model.Vozilo;
import utils.PomocnaKlasa;
public class PosedujeUI {
private static void ispisiMeni() {
System.out.println("*********************************************************************************************************");
System.out.println("***********************************AUTO SERVIS**********************************************************");
System.out.println("Rad sa posedovanjima klijenta - opcije: ");
System.out.println("\tOpcija 1 - Ispis vozila koja klijent poseduje");
System.out.println("\tOpcija 2 - Ispis vlasnika za traženo vozilo");
System.out.println("\tOpcija 3 - Dodavanje vozila vlasniku");
System.out.println("\tOpcija 4 - Uklanjanje vlasništva nad vozilom");
System.out.println("\t\t ...");
System.out.println("\tOpcija 0 - IZLAZ u prethodni meni");
System.out.println("*********************************************************************************************************");
}
public static void meniPosedujeUI() {
int odluka = -1;
while( odluka != 0 ) {
ispisiMeni();
System.out.println("opcija:");
odluka = PomocnaKlasa.ocitajCeoBroj();
switch( odluka ) {
case 0:
System.out.println("Izlaz iz menija za posedovanja");
break;
case 1:
ispisiVozilaZaKlijenta();
break;
case 2:
ispisiKlijentaZaVozilo();
break;
case 3:
dodajVoziloNaKlijenta();
break;
case 4:
ukloniVlasništvoNadVozilom();
break;
default:
System.out.println("Nepostojeća komanda.");
break;
}
}
}
/**
* Dodavanje vozila vlasniku
*
* prvo pronađemo klijenta na koga želimo da dodamo vozilo zatim pronađemo
* vozilo koje želimo da dodamo na klijenta
**/
public static void dodajVoziloNaKlijenta() {
System.out.println("*****Dodavanje vozila klijentu*********");
// prvo pronađemo vozilo koje želimo dodati na klijenta
Vozilo vozilo = VoziloUI.pronadjiVozilo();
// pronađemo klijenta na koga želimo dodati vozilo
Klijent klijent = KlijentUI.pronadjiKlijenta();
if (vozilo != null && klijent != null) {
// uspostavimo vezu između vozila i klijenta
PosedujeDAO.add(ApplicationUI.getConn(), klijent.getId(), vozilo.getId());
System.out.println(" Vozilo uspešno dodato i promena evidentirana u podacima klijenta.");
}
}
private static void ispisiVozilaZaKlijenta() {
System.out.println("** Traženje vozila za vlasnika ********");
// prvo pronađemo klijenta za koga želimo ispis vozila
Klijent klijent = KlijentUI.pronadjiKlijenta();
if (klijent != null) {
List<Vozilo> vozila = PosedujeDAO.getVozilaByKlijentID(ApplicationUI.getConn(), klijent.getId());
System.out.printf("%-5s %-20s", "id", "registracija");
System.out.println();
System.out.println("===== ====================");
for (Vozilo v : vozila) {
System.out.printf("%-5s %-20s", v.getId(), v.getRegistracija());
System.out.println();
}
System.out.println("*******kraj liste posedovanja**********");
System.out.println("***************************************");
}
else {
System.out.println("**Ne postoje podaci o klijentu/vozilu**");
System.out.println("***************************************");
}
}
private static String ispisiKlijentaZaVozilo() {
System.out.println("** Traženje vlasnika za vozilo ********");
// pronađemo vozilo za koga želimo ispis klijenta
Vozilo vozilo = VoziloUI.pronadjiVozilo();
if (vozilo != null) {
Klijent vlasnik = PosedujeDAO.getVlasnikByVoziloID(ApplicationUI.getConn(), vozilo.getId());
// int id, String ime, String prezime, String prebivaliste, String telefon;
System.out.println();
System.out.printf(" %-3s %-20s %-20s %-20s %-12s", "id", "ime", "prezime", "prebivalište", "telefon"); System.out.println();
System.out.println("=== ==================== ==================== ==================== ============");
System.out.printf("%-3s %-20s %-20s %-20s %-12s",
vlasnik.getId(),
vlasnik.getIme(),
vlasnik.getPrezime(),
vlasnik.getPrebivaliste(),
vlasnik.getTelefon());
System.out.println();
}
String poruka = "Vozilo nema vlasnika! Brzo to ispravi!";
return poruka;
}
private static void ukloniVlasništvoNadVozilom() {
// prvo pronađemo klijenta koga uklanjamo sa vozila
Klijent vlasnik = KlijentUI.pronadjiKlijenta();
// zatim pronađemo vozilo s akoga želimo ukloniti vlasnika
Vozilo vozilo = VoziloUI.pronadjiVozilo();
if(vlasnik != null && vozilo != null) {
// izbrišemo vezu između vlasnika i vozila
PosedujeDAO.delete(ApplicationUI.getConn(), vlasnik.getId(), vozilo.getId());
System.out.println("Vozilo uspešno uklonjeno i promena evidentirana u podacima klijenta.");
}
}
}
| 31.618421 | 130 | 0.608406 |
780a3b5a6aab9ffecb2438d24334ded828570005 | 713 | package asch.io.wallet.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import asch.io.base.util.ActivityUtils;
import asch.io.wallet.R;
import asch.io.wallet.view.fragment.AccountInfoFragment;
/**
* Created by kimziv on 2017/12/11.
*/
public class AccountInfoActivity extends TitleToolbarActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.personal_center));
AccountInfoFragment fragment = AccountInfoFragment.newInstance("","");
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),fragment, R.id.fragment_container);
}
}
| 28.52 | 107 | 0.764376 |
3d427f133dcb2e6734c57fdfcd4912e977c09832 | 223 | package net.objectlab.kit.util;
public class SampleStandardDeviation extends PopulationStandardDeviation {
@Override
protected long getDataPointsForCalc() {
return super.getDataPointsForCalc() - 1;
}
}
| 24.777778 | 74 | 0.748879 |
b7d8b0260e1ae96e2cbc746e2519f703fa1873d7 | 266 | package runtime;
/***
* @description: System.getProperty( ) method
* @author rui.chow
* @date 2020/12/10
*/
public class ShowUserDir {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
}
}
| 14.777778 | 59 | 0.620301 |
b06ce170f4d1236786a730ef2dbb065066ff5eaf | 423 | package ca.wescook.nutrition.proxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
public interface IProxy {
void preInit(FMLPreInitializationEvent event);
void init(FMLInitializationEvent event);
void postInit(FMLPostInitializationEvent event);
}
| 35.25 | 70 | 0.836879 |
320dd079aa99ac75167b3176ad5c5b552aaa956d | 13,597 | package com.tdlzgroup.educasa.Inicio.InicioFragments;
import android.Manifest;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.tdlzgroup.educasa.R;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
public class InicioMapaFragmen extends FragmentActivity implements OnMapReadyCallback {
private FusedLocationProviderClient mFusedLocationProviderClient;
private Location mLastKnownLocation;
private boolean mLocationPermissionGranted;
static final int DEFAULT_ZOOM = 15;
static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private LatLng ubicacionLatLng;
//private LatLng puntofinal;
private GoogleMap mMap;
private Button button;
private double latitudeDefault;
private double longitudeDefault;
private double latitudeBundle;
private double longitudeBundle;
private float zoom;
private Context context;
private Location currentLocation;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_mapa);
context = this;
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//fetchLastLocation();
latitudeDefault = -16.4010344;
longitudeDefault = -71.533039;
latitudeBundle = 0;
longitudeBundle = 0;
//ubicacionLatLng = new LatLng(-16.4010344, -71.533039);
zoom = 12f;
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("latitude")) {
// when LatLng Bundle exist
latitudeBundle = extras.getDouble("latitude", 0);
longitudeBundle = extras.getDouble("longitude", 0);
}
}
if (latitudeBundle != 0 && longitudeBundle != 0) {
ubicacionLatLng = new LatLng(latitudeBundle, longitudeBundle);
zoom = 18f;
Toast.makeText(context, "ifbundle", Toast.LENGTH_SHORT).show();
}
else {
ubicacionLatLng = new LatLng(latitudeDefault, longitudeDefault);
Toast.makeText(context, "elsebundle", Toast.LENGTH_SHORT).show();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); //referencia para acceder a la aplicacion
button = findViewById(R.id.mapa_btn_listo);
}
private void fetchLastLocation() {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(InicioMapaFragmen.this, "" + currentLocation.getLatitude() + "//" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(InicioMapaFragmen.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(this, R.raw.mapa_style));
getLocationPermission();
updateLocationUI();
if (mLocationPermissionGranted) {
if (latitudeBundle == 0 && longitudeBundle == 0) {
getDeviceLocation(false);
}
else {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ubicacionLatLng, zoom));
}
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
}
});
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
//LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);getDeviceLocation
activarUbicacion();
getDeviceLocation(true);
//fetchLastLocation();
return false;
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
@Override
public void onMarkerDragStart(Marker marker) {
}
@Override
public void onMarkerDrag(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
}
});
button.setOnClickListener(mibtn -> {
LatLng center = mMap.getCameraPosition().target;
Intent resultIntent = new Intent();
resultIntent.putExtra("latitude", center.latitude);
resultIntent.putExtra("longitude", center.longitude);
setResult(RESULT_OK, resultIntent);
finish();
});
}
private void activarUbicacion() {
LocationManager lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
new AlertDialog.Builder(context)
.setTitle("GPS Desactivado !")
.setMessage("Debe activar el GPS de su celular...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("Cancelar", null)
.show();
}
}
private void getDeviceLocation(boolean move) {
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ubicacionLatLng,zoom));
try {
if (mLocationPermissionGranted) {
final Task<Location> location = mFusedLocationProviderClient.getLastLocation();
location.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
latitudeDefault = currentLocation.getLatitude();
longitudeDefault = currentLocation.getLongitude();
if (move) {
CameraUpdate locationLatLng = CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeDefault,longitudeDefault),18);
mMap.animateCamera(locationLatLng);
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudeDefault,longitudeDefault), 17));
}
else {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ubicacionLatLng, zoom));
}
Toast.makeText(InicioMapaFragmen.this, "if task", Toast.LENGTH_SHORT).show();
//SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
//supportMapFragment.getMapAsync(InicioMapaFragmen.this);
}
else {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ubicacionLatLng, zoom));
Toast.makeText(InicioMapaFragmen.this, "else task", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
public Bitmap resizeMapIcons(Bitmap drawable, int width, int height) {
Bitmap resizeBitmap = Bitmap.createScaledBitmap(drawable, width, height, false);
return resizeBitmap;
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
updateLocationUI();
}
}
case REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//fetchLastLocation();
}
}
break;
}
}
private void updateLocationUI() {
if (mMap == null) return;
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
getDeviceLocation(false);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
}
| 41.966049 | 222 | 0.615798 |
5ad1358a92ce3034f14ac2f3133443a0963cf62c | 343 | package cn.com.allunion.common.validation;
/**
* 验证组接口
* @author yang.jie
* @email [email protected]
* @date 2016/5/27.
* @copyright <url>http://www.all-union.com.cn/</url>
*/
public interface ValidationGroup extends Validation {
/**
* 设置验证未通过提示
* @return 验证未通过提示
*/
void setErrorTip(String errorTip) ;
}
| 20.176471 | 53 | 0.650146 |
50f43ffaf5e00d46d36cf2151de3d1dd43ac40fa | 25,575 | /*
* Copyright 2014 gitblit.com.
*
* 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.gitblit.plugin.powertools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import com.gitblit.Constants.AccessRestrictionType;
import com.gitblit.Constants.AuthorizationControl;
import com.gitblit.Constants.CommitMessageRenderer;
import com.gitblit.Constants.FederationStrategy;
import com.gitblit.GitBlitException;
import com.gitblit.Keys;
import com.gitblit.manager.IGitblit;
import com.gitblit.models.RegistrantAccessPermission;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.UserModel;
import com.gitblit.transport.ssh.commands.CommandMetaData;
import com.gitblit.transport.ssh.commands.DispatchCommand;
import com.gitblit.transport.ssh.commands.ListFilterCommand;
import com.gitblit.transport.ssh.commands.SshCommand;
import com.gitblit.transport.ssh.commands.UsageExample;
import com.gitblit.transport.ssh.commands.UsageExamples;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.FileUtils;
import com.gitblit.utils.FlipTable;
import com.gitblit.utils.FlipTable.Borders;
import com.gitblit.utils.StringUtils;
import com.google.common.base.Joiner;
@CommandMetaData(name = "repositories", aliases = { "repos" }, description = "Repository management commands")
public class RepositoriesDispatcher extends DispatchCommand {
@Override
protected void setup() {
// primary commands
register(NewRepository.class);
register(RenameRepository.class);
register(RemoveRepository.class);
register(ShowRepository.class);
register(ForkRepository.class);
register(ListRepositories.class);
// repository-specific commands
register(SetField.class);
}
public static abstract class RepositoryCommand extends SshCommand {
@Argument(index = 0, required = true, metaVar = "REPOSITORY", usage = "repository")
protected String repository;
protected RepositoryModel getRepository(boolean requireRepository) throws UnloggedFailure {
IGitblit gitblit = getContext().getGitblit();
RepositoryModel repo = gitblit.getRepositoryModel(repository);
if (requireRepository && repo == null) {
throw new UnloggedFailure(1, String.format("Repository %s does not exist!", repository));
}
return repo;
}
protected String sanitize(String name) throws UnloggedFailure {
// automatically convert backslashes to forward slashes
name = name.replace('\\', '/');
// Automatically replace // with /
name = name.replace("//", "/");
// prohibit folder paths
if (name.startsWith("/")) {
throw new UnloggedFailure(1, "Illegal leading slash");
}
if (name.startsWith("../")) {
throw new UnloggedFailure(1, "Illegal relative slash");
}
if (name.contains("/../")) {
throw new UnloggedFailure(1, "Illegal relative slash");
}
if (name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
return name;
}
protected String getRepositoryUrl() {
return getRepositoryUrl(repository);
}
}
@CommandMetaData(name = "new", aliases = { "add" }, description = "Create a new repository")
@UsageExamples(examples = {
@UsageExample(syntax = "${cmd} myRepo", description = "Create a repository named 'myRepo'"),
@UsageExample(syntax = "${cmd} myMirror --mirror https://github.com/gitblit/gitblit.git",
description = "Create a mirror named 'myMirror'"),
})
public static class NewRepository extends RepositoryCommand {
@Option(name = "--mirror", aliases = {"-m" }, metaVar = "URL", usage = "URL of repository to mirror")
String src;
@Override
public void run() throws Failure {
UserModel user = getContext().getClient().getUser();
String name = sanitize(repository);
if (!name.endsWith(Constants.DOT_GIT)) {
name += Constants.DOT_GIT;
}
if (!user.canCreate(name)) {
// try to prepend personal path
String path = StringUtils.getFirstPathElement(name);
if ("".equals(path)) {
name = user.getPersonalPath() + "/" + name;
}
}
if (getRepository(false) != null) {
throw new UnloggedFailure(1, String.format("Repository %s already exists!", name));
}
if (!user.canCreate(name)) {
throw new UnloggedFailure(1, String.format("Sorry, you do not have permission to create %s", name));
}
IGitblit gitblit = getContext().getGitblit();
if (!StringUtils.isEmpty(src)) {
// Mirror repository
// JGit doesn't support --mirror so we have to accomplish this in a few steps
File repositoriesFolder = gitblit.getRepositoriesFolder();
File repoFolder = new File(repositoriesFolder, name);
Repository repository = null;
try {
// step 1: clone what we can
CloneCommand clone = new CloneCommand();
clone.setBare(true);
clone.setCloneAllBranches(true);
clone.setURI(src);
clone.setDirectory(repoFolder);
clone.setProgressMonitor(NullProgressMonitor.INSTANCE);
repository = clone.call().getRepository();
// step 2: update config to modify refspecs and flag as mirror
StoredConfig config = repository.getConfig();
config.setString("remote", "origin", "fetch", "+refs/*:refs/*");
config.setBoolean("remote", "origin", "mirror", true);
config.save();
// step 3: fetch
Git git = new Git(repository);
git.fetch().setProgressMonitor(NullProgressMonitor.INSTANCE).call();
} catch (GitAPIException |IOException e) {
if (repoFolder.exists()) {
FileUtils.delete(repoFolder);
}
throw new Failure(1, String.format("Failed to mirror %s", src), e);
} finally {
if (repository != null) {
repository.close();
}
}
}
// Standard create repository
RepositoryModel repo = new RepositoryModel();
repo.name = name;
repo.projectPath = StringUtils.getFirstPathElement(name);
String restriction = gitblit.getSettings().getString(Keys.git.defaultAccessRestriction, "PUSH");
repo.accessRestriction = AccessRestrictionType.fromName(restriction);
String authorization = gitblit.getSettings().getString(Keys.git.defaultAuthorizationControl, null);
repo.authorizationControl = AuthorizationControl.fromName(authorization);
if (user.isMyPersonalRepository(name)) {
// personal repositories are private by default
repo.addOwner(user.username);
repo.accessRestriction = AccessRestrictionType.VIEW;
repo.authorizationControl = AuthorizationControl.NAMED;
}
try {
gitblit.updateRepositoryModel(repo.name, repo, StringUtils.isEmpty(src));
if (StringUtils.isEmpty(src)) {
stdout.println(String.format("'%s' created.", repo.name));
} else {
stdout.println(String.format("'%s' created as mirror of %s.", repo.name, src));
}
} catch (GitBlitException e) {
log.error("Failed to add " + repository, e);
throw new UnloggedFailure(1, e.getMessage());
}
}
}
@CommandMetaData(name = "rename", aliases = { "mv" }, description = "Rename a repository")
@UsageExample(syntax = "${cmd} myRepo.git otherRepo.git", description = "Rename the repository from myRepo.git to otherRepo.git")
public static class RenameRepository extends RepositoryCommand {
@Argument(index = 1, required = true, metaVar = "NEWNAME", usage = "the new repository name")
protected String newRepositoryName;
@Override
public void run() throws UnloggedFailure {
RepositoryModel repo = getRepository(true);
IGitblit gitblit = getContext().getGitblit();
UserModel user = getContext().getClient().getUser();
String name = sanitize(newRepositoryName);
if (!user.canCreate(name)) {
// try to prepend personal path
String path = StringUtils.getFirstPathElement(name);
if ("".equals(path)) {
name = user.getPersonalPath() + "/" + name;
}
}
if (null != gitblit.getRepositoryModel(name)) {
throw new UnloggedFailure(1, String.format("Repository %s already exists!", name));
}
if (repo.name.equalsIgnoreCase(name)) {
throw new UnloggedFailure(1, "Repository names are identical");
}
if (!user.canAdmin(repo)) {
throw new UnloggedFailure(1, String.format("Sorry, you do not have permission to rename %s", repository));
}
if (!user.canCreate(name)) {
throw new UnloggedFailure(1, String.format("Sorry, you don't have permission to move %s to %s/", repository, name));
}
// set the new name
repo.name = name;
try {
gitblit.updateRepositoryModel(repository, repo, false);
stdout.println(String.format("Renamed repository %s to %s.", repository, name));
} catch (GitBlitException e) {
String msg = String.format("Failed to rename repository from %s to %s", repository, name);
log.error(msg, e);
throw new UnloggedFailure(1, msg);
}
}
}
@CommandMetaData(name = "set", description = "Set the specified field of a repository")
@UsageExample(syntax = "${cmd} myRepo description John's personal projects", description = "Set the description of a repository")
public static class SetField extends RepositoryCommand {
@Argument(index = 1, required = true, metaVar = "FIELD", usage = "the field to update")
protected String fieldName;
@Argument(index = 2, required = true, metaVar = "VALUE", usage = "the new value")
protected List<String> fieldValues = new ArrayList<String>();
protected enum Field {
acceptNewPatchsets, acceptNewTickets, accessRestriction, allowAuthenticated,
allowForks, authorizationControl, commitMessageRenderer, description,
federationSets, federationStrategy, frequency, gcThreshold, gcPeriod,
incrementalPushTagPrefix, isFederated, isFrozen, mailingLists,
maxActivityCommits, mergeTo, metricAuthorExclusions, owners, preReceiveScripts,
postReceiveScripts, requireApproval, showRemoteBranches, skipSizeCalculation,
skipSummaryMetrics, useIncrementalPushTags, verifyCommitter;
static Field fromString(String name) {
for (Field field : values()) {
if (field.name().equalsIgnoreCase(name)) {
return field;
}
}
return null;
}
}
@Override
protected String getUsageText() {
String fields = Joiner.on(", ").join(Field.values());
StringBuilder sb = new StringBuilder();
sb.append("Valid fields are:\n ").append(fields);
return sb.toString();
}
@Override
public void run() throws UnloggedFailure {
RepositoryModel repo = getRepository(true);
Field field = Field.fromString(fieldName);
if (field == null) {
throw new UnloggedFailure(1, String.format("Unknown field %s", fieldName));
}
if (!getContext().getClient().getUser().canAdmin(repo)) {
throw new UnloggedFailure(1, String.format("Sorry, you do not have permission to administer %s", repository));
}
String value = Joiner.on(" ").join(fieldValues).trim();
IGitblit gitblit = getContext().getGitblit();
switch(field) {
case acceptNewPatchsets:
repo.acceptNewPatchsets = toBool(value);
break;
case acceptNewTickets:
repo.acceptNewTickets = toBool(value);
break;
case accessRestriction:
repo.accessRestriction = AccessRestrictionType.fromName(value);
break;
case allowAuthenticated:
repo.allowAuthenticated = toBool(value);
break;
case allowForks:
repo.allowForks = toBool(value);
break;
case authorizationControl:
repo.authorizationControl = AuthorizationControl.fromName(value);
break;
case commitMessageRenderer:
repo.commitMessageRenderer = CommitMessageRenderer.fromName(value);
break;
case description:
repo.description = value;
break;
case federationSets:
repo.federationSets = fieldValues;
break;
case federationStrategy:
repo.federationStrategy = FederationStrategy.fromName(value);
break;
case frequency:
repo.frequency = value;
break;
case gcPeriod:
repo.gcPeriod = toInteger(value);
break;
case gcThreshold:
repo.gcThreshold = value;
break;
case incrementalPushTagPrefix:
repo.incrementalPushTagPrefix = value;
break;
case isFederated:
repo.isFederated = toBool(value);
break;
case isFrozen:
repo.isFrozen = toBool(value);
break;
case mailingLists:
repo.mailingLists = fieldValues;
break;
case maxActivityCommits:
repo.maxActivityCommits = toInteger(value);
break;
case mergeTo:
repo.mergeTo = value;
break;
case metricAuthorExclusions:
repo.metricAuthorExclusions = fieldValues;
break;
case owners:
repo.owners = fieldValues;
break;
case postReceiveScripts:
repo.postReceiveScripts = fieldValues;
break;
case preReceiveScripts:
repo.preReceiveScripts = fieldValues;
break;
case requireApproval:
repo.requireApproval = toBool(value);
break;
case showRemoteBranches:
repo.showRemoteBranches = toBool(value);
break;
case skipSizeCalculation:
repo.skipSizeCalculation = toBool(value);
break;
case skipSummaryMetrics:
repo.skipSummaryMetrics = toBool(value);
break;
case useIncrementalPushTags:
repo.useIncrementalPushTags = toBool(value);
break;
case verifyCommitter:
repo.verifyCommitter = toBool(value);
break;
default:
throw new UnloggedFailure(1, String.format("Field %s was not properly handled by the set command.", fieldName));
}
try {
gitblit.updateRepositoryModel(repo.name, repo, false);
stdout.println(String.format("Set %s.%s = %s", repo.name, fieldName, value));
} catch (GitBlitException e) {
String msg = String.format("Failed to set %s.%s = %s", repo.name, fieldName, value);
log.error(msg, e);
throw new UnloggedFailure(1, msg);
}
}
protected boolean toBool(String value) throws UnloggedFailure {
String v = value.toLowerCase();
if (v.equals("t")
|| v.equals("true")
|| v.equals("yes")
|| v.equals("on")
|| v.equals("y")
|| v.equals("1")) {
return true;
} else if (v.equals("f")
|| v.equals("false")
|| v.equals("no")
|| v.equals("off")
|| v.equals("n")
|| v.equals("0")) {
return false;
}
throw new UnloggedFailure(1, String.format("Invalid boolean value %s", value));
}
protected int toInteger(String value) throws UnloggedFailure {
try {
int i = Integer.parseInt(value);
return i;
} catch (NumberFormatException e) {
throw new UnloggedFailure(1, String.format("Invalid int value %s", value));
}
}
}
@CommandMetaData(name = "remove", aliases = { "rm" }, description = "Remove a repository")
@UsageExample(syntax = "${cmd} myRepo.git", description = "Delete myRepo.git")
public static class RemoveRepository extends RepositoryCommand {
@Override
public void run() throws UnloggedFailure {
RepositoryModel repo = getRepository(true);
if (!getContext().getClient().getUser().canAdmin(repo)) {
throw new UnloggedFailure(1, String.format("Sorry, you do not have permission to delete %s", repository));
}
IGitblit gitblit = getContext().getGitblit();
if (gitblit.deleteRepositoryModel(repo)) {
stdout.println(String.format("%s has been deleted.", repository));
} else {
throw new UnloggedFailure(1, String.format("Failed to delete %s!", repository));
}
}
}
@CommandMetaData(name = "fork", description = "Fork a repository")
@UsageExample(syntax = "${cmd} myRepo.git", description = "Fork myRepo.git")
public static class ForkRepository extends RepositoryCommand {
@Override
public void run() throws UnloggedFailure {
RepositoryModel repo = getRepository(true);
UserModel user = getContext().getClient().getUser();
if (!user.canFork(repo)) {
throw new UnloggedFailure(1, String.format("Sorry, you do not have permission to fork %s", repository));
}
IGitblit gitblit = getContext().getGitblit();
try {
RepositoryModel fork = gitblit.fork(repo, user);
if (fork != null) {
stdout.println(String.format("%s has been forked.", repository));
stdout.println();
stdout.println(String.format(" git clone %s", getRepositoryUrl(fork.name)));
stdout.println();
} else {
throw new UnloggedFailure(1, String.format("Failed to fork %s!", repository));
}
} catch (GitBlitException e) {
throw new UnloggedFailure(1, String.format("Failed to fork %s!", repository), e);
}
}
}
@CommandMetaData(name = "show", description = "Show the details of a repository")
@UsageExample(syntax = "${cmd} myRepo.git", description = "Display myRepo.git")
public static class ShowRepository extends RepositoryCommand {
@Override
public void run() throws UnloggedFailure {
RepositoryModel r = getRepository(true);
if (!getContext().getClient().getUser().canAdmin(r)) {
throw new UnloggedFailure(1, String.format("Sorry, you do not have permission to see the %s settings.", repository));
}
IGitblit gitblit = getContext().getGitblit();
// fields
StringBuilder fb = new StringBuilder();
fb.append("Description : ").append(toString(r.description)).append('\n');
fb.append("Origin : ").append(toString(r.origin)).append('\n');
fb.append("Default Branch : ").append(toString(r.HEAD)).append('\n');
fb.append('\n');
fb.append("GC Period : ").append(r.gcPeriod).append('\n');
fb.append("GC Threshold : ").append(r.gcThreshold).append('\n');
fb.append('\n');
fb.append("Accept Tickets : ").append(toString(r.acceptNewTickets)).append('\n');
fb.append("Accept Patchsets : ").append(toString(r.acceptNewPatchsets)).append('\n');
fb.append("Require Approval : ").append(toString(r.requireApproval)).append('\n');
fb.append("Merge To : ").append(toString(r.mergeTo)).append('\n');
fb.append('\n');
fb.append("Incremental push tags : ").append(toString(r.useIncrementalPushTags)).append('\n');
fb.append("Show remote branches : ").append(toString(r.showRemoteBranches)).append('\n');
fb.append("Skip size calculations : ").append(toString(r.skipSizeCalculation)).append('\n');
fb.append("Skip summary metrics : ").append(toString(r.skipSummaryMetrics)).append('\n');
fb.append("Max activity commits : ").append(r.maxActivityCommits).append('\n');
fb.append("Author metric exclusions : ").append(toString(r.metricAuthorExclusions)).append('\n');
fb.append("Commit Message Renderer : ").append(r.commitMessageRenderer).append('\n');
fb.append("Mailing Lists : ").append(toString(r.mailingLists)).append('\n');
fb.append('\n');
fb.append("Access Restriction : ").append(r.accessRestriction).append('\n');
fb.append("Authorization Control : ").append(r.authorizationControl).append('\n');
fb.append('\n');
fb.append("Is Frozen : ").append(toString(r.isFrozen)).append('\n');
fb.append("Allow Forks : ").append(toString(r.allowForks)).append('\n');
fb.append("Verify Committer : ").append(toString(r.verifyCommitter)).append('\n');
fb.append('\n');
fb.append("Federation Strategy : ").append(r.federationStrategy).append('\n');
fb.append("Federation Sets : ").append(toString(r.federationSets)).append('\n');
fb.append('\n');
fb.append("Indexed Branches : ").append(toString(r.indexedBranches)).append('\n');
fb.append('\n');
fb.append("Pre-Receive Scripts : ").append(toString(r.preReceiveScripts)).append('\n');
fb.append(" inherited : ").append(toString(gitblit.getPreReceiveScriptsInherited(r))).append('\n');
fb.append("Post-Receive Scripts : ").append(toString(r.postReceiveScripts)).append('\n');
fb.append(" inherited : ").append(toString(gitblit.getPostReceiveScriptsInherited(r))).append('\n');
String fields = fb.toString();
// owners
String owners;
if (r.owners.isEmpty()) {
owners = FlipTable.EMPTY;
} else {
String[] pheaders = { "Account", "Name" };
Object [][] pdata = new Object[r.owners.size()][];
for (int i = 0; i < r.owners.size(); i++) {
String owner = r.owners.get(i);
UserModel u = gitblit.getUserModel(owner);
pdata[i] = new Object[] { owner, u == null ? "" : u.getDisplayName() };
}
owners = FlipTable.of(pheaders, pdata, Borders.COLS);
}
// team permissions
List<RegistrantAccessPermission> tperms = gitblit.getTeamAccessPermissions(r);
String tpermissions;
if (tperms.isEmpty()) {
tpermissions = FlipTable.EMPTY;
} else {
String[] pheaders = { "Team", "Permission", "Type" };
Object [][] pdata = new Object[tperms.size()][];
for (int i = 0; i < tperms.size(); i++) {
RegistrantAccessPermission ap = tperms.get(i);
pdata[i] = new Object[] { ap.registrant, ap.permission, ap.permissionType };
}
tpermissions = FlipTable.of(pheaders, pdata, Borders.COLS);
}
// user permissions
List<RegistrantAccessPermission> uperms = gitblit.getUserAccessPermissions(r);
String upermissions;
if (uperms.isEmpty()) {
upermissions = FlipTable.EMPTY;
} else {
String[] pheaders = { "Account", "Name", "Permission", "Type", "Source", "Mutable" };
Object [][] pdata = new Object[uperms.size()][];
for (int i = 0; i < uperms.size(); i++) {
RegistrantAccessPermission ap = uperms.get(i);
String name = "";
try {
String dn = gitblit.getUserModel(ap.registrant).displayName;
if (dn != null) {
name = dn;
}
} catch (Exception e) {
}
pdata[i] = new Object[] { ap.registrant, name, ap.permission, ap.permissionType, ap.source, ap.mutable ? "Y":"" };
}
upermissions = FlipTable.of(pheaders, pdata, Borders.COLS);
}
// assemble table
String title = r.name;
String [] headers = new String[] { title };
String[][] data = new String[8][];
data[0] = new String [] { "FIELDS" };
data[1] = new String [] {fields };
data[2] = new String [] { "OWNERS" };
data[3] = new String [] { owners };
data[4] = new String [] { "TEAM PERMISSIONS" };
data[5] = new String [] { tpermissions };
data[6] = new String [] { "USER PERMISSIONS" };
data[7] = new String [] { upermissions };
stdout.println(FlipTable.of(headers, data));
}
protected String toString(String val) {
if (val == null) {
return "";
}
return val;
}
protected String toString(Collection<?> collection) {
if (collection == null) {
return "";
}
return Joiner.on(", ").join(collection);
}
protected String toString(boolean val) {
if (val) {
return "Y";
}
return "";
}
}
/* List repositories */
@CommandMetaData(name = "list", aliases = { "ls" }, description = "List repositories")
@UsageExample(syntax = "${cmd} mirror/.* -v", description = "Verbose list of all repositories in the 'mirror' directory")
public static class ListRepositories extends ListFilterCommand<RepositoryModel> {
@Override
protected List<RepositoryModel> getItems() {
IGitblit gitblit = getContext().getGitblit();
UserModel user = getContext().getClient().getUser();
List<RepositoryModel> repositories = gitblit.getRepositoryModels(user);
return repositories;
}
@Override
protected boolean matches(String filter, RepositoryModel r) {
return r.name.matches(filter);
}
@Override
protected void asTable(List<RepositoryModel> list) {
String[] headers;
if (verbose) {
String[] h = { "Name", "Description", "Owners", "Last Modified", "Size" };
headers = h;
} else {
String[] h = { "Name", "Last Modified", "Size" };
headers = h;
}
Object[][] data = new Object[list.size()][];
for (int i = 0; i < list.size(); i++) {
RepositoryModel r = list.get(i);
String lm = formatDate(r.lastChange);
String size = r.size;
if (!r.hasCommits) {
lm = "";
size = FlipTable.EMPTY;
}
if (verbose) {
String owners = "";
if (!ArrayUtils.isEmpty(r.owners)) {
owners = Joiner.on(",").join(r.owners);
}
data[i] = new Object[] { r.name, r.description, owners, lm, size };
} else {
data[i] = new Object[] { r.name, lm, size };
}
}
stdout.println(FlipTable.of(headers, data, Borders.BODY_HCOLS));
}
@Override
protected void asTabbed(List<RepositoryModel> list) {
if (verbose) {
for (RepositoryModel r : list) {
String lm = formatDate(r.lastChange);
String owners = "";
if (!ArrayUtils.isEmpty(r.owners)) {
owners = Joiner.on(",").join(r.owners);
}
String size = r.size;
if (!r.hasCommits) {
lm = "";
size = "(empty)";
}
outTabbed(r.name, r.description == null ? "" : r.description,
owners, lm, size);
}
} else {
for (RepositoryModel r : list) {
outTabbed(r.name);
}
}
}
}
} | 34.843324 | 130 | 0.677419 |
e70d3f1e667c90d73a7274ca7ec44c381d87e921 | 1,765 | /*
* 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 co.edu.uniandes.csw.mascotas.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import uk.co.jemos.podam.common.PodamExclude;
/**
*
* @author Johan E. Vivas Sepulveda (je.vivas)
*/
@Entity
public class ClasificadoEntity extends BaseEntity implements Serializable {
private String nombre;
private String contenido;
private String enlace;
@PodamExclude
@ManyToOne
private UsuarioEntity autor;
public ClasificadoEntity()
{
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the contenido
*/
public String getContenido() {
return contenido;
}
/**
* @param contenido the contenido to set
*/
public void setContenido(String contenido) {
this.contenido = contenido;
}
/**
* @return the enlace
*/
public String getEnlace() {
return enlace;
}
/**
* @param enlace the enlace to set
*/
public void setEnlace(String enlace) {
this.enlace = enlace;
}
/**
* @return the autor
*/
public UsuarioEntity getAutor() {
return autor;
}
/**
* @param autor the autor to set
*/
public void setAutor(UsuarioEntity autor) {
this.autor = autor;
}
}
| 19.395604 | 79 | 0.608499 |
64502a5c0256ba2629baafa25fecea24057411c0 | 2,234 | /*
* 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.parquet.thrift;
import java.util.ArrayList;
import org.apache.parquet.thrift.struct.ThriftField;
import org.apache.parquet.thrift.struct.ThriftType.StructType;
import org.apache.parquet.thrift.struct.ThriftType.StructType.StructOrUnionType;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestThriftMetaData {
/**
* Previously, ThriftMetaData.toString would try to instantiate thriftClassName,
* but there is no guarantee that that class is on the classpath, and it is in fact
* normal for that to be the case (for example, when a file was written with TBase objects
* but is being read with scrooge objects).
*
* See PARQUET-345
*/
@Test
public void testToStringDoesNotThrow() {
StructType descriptor = new StructType(new ArrayList<ThriftField>(), StructOrUnionType.STRUCT);
ThriftMetaData tmd = new ThriftMetaData("non existent class!!!", descriptor);
assertEquals("ThriftMetaData(thriftClassName: non existent class!!!, descriptor: {\n" +
" \"id\" : \"STRUCT\",\n" +
" \"children\" : [ ],\n" +
" \"structOrUnionType\" : \"STRUCT\",\n" +
" \"logicalTypeAnnotation\" : null\n" +
"})", tmd.toString());
tmd = new ThriftMetaData("non existent class!!!", null);
assertEquals("ThriftMetaData(thriftClassName: non existent class!!!, descriptor: null)", tmd.toString());
}
}
| 39.192982 | 109 | 0.718442 |
70582a5dd5ec252da9675f63da01f0393a1c2d32 | 2,918 | package crazypants.enderio.machine.monitor;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.Player;
import crazypants.enderio.IPacketProcessor;
import crazypants.enderio.Log;
import crazypants.enderio.PacketHandler;
import crazypants.util.DyeColor;
public class PowerMonitorPacketHandler implements IPacketProcessor {
@Override
public boolean canProcessPacket(int packetID) {
return PacketHandler.ID_POWER_MONITOR_PACKET == packetID;
}
@Override
public void processPacket(int packetID, INetworkManager manager, DataInputStream data, Player player) throws IOException {
if(packetID == PacketHandler.ID_POWER_MONITOR_PACKET) {
handlPacket(data, manager, player);
}
}
public static Packet createPowerMonitotPacket(TilePowerMonitor pm) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
dos.writeInt(PacketHandler.ID_POWER_MONITOR_PACKET);
dos.writeInt(pm.xCoord);
dos.writeInt(pm.yCoord);
dos.writeInt(pm.zCoord);
dos.writeBoolean(pm.engineControlEnabled);
dos.writeFloat(pm.startLevel);
dos.writeFloat(pm.stopLevel);
dos.writeShort(pm.signalColor.ordinal());
} catch (IOException e) {
// never thrown
}
Packet250CustomPayload pkt = new Packet250CustomPayload();
pkt.channel = PacketHandler.CHANNEL;
pkt.data = bos.toByteArray();
pkt.length = bos.size();
pkt.isChunkDataPacket = true;
return pkt;
}
private void handlPacket(DataInputStream data, INetworkManager manager, Player player) throws IOException {
if(!(player instanceof EntityPlayer)) {
Log.warn("createPowerMonitotPacket: Could not handle packet as player not an entity player.");
return;
}
World world = ((EntityPlayer) player).worldObj;
if(world == null) {
Log.warn("createPowerMonitotPacket: Could not handle packet as player world was null.");
return;
}
int x = data.readInt();
int y = data.readInt();
int z = data.readInt();
TileEntity te = world.getBlockTileEntity(x, y, z);
if(!(te instanceof TilePowerMonitor)) {
Log.warn("createPowerMonitotPacket: Could not handle packet as TileEntity was not a TilePowerMonitor.");
return;
}
TilePowerMonitor pm = (TilePowerMonitor) te;
pm.engineControlEnabled = data.readBoolean();
pm.startLevel = data.readFloat();
pm.stopLevel = data.readFloat();
pm.signalColor = DyeColor.fromIndex(data.readShort());
}
}
| 33.54023 | 124 | 0.736121 |
48a6dc252a73bc3cf1dc26b7ea2832c4b92e4c09 | 3,878 | /*
* Copyright 2003-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 jetbrains.mps.lang.editor.menus.substitute;
import jetbrains.mps.editor.runtime.completion.CompletionItemInformation;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.menus.substitute.SubstituteMenuContext;
import jetbrains.mps.smodel.presentation.NodePresentationUtil;
import jetbrains.mps.smodel.runtime.IconResource;
import jetbrains.mps.smodel.runtime.IconResourceUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.language.SReferenceLink;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.model.SNodeAccessUtil;
/**
* @author Radimir.Sorokin
*/
public class ReferenceScopeSubstituteMenuItem extends DefaultSubstituteMenuItem {
@NotNull
private final SNode myReferent;
@NotNull
private final SReferenceLink myReferenceLink;
@Deprecated
public ReferenceScopeSubstituteMenuItem(@NotNull SAbstractConcept concept, @NotNull SNode parentNode, @Nullable SNode currentChild,
@NotNull SNode referent, @NotNull SReferenceLink referenceLink,
@NotNull EditorContext editorContext) {
super(concept, parentNode, currentChild, editorContext);
myReferent = referent;
myReferenceLink = referenceLink;
}
public ReferenceScopeSubstituteMenuItem(@NotNull SAbstractConcept concept, @NotNull SubstituteMenuContext context,
@NotNull SNode referent, @NotNull SReferenceLink referenceLink) {
super(concept, context);
myReferent = referent;
myReferenceLink = referenceLink;
}
@Nullable
@Override
public String getMatchingText(@NotNull String pattern) {
return NodePresentationUtil.matchingText(myReferent, getParentNode());
}
@Nullable
public String getVisibleMatchingText(@NotNull String pattern) {
return NodePresentationUtil.visibleMatchingText(myReferent, getParentNode());
}
@Nullable
@Override
public String getDescriptionText(@NotNull String pattern) {
return "^" + NodePresentationUtil.descriptionText(myReferent, getParentNode());
}
@Nullable
@Override
public IconResource getIcon(@NotNull String pattern) {
return IconResourceUtil.getIconResourceForNode(myReferent);
}
@Nullable
@Override
public SNode createNode(@NotNull String pattern) {
SNode currentChild = getCurrentChild();
if (currentChild != null && currentChild.getConcept().equals(getOutputConcept())) {
SNodeAccessUtil.setReferenceTarget(currentChild, myReferenceLink, myReferent);
return currentChild;
} else {
SNode node = super.createNode(pattern);
SNodeAccessUtil.setReferenceTarget(node, myReferenceLink, myReferent);
return node;
}
}
@NotNull
protected SNode getReferent() {
return myReferent;
}
@NotNull
protected SReferenceLink getReferenceLink() {
return myReferenceLink;
}
@NotNull
@Override
protected CompletionItemInformation createInformation(String pattern) {
return new CompletionItemInformation(myReferent, getOutputConcept(), getMatchingText(pattern), getDescriptionText(pattern));
}
}
| 34.936937 | 133 | 0.753739 |
3e9d1a092b28fa765ff856973386b72f548ef333 | 14,493 | /*
* 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.camel.component.huaweicloud.image;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.utils.StringUtils;
import com.huaweicloud.sdk.image.v2.ImageClient;
import com.huaweicloud.sdk.image.v2.model.CelebrityRecognitionReq;
import com.huaweicloud.sdk.image.v2.model.ImageTaggingReq;
import com.huaweicloud.sdk.image.v2.model.RunCelebrityRecognitionRequest;
import com.huaweicloud.sdk.image.v2.model.RunCelebrityRecognitionResponse;
import com.huaweicloud.sdk.image.v2.model.RunImageTaggingRequest;
import com.huaweicloud.sdk.image.v2.model.RunImageTaggingResponse;
import com.huaweicloud.sdk.image.v2.region.ImageRegion;
import org.apache.camel.Exchange;
import org.apache.camel.component.huaweicloud.image.constants.ImageRecognitionConstants;
import org.apache.camel.component.huaweicloud.image.constants.ImageRecognitionProperties;
import org.apache.camel.component.huaweicloud.image.models.ClientConfigurations;
import org.apache.camel.support.DefaultProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImageRecognitionProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(ImageRecognitionProducer.class);
private ImageClient imageClient;
private ImageRecognitionEndpoint endpoint;
public ImageRecognitionProducer(ImageRecognitionEndpoint endpoint) {
super(endpoint);
this.endpoint = endpoint;
}
@Override
protected void doStart() throws Exception {
super.doStart();
}
/**
* initialize ClientConfigurations
*
* @param endpoint ImageRecognitionEndpoint
* @return ClientConfigurations
*/
private ClientConfigurations initializeConfigurations(ImageRecognitionEndpoint endpoint) {
ClientConfigurations clientConfigurations = new ClientConfigurations();
clientConfigurations.setAccessKey(getAccessKey(endpoint));
clientConfigurations.setSecretKey(getSecretKey(endpoint));
clientConfigurations.setProjectId(getProjectId(endpoint));
clientConfigurations.setEndpoint(getEndpoint(endpoint));
if (StringUtils.isEmpty(endpoint.getImageContent()) && StringUtils.isEmpty(endpoint.getImageUrl())) {
if (StringUtils.isEmpty(endpoint.getRegion())) {
throw new IllegalArgumentException("either image or url should be set");
}
}
clientConfigurations.setIgnoreSslVerification(endpoint.isIgnoreSslVerification());
if (clientConfigurations.isIgnoreSslVerification()) {
LOG.warn("SSL verification is ignored. This is unsafe in production environment");
}
if (!StringUtils.isEmpty(endpoint.getProxyHost())) {
clientConfigurations.setProxyHost(endpoint.getProxyHost());
clientConfigurations.setProxyPort(endpoint.getProxyPort());
clientConfigurations.setProxyUser(endpoint.getProxyUser());
clientConfigurations.setProxyPassword(endpoint.getProxyPassword());
}
return clientConfigurations;
}
/**
* initialize image client. this is lazily initialized on the first message
*
* @param endpoint
* @param clientConfigurations
* @return
*/
private ImageClient initializeSdkClient(ImageRecognitionEndpoint endpoint, ClientConfigurations clientConfigurations) {
if (endpoint.getImageClient() != null) {
LOG.info(
"Instance of ImageClient was set on the endpoint. Skipping creation of ImageClient from endpoint parameters");
this.imageClient = endpoint.getImageClient();
return endpoint.getImageClient();
}
HttpConfig httpConfig = null;
if (clientConfigurations.getProxyHost() != null) {
httpConfig = HttpConfig.getDefaultHttpConfig()
.withProxyHost(clientConfigurations.getProxyHost())
.withProxyPort(clientConfigurations.getProxyPort())
.withIgnoreSSLVerification(clientConfigurations.isIgnoreSslVerification());
if (clientConfigurations.getProxyUser() != null) {
httpConfig.setProxyUsername(clientConfigurations.getProxyUser());
httpConfig.setProxyPassword(clientConfigurations.getProxyPassword());
}
}
BasicCredentials credentials = new BasicCredentials().withAk(clientConfigurations.getAccessKey())
.withSk(clientConfigurations.getSecretKey())
.withProjectId(clientConfigurations.getProjectId());
imageClient = ImageClient.newBuilder()
.withCredential(credentials)
.withHttpConfig(httpConfig)
.withEndpoint(clientConfigurations.getEndpoint())
.build();
if (LOG.isDebugEnabled()) {
LOG.debug("Successfully initialized Image client");
}
return imageClient;
}
public void process(Exchange exchange) {
ClientConfigurations clientConfigurations = initializeConfigurations(endpoint);
if (imageClient == null) {
initializeSdkClient(endpoint, clientConfigurations);
}
String operation = ((ImageRecognitionEndpoint) super.getEndpoint()).getOperation();
if (StringUtils.isEmpty(operation)) {
throw new IllegalStateException("operation name cannot be empty");
}
switch (operation) {
case ImageRecognitionConstants.OPERATION_CELEBRITY_RECOGNITION:
if (LOG.isDebugEnabled()) {
LOG.debug("Performing celebrity recognition");
}
performCelebrityRecognitionOperation(exchange, clientConfigurations);
break;
case ImageRecognitionConstants.OPERATION_TAG_RECOGNITION:
if (LOG.isDebugEnabled()) {
LOG.debug("Performing tag recognition");
}
performTagRecognitionOperation(exchange, clientConfigurations);
break;
default:
throw new UnsupportedOperationException(
"operation can only be either tagRecognition or celebrityRecognition");
}
}
/**
* perform celebrity recognition
*
* @param exchange camel exchange
*/
private void performCelebrityRecognitionOperation(Exchange exchange, ClientConfigurations clientConfigurations) {
updateClientConfigurations(exchange, clientConfigurations);
CelebrityRecognitionReq reqBody = new CelebrityRecognitionReq().withImage(clientConfigurations.getImageContent())
.withUrl(clientConfigurations.getImageUrl())
.withThreshold(clientConfigurations.getThreshold());
RunCelebrityRecognitionResponse response
= this.imageClient.runCelebrityRecognition(new RunCelebrityRecognitionRequest().withBody(reqBody));
exchange.getMessage().setBody(response.getResult());
}
/**
* perform tag recognition
*
* @param exchange camel exchange
*/
private void performTagRecognitionOperation(Exchange exchange, ClientConfigurations clientConfigurations) {
updateClientConfigurations(exchange, clientConfigurations);
ImageTaggingReq reqBody = new ImageTaggingReq().withImage(clientConfigurations.getImageContent())
.withUrl(clientConfigurations.getImageUrl())
.withThreshold(clientConfigurations.getThreshold())
.withLanguage(clientConfigurations.getTagLanguage())
.withLimit(clientConfigurations.getTagLimit());
RunImageTaggingResponse response = this.imageClient.runImageTagging(new RunImageTaggingRequest().withBody(reqBody));
exchange.getMessage().setBody(response.getResult());
}
/**
* Update dynamic client configurations. Some endpoint parameters (imageContent, imageUrl, tagLanguage, tagLimit and
* threshold) can also be passed via exchange properties, so they can be updated between each transaction. Since
* they can change, we must clear the previous transaction and update these parameters with their new values
*
* @param exchange
* @param clientConfigurations
*/
private void updateClientConfigurations(Exchange exchange, ClientConfigurations clientConfigurations) {
boolean isImageContentSet = true;
boolean isImageUrlSet = true;
String imageContent = exchange.getProperty(ImageRecognitionProperties.IMAGE_CONTENT, String.class);
if (!StringUtils.isEmpty(imageContent)) {
clientConfigurations.setImageContent(imageContent);
} else if (!StringUtils.isEmpty(this.endpoint.getImageContent())) {
clientConfigurations.setImageContent(this.endpoint.getImageContent());
} else {
isImageContentSet = false;
}
String imageUrl = exchange.getProperty(ImageRecognitionProperties.IMAGE_URL, String.class);
if (!StringUtils.isEmpty(imageUrl)) {
clientConfigurations.setImageUrl(imageUrl);
} else if (!StringUtils.isEmpty(this.endpoint.getImageUrl())) {
clientConfigurations.setImageUrl(this.endpoint.getImageUrl());
} else {
isImageUrlSet = false;
}
if (!isImageContentSet && !isImageUrlSet) {
throw new IllegalArgumentException("either image content or image url should be set");
}
String tagLanguageProperty = exchange.getProperty(ImageRecognitionProperties.TAG_LANGUAGE, String.class);
clientConfigurations.setTagLanguage(
StringUtils.isEmpty(tagLanguageProperty) ? this.endpoint.getTagLanguage() : tagLanguageProperty);
if (!ImageRecognitionConstants.TAG_LANGUAGE_ZH.equals(clientConfigurations.getTagLanguage())
&& !ImageRecognitionConstants.TAG_LANGUAGE_EN.equals(clientConfigurations.getTagLanguage())) {
throw new IllegalArgumentException("tag language can only be 'zh' or 'en'");
}
Integer tagLimitProperty = exchange.getProperty(ImageRecognitionProperties.TAG_LIMIT, Integer.class);
clientConfigurations.setTagLimit(tagLimitProperty == null ? endpoint.getTagLimit() : tagLimitProperty);
Float thresholdProperty = exchange.getProperty(ImageRecognitionProperties.THRESHOLD, Float.class);
clientConfigurations.setThreshold(thresholdProperty == null ? endpoint.getThreshold() : thresholdProperty);
if (clientConfigurations.getThreshold() == -1) {
clientConfigurations
.setThreshold(ImageRecognitionConstants.OPERATION_TAG_RECOGNITION.equals(endpoint.getOperation())
? ImageRecognitionConstants.DEFAULT_TAG_RECOGNITION_THRESHOLD
: ImageRecognitionConstants.DEFAULT_CELEBRITY_RECOGNITION_THRESHOLD);
}
validateThresholdValue(clientConfigurations.getThreshold(), endpoint.getOperation());
}
/**
* validate threshold value. for tagRecognition, threshold should be at 0~100. for celebrityRecognition, threshold
* should be at 0~1.
*
* @param threshold
* @param operation
*/
private void validateThresholdValue(float threshold, String operation) {
if (ImageRecognitionConstants.OPERATION_TAG_RECOGNITION.equals(operation)) {
if (threshold < 0 || threshold > ImageRecognitionConstants.TAG_RECOGNITION_THRESHOLD_MAX) {
throw new IllegalArgumentException("tag recognition threshold should be at 0~100");
}
} else {
if (threshold < 0 || threshold > ImageRecognitionConstants.CELEBRITY_RECOGNITION_THRESHOLD_MAX) {
throw new IllegalArgumentException("celebrity recognition threshold should be at 0~1");
}
}
}
private String getAccessKey(ImageRecognitionEndpoint endpoint) {
if (!StringUtils.isEmpty(endpoint.getAccessKey())) {
return endpoint.getAccessKey();
} else if (endpoint.getServiceKeys() != null
&& !StringUtils.isEmpty(endpoint.getServiceKeys().getAccessKey())) {
return endpoint.getServiceKeys().getAccessKey();
} else {
throw new IllegalArgumentException("authentication parameter 'access key (AK)' not found");
}
}
private String getSecretKey(ImageRecognitionEndpoint endpoint) {
if (!StringUtils.isEmpty(endpoint.getSecretKey())) {
return endpoint.getSecretKey();
} else if (endpoint.getServiceKeys() != null
&& !StringUtils.isEmpty(endpoint.getServiceKeys().getSecretKey())) {
return endpoint.getServiceKeys().getSecretKey();
} else {
throw new IllegalArgumentException("authentication parameter 'secret key (SK)' not found");
}
}
private String getProjectId(ImageRecognitionEndpoint endpoint) {
if (StringUtils.isEmpty(endpoint.getProjectId())) {
throw new IllegalArgumentException("Project id not found");
}
return endpoint.getProjectId();
}
private String getEndpoint(ImageRecognitionEndpoint endpoint) {
if (!StringUtils.isEmpty(endpoint.getEndpoint())) {
return endpoint.getEndpoint();
}
if (StringUtils.isEmpty(endpoint.getRegion())) {
throw new IllegalArgumentException("either endpoint or region should be set");
}
return ImageRegion.valueOf(endpoint.getRegion()).getEndpoint();
}
}
| 46.156051 | 130 | 0.695094 |
6c01e73fbcf4a7c67fc2c9c4d7bea54fa465ae4e | 148 | package zy.es.mapping.type;
public class NumberRange {
public Number gte;
public Number lte;
public Number gt;
public Number lt;
}
| 16.444444 | 27 | 0.689189 |
24ba5fc7f01fd6572874ec869f133ed6464a1062 | 25,565 | /*
* Copyright (C) 2009 University of Washington
*
* 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.redrosecps.collect.android.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import androidx.appcompat.widget.Toolbar;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import com.redrosecps.collect.android.R;
import com.redrosecps.collect.android.application.Collect;
import com.redrosecps.collect.android.dao.InstancesDao;
import com.redrosecps.collect.android.preferences.AdminKeys;
import com.redrosecps.collect.android.preferences.AdminPreferencesActivity;
import com.redrosecps.collect.android.preferences.AdminSharedPreferences;
import com.redrosecps.collect.android.preferences.AutoSendPreferenceMigrator;
import com.redrosecps.collect.android.preferences.GeneralSharedPreferences;
import com.redrosecps.collect.android.preferences.GeneralKeys;
import com.redrosecps.collect.android.preferences.PreferenceSaver;
import com.redrosecps.collect.android.preferences.PreferencesActivity;
import com.redrosecps.collect.android.preferences.Transport;
import com.redrosecps.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import com.redrosecps.collect.android.utilities.ApplicationConstants;
import com.redrosecps.collect.android.utilities.PlayServicesUtil;
import com.redrosecps.collect.android.utilities.SharedPreferencesUtils;
import com.redrosecps.collect.android.utilities.ToastUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ref.WeakReference;
import java.util.Map;
import timber.log.Timber;
import static com.redrosecps.collect.android.preferences.GeneralKeys.KEY_SUBMISSION_TRANSPORT_TYPE;
/**
* Responsible for displaying buttons to launch the major activities. Launches
* some activities based on returns of others.
*
* @author Carl Hartung ([email protected])
* @author Yaw Anokwa ([email protected])
*/
public class MainMenuActivity extends CollectAbstractActivity {
private static final int PASSWORD_DIALOG = 1;
private static final boolean EXIT = true;
// buttons
private Button manageFilesButton;
private Button sendDataButton;
private Button viewSentFormsButton;
private Button reviewDataButton;
private Button getFormsButton;
private AlertDialog alertDialog;
private SharedPreferences adminPreferences;
private int completedCount;
private int savedCount;
private int viewSentCount;
private Cursor finalizedCursor;
private Cursor savedCursor;
private Cursor viewSentCursor;
private final IncomingHandler handler = new IncomingHandler(this);
private final MyContentObserver contentObserver = new MyContentObserver();
// private static boolean DO_NOT_EXIT = false;
public static void startActivityAndCloseAllOthers(Activity activity) {
activity.startActivity(new Intent(activity, MainMenuActivity.class));
activity.overridePendingTransition(0, 0);
activity.finishAffinity();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
initToolbar();
disableSmsIfNeeded();
// enter data button. expects a result.
Button enterDataButton = findViewById(R.id.enter_data);
enterDataButton.setText(getString(R.string.enter_data_button));
enterDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Collect.allowClick(getClass().getName())) {
Intent i = new Intent(getApplicationContext(),
FormChooserListActivity.class);
startActivity(i);
}
}
});
// review data button. expects a result.
reviewDataButton = findViewById(R.id.review_data);
reviewDataButton.setText(getString(R.string.review_data_button));
reviewDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Collect.allowClick(getClass().getName())) {
Intent i = new Intent(getApplicationContext(), InstanceChooserList.class);
i.putExtra(ApplicationConstants.BundleKeys.FORM_MODE,
ApplicationConstants.FormModes.EDIT_SAVED);
startActivity(i);
}
}
});
// send data button. expects a result.
sendDataButton = findViewById(R.id.send_data);
sendDataButton.setText(getString(R.string.send_data_button));
sendDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Collect.allowClick(getClass().getName())) {
Intent i = new Intent(getApplicationContext(),
InstanceUploaderListActivity.class);
startActivity(i);
}
}
});
//View sent forms
viewSentFormsButton = findViewById(R.id.view_sent_forms);
viewSentFormsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Collect.allowClick(getClass().getName())) {
Intent i = new Intent(getApplicationContext(), InstanceChooserList.class);
i.putExtra(ApplicationConstants.BundleKeys.FORM_MODE,
ApplicationConstants.FormModes.VIEW_SENT);
startActivity(i);
}
}
});
// manage forms button. no result expected.
getFormsButton = findViewById(R.id.get_forms);
getFormsButton.setText(getString(R.string.get_forms));
getFormsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Collect.allowClick(getClass().getName())) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(MainMenuActivity.this);
String protocol = sharedPreferences.getString(
GeneralKeys.KEY_PROTOCOL, getString(R.string.protocol_odk_default));
Intent i = null;
if (protocol.equalsIgnoreCase(getString(R.string.protocol_google_sheets))) {
if (PlayServicesUtil.isGooglePlayServicesAvailable(MainMenuActivity.this)) {
i = new Intent(getApplicationContext(),
GoogleDriveActivity.class);
} else {
PlayServicesUtil.showGooglePlayServicesAvailabilityErrorDialog(MainMenuActivity.this);
return;
}
} else {
i = new Intent(getApplicationContext(),
FormDownloadList.class);
}
startActivity(i);
}
}
});
// manage forms button. no result expected.
manageFilesButton = findViewById(R.id.manage_forms);
manageFilesButton.setText(getString(R.string.manage_files));
manageFilesButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Collect.allowClick(getClass().getName())) {
Intent i = new Intent(getApplicationContext(),
FileManagerTabs.class);
startActivity(i);
}
}
});
// must be at the beginning of any activity that can be called from an
// external intent
Timber.i("Starting up, creating directories");
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
{
// dynamically construct the "ODK Collect vA.B" string
TextView mainMenuMessageLabel = findViewById(R.id.main_menu_header);
mainMenuMessageLabel.setText(Collect.getInstance()
.getVersionedAppName());
}
File f = new File(Collect.ODK_ROOT + "/collect.settings");
File j = new File(Collect.ODK_ROOT + "/collect.settings.json");
// Give JSON file preference
if (j.exists()) {
boolean success = SharedPreferencesUtils.loadSharedPreferencesFromJSONFile(j);
if (success) {
ToastUtils.showLongToast(R.string.settings_successfully_loaded_file_notification);
j.delete();
recreate();
// Delete settings file to prevent overwrite of settings from JSON file on next startup
if (f.exists()) {
f.delete();
}
} else {
ToastUtils.showLongToast(R.string.corrupt_settings_file_notification);
}
} else if (f.exists()) {
boolean success = loadSharedPreferencesFromFile(f);
if (success) {
ToastUtils.showLongToast(R.string.settings_successfully_loaded_file_notification);
f.delete();
recreate();
} else {
ToastUtils.showLongToast(R.string.corrupt_settings_file_notification);
}
}
adminPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setTitle(getString(R.string.main_menu));
setSupportActionBar(toolbar);
}
@Override
protected void onResume() {
super.onResume();
countSavedForms();
updateButtons();
getContentResolver().registerContentObserver(InstanceColumns.CONTENT_URI, true,
contentObserver);
setButtonsVisibility();
}
private void setButtonsVisibility() {
SharedPreferences sharedPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
boolean edit = sharedPreferences.getBoolean(AdminKeys.KEY_EDIT_SAVED, true);
if (!edit) {
if (reviewDataButton != null) {
reviewDataButton.setVisibility(View.GONE);
}
} else {
if (reviewDataButton != null) {
reviewDataButton.setVisibility(View.VISIBLE);
}
}
boolean send = sharedPreferences.getBoolean(AdminKeys.KEY_SEND_FINALIZED, true);
if (!send) {
if (sendDataButton != null) {
sendDataButton.setVisibility(View.GONE);
}
} else {
if (sendDataButton != null) {
sendDataButton.setVisibility(View.VISIBLE);
}
}
boolean viewSent = sharedPreferences.getBoolean(AdminKeys.KEY_VIEW_SENT, true);
if (!viewSent) {
if (viewSentFormsButton != null) {
viewSentFormsButton.setVisibility(View.GONE);
}
} else {
if (viewSentFormsButton != null) {
viewSentFormsButton.setVisibility(View.VISIBLE);
}
}
boolean getBlank = sharedPreferences.getBoolean(AdminKeys.KEY_GET_BLANK, true);
if (!getBlank) {
if (getFormsButton != null) {
getFormsButton.setVisibility(View.GONE);
}
} else {
if (getFormsButton != null) {
getFormsButton.setVisibility(View.VISIBLE);
}
}
boolean deleteSaved = sharedPreferences.getBoolean(AdminKeys.KEY_DELETE_SAVED, true);
if (!deleteSaved) {
if (manageFilesButton != null) {
manageFilesButton.setVisibility(View.GONE);
}
} else {
if (manageFilesButton != null) {
manageFilesButton.setVisibility(View.VISIBLE);
}
}
}
@Override
protected void onPause() {
super.onPause();
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
getContentResolver().unregisterContentObserver(contentObserver);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//case R.id.menu_about:
// startActivity(new Intent(this, AboutActivity.class));
// return true;
case R.id.menu_general_preferences:
startActivity(new Intent(this, PreferencesActivity.class));
return true;
case R.id.menu_admin_preferences:
String pw = adminPreferences.getString(
AdminKeys.KEY_ADMIN_PW, "");
if ("".equalsIgnoreCase(pw)) {
startActivity(new Intent(this, AdminPreferencesActivity.class));
} else {
showDialog(PASSWORD_DIALOG);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void countSavedForms() {
InstancesDao instancesDao = new InstancesDao();
// count for finalized instances
try {
finalizedCursor = instancesDao.getFinalizedInstancesCursor();
} catch (Exception e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
if (finalizedCursor != null) {
startManagingCursor(finalizedCursor);
}
completedCount = finalizedCursor != null ? finalizedCursor.getCount() : 0;
// count for saved instances
try {
savedCursor = instancesDao.getUnsentInstancesCursor();
} catch (Exception e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
if (savedCursor != null) {
startManagingCursor(savedCursor);
}
savedCount = savedCursor != null ? savedCursor.getCount() : 0;
//count for view sent form
try {
viewSentCursor = instancesDao.getSentInstancesCursor();
} catch (Exception e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
if (viewSentCursor != null) {
startManagingCursor(viewSentCursor);
}
viewSentCount = viewSentCursor != null ? viewSentCursor.getCount() : 0;
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
if (shouldExit) {
finish();
}
break;
}
}
};
alertDialog.setCancelable(false);
alertDialog.setButton(getString(R.string.ok), errorListener);
alertDialog.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PASSWORD_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog passwordDialog = builder.create();
passwordDialog.setTitle(getString(R.string.enter_admin_password));
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialogbox_layout, null);
passwordDialog.setView(dialogView, 20, 10, 20, 10);
final CheckBox checkBox = dialogView.findViewById(R.id.checkBox);
final EditText input = dialogView.findViewById(R.id.editText);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!checkBox.isChecked()) {
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else {
input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
});
passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE,
getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
String pw = adminPreferences.getString(
AdminKeys.KEY_ADMIN_PW, "");
if (pw.compareTo(value) == 0) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
input.setText("");
passwordDialog.dismiss();
} else {
ToastUtils.showShortToast(R.string.admin_password_incorrect);
}
}
});
passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE,
getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
input.setText("");
}
});
passwordDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return passwordDialog;
}
return null;
}
private void updateButtons() {
if (finalizedCursor != null && !finalizedCursor.isClosed()) {
finalizedCursor.requery();
completedCount = finalizedCursor.getCount();
if (completedCount > 0) {
sendDataButton.setText(
getString(R.string.send_data_button, String.valueOf(completedCount)));
} else {
sendDataButton.setText(getString(R.string.send_data));
}
} else {
sendDataButton.setText(getString(R.string.send_data));
Timber.w("Cannot update \"Send Finalized\" button label since the database is closed. "
+ "Perhaps the app is running in the background?");
}
if (savedCursor != null && !savedCursor.isClosed()) {
savedCursor.requery();
savedCount = savedCursor.getCount();
if (savedCount > 0) {
reviewDataButton.setText(getString(R.string.review_data_button,
String.valueOf(savedCount)));
} else {
reviewDataButton.setText(getString(R.string.review_data));
}
} else {
reviewDataButton.setText(getString(R.string.review_data));
Timber.w("Cannot update \"Edit Form\" button label since the database is closed. "
+ "Perhaps the app is running in the background?");
}
if (viewSentCursor != null && !viewSentCursor.isClosed()) {
viewSentCursor.requery();
viewSentCount = viewSentCursor.getCount();
if (viewSentCount > 0) {
viewSentFormsButton.setText(
getString(R.string.view_sent_forms_button, String.valueOf(viewSentCount)));
} else {
viewSentFormsButton.setText(getString(R.string.view_sent_forms));
}
} else {
viewSentFormsButton.setText(getString(R.string.view_sent_forms));
Timber.w("Cannot update \"View Sent\" button label since the database is closed. "
+ "Perhaps the app is running in the background?");
}
}
private boolean loadSharedPreferencesFromFile(File src) {
// this should probably be in a thread if it ever gets big
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
// first object is preferences
Map<String, Object> entries = (Map<String, Object>) input.readObject();
AutoSendPreferenceMigrator.migrate(entries);
PreferenceSaver.saveGeneralPrefs(GeneralSharedPreferences.getInstance(), entries);
// second object is admin options
Map<String, Object> adminEntries = (Map<String, Object>) input.readObject();
PreferenceSaver.saveAdminPrefs(AdminSharedPreferences.getInstance(), adminEntries);
Collect.getInstance().initializeJavaRosa();
res = true;
} catch (IOException | ClassNotFoundException e) {
Timber.e(e, "Exception while loading preferences from file due to : %s ", e.getMessage());
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
Timber.e(ex, "Exception thrown while closing an input stream due to: %s ", ex.getMessage());
}
}
return res;
}
/*
* Used to prevent memory leaks
*/
static class IncomingHandler extends Handler {
private final WeakReference<MainMenuActivity> target;
IncomingHandler(MainMenuActivity target) {
this.target = new WeakReference<>(target);
}
@Override
public void handleMessage(Message msg) {
MainMenuActivity target = this.target.get();
if (target != null) {
target.updateButtons();
}
}
}
/**
* notifies us that something changed
*/
private class MyContentObserver extends ContentObserver {
MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
handler.sendEmptyMessage(0);
}
}
private void disableSmsIfNeeded() {
if (Transport.Internet != Transport.fromPreference(GeneralSharedPreferences.getInstance().get(KEY_SUBMISSION_TRANSPORT_TYPE))) {
GeneralSharedPreferences.getInstance().save(KEY_SUBMISSION_TRANSPORT_TYPE, getString(R.string.transport_type_value_internet));
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.sms_feature_disabled_dialog_title)
.setMessage(R.string.sms_feature_disabled_dialog_message)
.setPositiveButton(R.string.read_details, (dialog, which) -> {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra("url", "https://forum.opendatakit.org/t/17973");
startActivity(intent);
})
.setNegativeButton(R.string.ok, (dialog, which) -> dialog.dismiss());
builder
.create()
.show();
}
}
}
| 39.945313 | 138 | 0.595658 |
7d35b1be9f4e7263a442f21f45a5a886c4b6523a | 1,972 | /**
* Copyright 2021 UINB Technologies Pte. Ltd.
* <p>
* 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 tech.uinb.tungus.entity;
import lombok.Data;
import java.util.List;
import java.util.Objects;
@Data
public class BlockHeader {
private Long blkId;
private String extrinsics;
private Long number;
private String hash;
private String parentHash;
private String stateRoot;
private List<DigestLog> logs;
private Long createTime;
private Long extrinsicsCnt;
private Long eventsCnt;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BlockHeader that = (BlockHeader) o;
return Objects.equals(blkId, that.blkId);
}
@Override
public int hashCode() {
return Objects.hash(blkId);
}
@Override
public String toString() {
return "BlockHeader{" +
"blkId=" + blkId +
", extrinsics='" + extrinsics + '\'' +
", number=" + number +
", parentHash='" + parentHash + '\'' +
", stateRoot='" + stateRoot + '\'' +
'}';
}
}
| 31.301587 | 75 | 0.648073 |
ce986e75dd676e9cace0fa8423a76a1b26972946 | 1,566 | // ============================================================================
//
// Copyright (C) 2006-2019 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.codegen.enforcer;
import org.apache.avro.Schema;
/**
* {@link IndexMapper} implementation, which match fields according their indexes
*/
class IndexMapperByIndex implements IndexMapper {
/**
* Number of fields in design schema. It is also equaled number of fields of POJO class in case there is no dynamic fields
*/
private final int designSchemaSize;
/**
* Constructor sets design schema size
*
* @param designSchema design schema
*/
IndexMapperByIndex(Schema designSchema) {
designSchemaSize = designSchema.getFields().size();
}
/**
* {@inheritDoc}
*
* If there is no dynamic fields runtime indexes equal design indexes
* <code>runtimeSchema</code> parameter is not used here
*/
@Override
public int[] computeIndexMap(Schema runtimeSchema) {
int[] indexMap = new int[designSchemaSize];
for (int i = 0; i < designSchemaSize; i++) {
indexMap[i] = i;
}
return indexMap;
}
}
| 30.115385 | 126 | 0.600255 |
77965c98653ec13353c2680a4121bebf58b1b7f3 | 607 | package com.example.jpa.service.mapper;
import com.example.jpa.entity.primary.Book;
import com.example.jpa.service.dto.BookDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
/**
* BookMapper
*
* @author star
*/
@Service
public class BookMapper {
public Book convertToBook(BookDTO dto) {
Book book = new Book();
BeanUtils.copyProperties(dto, book);
return book;
}
public BookDTO convertForBook(Book book) {
BookDTO dto = new BookDTO();
BeanUtils.copyProperties(book, dto);
return dto;
}
}
| 20.233333 | 46 | 0.682043 |
a40441fcfb7ce2674bd014b3b9aa81280a8ea603 | 1,689 | package com.remair.util;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import com.remair.log.LogUtils;
/**
* 项目名称:heixiu
* 类描述:
* 创建人:wsk
* 创建时间:16/5/4 20:54
* 修改人:LiuJun
* 修改时间:16/5/4 20:54
* 修改备注:
*/
public class ClipboardUtil {
/**
* 实现文本复制功能
*/
public static void copy(String content, Context context) {
if (context == null || content == null) {
return;
}
// 得到剪贴板管理器
ClipboardManager cmb = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
if (cmb == null) {
return;
}
try {
cmb.setPrimaryClip(ClipData.newPlainText(null, content.trim()));
} catch (Exception e) {
LogUtils.e(e);
}
}
/**
* 实现粘贴功能
*/
public static String paste(Context context) {
if (context == null) {
return "";
}
// 得到剪贴板管理器
ClipboardManager cmb = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
if (cmb == null) {
return "";
}
ClipData clip = null;
try {
clip = cmb.getPrimaryClip();
} catch (Exception e) {
LogUtils.e(e);
}
if (clip != null && clip.getItemCount() > 0) {
String trim = "";
try {
trim = clip.getItemAt(0).coerceToText(context).toString().trim();
} catch (Exception e) {
LogUtils.e(e);
}
return trim;
} else {
return "";
}
}
}
| 23.458333 | 81 | 0.505033 |
0cd6dc134837eb049e4a48e8a756ac056d9d36a5 | 9,178 | package org.icatproject.authn_oidc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.json.stream.JsonGenerator;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.auth0.jwk.Jwk;
import com.auth0.jwk.JwkException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import org.icatproject.authentication.AuthnException;
import org.icatproject.utils.AddressChecker;
import org.icatproject.utils.AddressCheckerException;
import org.icatproject.utils.CheckedProperties;
import org.icatproject.utils.CheckedProperties.CheckedPropertyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
/* Mapped name is to avoid name clashes */
@Path("/")
@Stateless
public class OIDC_Authenticator {
private static final Logger logger = LoggerFactory.getLogger(OIDC_Authenticator.class);
private static final Marker fatal = MarkerFactory.getMarker("FATAL");
private OpenidConfigurationManager configurationManager;
private String icatUserClaim;
private boolean icatUserClaimException;
private String requiredScope;
private AddressChecker addressChecker;
private String mechanism;
private boolean icatUserPrependMechanism;
@PostConstruct
private void init() {
CheckedProperties props = new CheckedProperties();
try {
props.loadFromResource("run.properties");
String wellKnownUrl = props.getString("wellKnownUrl");
String tokenIssuer = props.getString("tokenIssuer");
try {
configurationManager = new OpenidConfigurationManager(wellKnownUrl, tokenIssuer);
} catch (MalformedURLException e) {
String msg = "Invalid wellKnownUrl URL in run.properties: " + e.getMessage();
logger.error(fatal, msg);
throw new IllegalStateException(msg);
}
icatUserClaim = props.getString("icatUserClaim");
icatUserClaimException = false;
if (props.has("icatUserClaimException")) {
if (props.getString("icatUserClaimException") == "true") {
icatUserClaimException = true;
}
}
if (props.has("requiredScope")) {
requiredScope = props.getString("requiredScope");
}
if (props.has("ip")) {
String authips = props.getString("ip");
try {
addressChecker = new AddressChecker(authips);
} catch (Exception e) {
String msg = "Problem creating AddressChecker with information from run.properties "
+ e.getMessage();
logger.error(fatal, msg);
throw new IllegalStateException(msg);
}
}
if (props.has("mechanism")) {
mechanism = props.getString("mechanism");
}
icatUserPrependMechanism = false;
if (props.has("icatUserPrependMechanism")) {
if (props.getString("icatUserPrependMechanism") == "true") {
icatUserPrependMechanism = true;
}
}
} catch (CheckedPropertyException e) {
logger.error(fatal, e.getMessage());
throw new IllegalStateException(e.getMessage());
}
logger.info("Initialized OIDC_Authenticator");
}
@PreDestroy
public void exit() {
configurationManager.exit();
}
@POST
@Path("jwkupdate")
public void jwkUpdate() {
configurationManager.checkJwkProvider();
}
@GET
@Path("version")
@Produces(MediaType.APPLICATION_JSON)
public String getVersion() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonGenerator gen = Json.createGenerator(baos);
gen.writeStartObject().write("version", Constants.API_VERSION).writeEnd();
gen.close();
return baos.toString();
}
@POST
@Path("authenticate")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String authenticate(@FormParam("json") String jsonString) throws AuthnException {
ByteArrayInputStream s = new ByteArrayInputStream(jsonString.getBytes());
String token = null;
String ip = null;
try (JsonReader r = Json.createReader(s)) {
JsonObject o = r.readObject();
for (JsonValue c : o.getJsonArray("credentials")) {
JsonObject credential = (JsonObject) c;
if (credential.containsKey("token")) {
token = credential.getString("token");
}
}
if (o.containsKey("ip")) {
ip = o.getString("ip");
}
}
logger.debug("Login request: {}", token);
if (token == null || token.isEmpty()) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token cannot be null or empty");
}
if (addressChecker != null) {
try {
if (!addressChecker.check(ip)) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN,
"authn.oidc does not allow log in from your IP address " + ip);
}
} catch (AddressCheckerException e) {
throw new AuthnException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getClass() + " " + e.getMessage());
}
}
DecodedJWT decodedJWT;
try {
decodedJWT = JWT.decode(token);
} catch (JWTDecodeException e) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token could not be decoded");
}
if (requiredScope != null) {
Claim scope = decodedJWT.getClaim("scope");
if (scope.isNull()) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token is missing the scope claim");
}
String[] scopes = scope.asString().split("\\s+");
if (!Arrays.asList(scopes).contains(requiredScope)) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN,
"The token is missing the required scope " + requiredScope);
}
}
Claim iss = decodedJWT.getClaim("iss");
if (iss.isNull()) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token is missing the iss claim");
}
if (!configurationManager.getTokenIssuer().equals(iss.asString())) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN,
"The iss claim of the token does not match the configured issuer");
}
String kid = decodedJWT.getKeyId();
if (kid == null) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token is missing a kid");
}
Jwk jwk;
try {
jwk = configurationManager.getJwkProvider().get(kid);
} catch (JwkException e) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "Unable to find a public key matching the kid");
} catch (NullPointerException e) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN,
"The JWK configuration is not ready, try again in a few minutes");
}
try {
Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
Verification verifier = JWT.require(algorithm);
verifier.build().verify(decodedJWT);
} catch (TokenExpiredException e) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token has expired");
} catch (JWTVerificationException | JwkException e) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token is invalid");
}
String icatUser;
String icatMechanism;
Claim claim = decodedJWT.getClaim(icatUserClaim);
if (claim.isNull()) {
if (icatUserClaimException) {
throw new AuthnException(HttpURLConnection.HTTP_FORBIDDEN, "The token is missing an ICAT username");
} else {
icatUser = decodedJWT.getClaim("sub").asString();
icatMechanism = mechanism;
}
} else {
if (icatUserPrependMechanism) {
icatUser = claim.asString();
icatMechanism = mechanism;
} else {
String[] split = claim.asString().split("/");
if (split.length == 2) {
icatMechanism = split[0];
icatUser = split[1];
} else {
icatMechanism = null;
icatUser = claim.asString();
}
}
}
logger.info("User logged in succesfully as {}{}", (icatMechanism != null ? icatMechanism + "/" : ""), icatUser);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (JsonGenerator gen = Json.createGenerator(baos)) {
gen.writeStartObject().write("username", icatUser);
if (icatMechanism != null) {
gen.write("mechanism", icatMechanism);
}
gen.writeEnd();
}
return baos.toString();
}
@GET
@Path("description")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String getDescription() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (JsonGenerator gen = Json.createGenerator(baos)) {
gen.writeStartObject().writeStartArray("keys");
gen.writeStartObject().write("name", "token").write("hide", true).writeEnd();
gen.writeEnd().writeEnd();
}
return baos.toString();
}
}
| 31.431507 | 114 | 0.728154 |
8a535fadfcc91c064e2a7111ff4568e1195bf35b | 4,134 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.drools.impl.adapters;
import org.drools.event.rule.ObjectRetractedEvent;
import org.drools.event.rule.WorkingMemoryEventListener;
import org.drools.runtime.KnowledgeRuntime;
import org.drools.runtime.rule.FactHandle;
import org.drools.runtime.rule.PropagationContext;
import org.kie.api.event.rule.ObjectDeletedEvent;
import org.kie.api.event.rule.ObjectInsertedEvent;
import org.kie.api.event.rule.ObjectUpdatedEvent;
public class WorkingMemoryEventListenerAdapter implements org.kie.api.event.rule.RuleRuntimeEventListener {
private final WorkingMemoryEventListener delegate;
public WorkingMemoryEventListenerAdapter(WorkingMemoryEventListener delegate) {
this.delegate = delegate;
}
public void objectInserted(final ObjectInsertedEvent event) {
delegate.objectInserted(new org.drools.event.rule.ObjectInsertedEvent() {
public FactHandle getFactHandle() {
return new FactHandleAdapter(event.getFactHandle());
}
public Object getObject() {
return event.getObject();
}
public PropagationContext getPropagationContext() {
throw new UnsupportedOperationException("This operation is no longer supported");
}
public KnowledgeRuntime getKnowledgeRuntime() {
return new KnowledgeRuntimeAdapter((org.kie.internal.runtime.KnowledgeRuntime)event.getKieRuntime());
}
});
}
public void objectUpdated(final ObjectUpdatedEvent event) {
delegate.objectUpdated(new org.drools.event.rule.ObjectUpdatedEvent() {
@Override
public FactHandle getFactHandle() {
return new FactHandleAdapter(event.getFactHandle());
}
@Override
public Object getOldObject() {
return event.getOldObject();
}
@Override
public Object getObject() {
return event.getObject();
}
@Override
public PropagationContext getPropagationContext() {
throw new UnsupportedOperationException("This operation is no longer supported");
}
@Override
public KnowledgeRuntime getKnowledgeRuntime() {
return new KnowledgeRuntimeAdapter((org.kie.internal.runtime.KnowledgeRuntime)event.getKieRuntime());
}
});
}
public void objectDeleted(final ObjectDeletedEvent event) {
delegate.objectRetracted(new ObjectRetractedEvent() {
@Override
public FactHandle getFactHandle() {
return new FactHandleAdapter(event.getFactHandle());
}
@Override
public Object getOldObject() {
return event.getOldObject();
}
@Override
public PropagationContext getPropagationContext() {
throw new UnsupportedOperationException("This operation is no longer supported");
}
@Override
public KnowledgeRuntime getKnowledgeRuntime() {
return new KnowledgeRuntimeAdapter((org.kie.internal.runtime.KnowledgeRuntime)event.getKieRuntime());
}
});
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof WorkingMemoryEventListenerAdapter && delegate.equals(((WorkingMemoryEventListenerAdapter)obj).delegate);
}
}
| 34.739496 | 134 | 0.657233 |
f035e1bde77a6101ca9431d9ae7f1edb9e8662b0 | 656 | package com.designpattern.cases.constructor.singleton;
public class Singleton {
private String objName;
public String getObjName() {
return objName;
}
public void setObjName(String objName) {
this.objName = objName;
}
private Singleton() {
}
public static Singleton getInstance() {
return SingletonEnum.INSTANCE.getSingleton();
}
private enum SingletonEnum {
INSTANCE;
private Singleton singleton;
public Singleton getSingleton() {
return singleton;
}
SingletonEnum() {
singleton = new Singleton();
}
}
}
| 17.72973 | 54 | 0.60061 |
d85b2300e001a0b6a8ab61a6cc464475f693600f | 440 | package com.smlnskgmail.jaman.hashchecker.screenshots;
import androidx.test.runner.AndroidJUnit4;
import com.smlnskgmail.jaman.hashchecker.R;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class HashTypesScreenshotTest extends BaseScreenshotTest {
@Override
public void runTest() {
clickById(R.id.tv_selected_hash_type);
makeScreenshot(
"4_hash_types"
);
}
}
| 20.952381 | 65 | 0.720455 |
81489d374c201f3625e9280d3606ea57fded943a | 2,167 | package com.zjzy.morebit.Module.common.Dialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.zjzy.morebit.R;
import com.zjzy.morebit.contact.EventBusAction;
import com.zjzy.morebit.pojo.MessageEvent;
import com.zjzy.morebit.utils.GoodsUtil;
import org.greenrobot.eventbus.EventBus;
/*
*
* 升级成功弹框
* */
public class ShopkeeperUpgradeDialog3 extends Dialog {
private TextView btn_ok,title,tv2,tv3;
private Context mContext;
private ImageView img;
private int type=1;
private int h5=1;
public ShopkeeperUpgradeDialog3(Context context,int type,int h5) {
super(context, R.style.dialog);
this.mContext = context;
this.type=type;
this.h5=h5;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_upgrade_shopkeeper3);
setCanceledOnTouchOutside(false);
initView();
}
private void initView() {
img=findViewById(R.id.img);
tv3=findViewById(R.id.tv3);
tv2=findViewById(R.id.tv2);
title=findViewById(R.id.title);
btn_ok = findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (h5==1){
GoodsUtil.getVipH5(mContext);
}else{
EventBus.getDefault().post(new MessageEvent(EventBusAction.UPGRADE_REFRSH));
}
dismiss();
}
});
if (type==1){
img.setImageResource(R.mipmap.vip_bg_icon);
title.setText("恭喜您升级成功");
tv2.setText("将获得掌柜");
tv3.setText("尊享权益");
}else{
img.setImageResource(R.mipmap.group_bg_icon);
title.setText("领取成功");
tv2.setText("您将尊享掌柜");
tv3.setText("权益");
}
}
}
| 24.348315 | 96 | 0.624365 |
bd5c89a5102c828a580944a4bb3e603aa0a9fe85 | 1,045 | package com.replica;
import com.graphhopper.util.Helper;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.io.File;
import static com.replica.ReplicaGraphHopperTest.*;
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL;
public class ReplicaGraphHopperTestExtention implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
private static boolean started = false;
@Override
public void beforeAll(ExtensionContext context) throws Exception {
if (!started) {
started = true;
setup();
// The following line registers a callback hook when the root test context is shut down
context.getRoot().getStore(GLOBAL).put("Global GraphHopper test context", this);
}
}
@Override
public void close() {
Helper.removeDir(new File(GRAPH_FILES_DIR));
Helper.removeDir(new File(TRANSIT_DATA_DIR));
closeGraphhopper();
}
}
| 31.666667 | 117 | 0.719617 |
31669f6f535fb57a72d338a9e916e2948a02f828 | 631 | package ru.schernigin.arrays;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test class rotation array.
*
* @author schernigin.
* @version 1
* @since 05.12.2016
*/
public class RotationArrayTest {
/**
* Test mrthod rotation.
*/
@Test
public void whenAddTwoDimensionalArrayThenInvertedArray90Degrees() {
RotationArray rot = new RotationArray();
final int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
final int[][] arrRot = {{3, 6, 9}, {2, 5, 8}, {1, 4, 7}};
final int[][] resultArr = rot.rotation(arr);
assertThat(resultArr, is(arrRot));
}
} | 21.758621 | 69 | 0.656101 |
21318ba2a77536c6fc862360cb4393902879d234 | 1,367 | package com.piasy.playground.ViewCompatAnimate;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View src = findViewById(R.id.src);
final View dst = findViewById(R.id.dst);
findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
int[] srcLoc = new int[2];
src.getLocationOnScreen(srcLoc);
int[] dstLoc = new int[2];
dst.getLocationOnScreen(dstLoc);
ViewCompat.animate(src)
.withLayer()
// right
.translationX((dst.getWidth() / 2 + dstLoc[0]) - (src.getWidth() / 2 + srcLoc[0]))
.translationY((dst.getHeight() / 2 + dstLoc[1]) - (src.getHeight() / 2 + srcLoc[1]))
// wrong
//.translationX((dstLoc[0]) - (srcLoc[0]))
//.translationY((dstLoc[1]) - (srcLoc[1]))
.scaleX((float) dst.getWidth() / src.getWidth())
.scaleY((float) dst.getHeight() / src.getHeight())
.rotation(0f)
.setDuration(500);
}
});
}
}
| 32.547619 | 96 | 0.618873 |
bb7eeb5336bdb8fd9c8718c06d5f521bc2a2cc02 | 1,821 | package com.cookpad.puree;
import android.content.Context;
import com.cookpad.puree.outputs.PureeOutput;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class PureeConfiguration {
private Context applicationContext;
private Gson gson;
private Map<String, PureeOutput> outputs = new HashMap<>();
public Context getApplicationContext() {
return applicationContext;
}
public Gson getGson() {
return gson;
}
public Map<String, PureeOutput> getOutputs() {
return outputs;
}
PureeConfiguration(Context context,
Gson gson,
Map<String, PureeOutput> outputs) {
this.applicationContext = context.getApplicationContext();
this.gson = gson;
this.outputs = outputs;
}
public static class Builder {
private Context context;
private Gson gson = new Gson();
private Map<String, PureeOutput> outputs = new HashMap<>();
public Builder(Context context) {
this.context = context;
}
public Builder gson(Gson gson) {
this.gson = gson;
return this;
}
public Builder registerOutput(PureeOutput output, PureeFilter... filters) {
for (PureeFilter filter : filters) {
output.registerFilter(filter);
}
if (outputs.put(output.type(), output) != null) {
throw new IllegalStateException("duplicate PureeOutput for type: " + output.type());
}
return this;
}
public PureeConfiguration build() {
return new PureeConfiguration(
context,
gson,
outputs);
}
}
}
| 26.779412 | 100 | 0.576606 |
ccd755412bea702567fc6438d7eacd234717ad5b | 9,889 | package com.nedap.healthcare.aqlparser.util;
import com.nedap.healthcare.aqlparser.AQLParser;
import com.nedap.healthcare.aqlparser.exception.AQLRuntimeException;
import com.nedap.healthcare.aqlparser.exception.AQLUnsupportedFeatureException;
import com.nedap.healthcare.aqlparser.model.*;
import com.nedap.healthcare.aqlparser.model.clause.*;
import com.nedap.healthcare.aqlparser.model.leaf.*;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList;
import java.util.List;
public class QOMParserUtil {
public static QOMObject parse(Lookup lookup, ParseTree parseTree) {
return parse(lookup, new ParseTree[]{parseTree}).get(0);
}
public static List<QOMObject> parse(Lookup lookup, ParseTree... parseTrees) {
List<QOMObject> objects = new ArrayList<>();
for (ParseTree parseTree : parseTrees) {
if (parseTree == null) continue;
if (parseTree instanceof TerminalNode) {
objects.add(parse(lookup, (TerminalNode) parseTree));
} else if (parseTree instanceof ParserRuleContext) {
objects.add(parse(lookup, (ParserRuleContext) parseTree));
} else {
throw new AQLRuntimeException("Must not be reached");
}
}
return objects;
}
public static QOMObject parse(Lookup lookup, TerminalNode terminalNode) {
return QOMParserUtil.parse(lookup, new TerminalNode[]{terminalNode}).get(0);
}
public static List<QOMObject> parse(Lookup lookup, TerminalNode... terminalNodes) {
List<QOMObject> objects = new ArrayList<>();
for (TerminalNode terminalNode : terminalNodes) {
if (terminalNode == null) continue;
int type = terminalNode.getSymbol().getType();
switch (type) {
case AQLParser.NODEID :
case AQLParser.URIVALUE:
objects.add(new TerminalNodeLeaf(terminalNode));
break;
case AQLParser.PARAMETER:
objects.add(new PrimitiveOperand(PrimitiveType.PARAMETER,terminalNode.getText(), lookup));
break;
case AQLParser.ARCHETYPEID:
objects.add(new ArchetypeId(terminalNode));
break;
case AQLParser.STRING:
objects.add(new PrimitiveOperand(PrimitiveType.STRING,terminalNode.getText(), lookup));
break;
case AQLParser.INTEGER:
objects.add(new PrimitiveOperand(PrimitiveType.INTEGER,terminalNode.getText(), lookup));
break;
case AQLParser.FLOAT:
objects.add(new PrimitiveOperand(PrimitiveType.FLOAT,terminalNode.getText(), lookup));
break;
case AQLParser.DATE:
objects.add(new PrimitiveOperand(PrimitiveType.DATE,terminalNode.getText(), lookup));
break;
case AQLParser.BOOLEAN:
objects.add(new PrimitiveOperand(PrimitiveType.BOOLEAN,terminalNode.getText(), lookup));
break;
case AQLParser.COMPARABLEOPERATOR:
case AQLParser.AND:
case AQLParser.OR:
case AQLParser.NOT:
case AQLParser.EXISTS:
case AQLParser.MATCHES:
case AQLParser.CONTAINS:
objects.add(new Operator(terminalNode));
break;
default:
throw new AQLUnsupportedFeatureException(terminalNode.getSymbol() + " not yet supported in QOMParserUtil");
}
}
return objects;
}
public static QOMObject parse(Lookup lookup, ParserRuleContext parserRuleContext) {
return QOMParserUtil.parse(lookup, new ParserRuleContext[]{parserRuleContext}).get(0);
}
public static List<QOMObject> parse(Lookup lookup, ParserRuleContext... parserRuleContexts) {
List<QOMObject> objects = new ArrayList<>();
for (ParserRuleContext ctx : parserRuleContexts) {
if (ctx == null) continue;
if (ctx instanceof AQLParser.IdentifiedExprContext) {
objects.add(new NodeExpression((AQLParser.IdentifiedExprContext) ctx, lookup));
} else if (ctx instanceof AQLParser.IdentifiedExprOperandContext) {
objects.add(new IdentifiedExprOperand((AQLParser.IdentifiedExprOperandContext) ctx, lookup));
} else if (ctx instanceof AQLParser.MatchesOperandContext) {
AQLParser.MatchesOperandContext moctx = (AQLParser.MatchesOperandContext) ctx;
objects.add(parse(lookup, moctx.valueList(), moctx.URIVALUE()).get(0));
} else if (ctx instanceof AQLParser.ValueListContext) {
objects.add(new ValueList((AQLParser.ValueListContext) ctx, lookup));
} else if (ctx instanceof AQLParser.PredicateOperandContext) {
AQLParser.PredicateOperandContext poctx = (AQLParser.PredicateOperandContext) ctx;
if (poctx.identifiedPath() != null &&
poctx.identifiedPath().objectPath() == null &&
poctx.identifiedPath().nodePredicate() == null) {
//If only an IDENTIFIER is specified, an IdentifiedPath can not be distinguished from a
//PrimitiveOperand of type String.
objects.add(new PrimitiveOperand(PrimitiveType.STRING,poctx.identifiedPath().IDENTIFIER().getText(), lookup));
} else {
objects.addAll(QOMParserUtil.parse(lookup, poctx.identifiedPath(),poctx.primitiveOperand()));
}
} else if (ctx instanceof AQLParser.PrimitiveOperandContext) {
objects.add(new PrimitiveOperand((AQLParser.PrimitiveOperandContext) ctx, lookup));
} else if (ctx instanceof AQLParser.ArchetypePredicateExprContext) {
AQLParser.ArchetypePredicateExprContext apctx = (AQLParser.ArchetypePredicateExprContext) ctx;
objects.add(parse(lookup, apctx.ARCHETYPEID(),apctx.PARAMETER()).get(0));
} else if (ctx instanceof AQLParser.PathPartContext) {
objects.add(new PathPart((AQLParser.PathPartContext) ctx, lookup));
} else if (ctx instanceof AQLParser.ObjectPathContext) {
objects.add(new ObjectPath((AQLParser.ObjectPathContext) ctx, lookup));
} else if (ctx instanceof AQLParser.NodePredicateContext) {
objects.add(new Predicate((AQLParser.NodePredicateContext) ctx, lookup));
} else if (ctx instanceof AQLParser.NodePredicateExprContext) {
objects.add(new NodeExpression((AQLParser.NodePredicateExprContext) ctx, lookup));
} else if (ctx instanceof AQLParser.NodePredicateExprOperandContext) {
objects.add(new NodeExpression((AQLParser.NodePredicateExprOperandContext) ctx, lookup));
} else if (ctx instanceof AQLParser.QueryClauseContext) {
objects.add(new QueryClause((AQLParser.QueryClauseContext) ctx, lookup));
} else if (ctx instanceof AQLParser.ClassExprOperandContext) {
objects.add(new ClassExprOperand((AQLParser.ClassExprOperandContext) ctx, lookup));
} else if (ctx instanceof AQLParser.ContainsExprContext) {
objects.add(new NodeExpression((AQLParser.ContainsExprContext) ctx, lookup));
} else if (ctx instanceof AQLParser.FromClauseContext) {
objects.add(new FromClause((AQLParser.FromClauseContext) ctx, lookup));
} else if (ctx instanceof AQLParser.ArchetypePredicateContext) {
objects.add(new ArchetypePredicate((AQLParser.ArchetypePredicateContext) ctx, lookup));
} else if (ctx instanceof AQLParser.IdentifiedPathContext) {
objects.add(new IdentifiedPath((AQLParser.IdentifiedPathContext) ctx, lookup));
} else if (ctx instanceof AQLParser.SelectOperandContext) {
objects.add(new SelectOperand((AQLParser.SelectOperandContext) ctx, lookup));
} else if (ctx instanceof AQLParser.SelectClauseContext) {
objects.add(new SelectClause((AQLParser.SelectClauseContext) ctx, lookup));
} else if (ctx instanceof AQLParser.TopClauseContext) {
objects.add(new TopClause((AQLParser.TopClauseContext) ctx));
} else if (ctx instanceof AQLParser.OrderByExprContext) {
objects.add(new OrderByExpression((AQLParser.OrderByExprContext) ctx, lookup));
} else if (ctx instanceof AQLParser.OrderByClauseContext) {
objects.add(new OrderByClause((AQLParser.OrderByClauseContext) ctx, lookup));
} else if (ctx instanceof AQLParser.StandardPredicateExprContext) {
objects.add(new NodeExpression((AQLParser.StandardPredicateExprContext) ctx, lookup));
} else if (ctx instanceof AQLParser.StandardPredicateContext) {
objects.add(new Predicate((AQLParser.StandardPredicateContext) ctx, lookup));
} else if (ctx instanceof AQLParser.StandardPredicateExprOperandContext) {
objects.add(new NodeExpression((AQLParser.StandardPredicateExprOperandContext) ctx, lookup));
} else if (ctx instanceof AQLParser.WhereClauseContext) {
objects.add(new WhereClause((AQLParser.WhereClauseContext) ctx, lookup));
} else {
throw new AQLUnsupportedFeatureException(ctx.getClass().getCanonicalName() + " not yet supported in QOMParserUtil");
}
}
return objects;
}
}
| 58.514793 | 132 | 0.643442 |
0c2f6ec5c4b4a7535196ee3334a3a43ed0c1ceb0 | 2,828 | package com.charles445.rltweaker.handler;
import java.lang.reflect.Field;
import java.util.HashSet;
import com.charles445.rltweaker.RLTweaker;
import com.charles445.rltweaker.config.ModConfig;
import com.charles445.rltweaker.util.CompatUtil;
import com.charles445.rltweaker.util.CriticalException;
import com.charles445.rltweaker.util.ErrorUtil;
import com.charles445.rltweaker.util.ReflectUtil;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.IEventListener;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
public class SpawnerControlHandler
{
public SpawnerControlHandler()
{
try
{
if(ModConfig.server.spawnercontrol.synchronizeSpawnerIteration || ModConfig.server.spawnercontrol.removeWorldTicks)
{
//Wrap the WorldTick handler
CompatUtil.wrapSpecificHandler("SCWorldTick", SCWorldTick::new, "ladysnake.spawnercontrol.SpawnerEventHandler", "onTickWorldTick");
}
if(ModConfig.server.spawnercontrol.removeWorldTicks)
{
Class c_SpawnerEventHandler = Class.forName("ladysnake.spawnercontrol.SpawnerEventHandler");
Field f_SpawnerEventHandler_allSpawners = ReflectUtil.findField(c_SpawnerEventHandler, "allSpawners");
f_SpawnerEventHandler_allSpawners.set(null, new DenySet<TileEntityMobSpawner>());
}
}
catch (Exception e)
{
RLTweaker.logger.error("Failed to setup SpawnerControlHandler!", e);
ErrorUtil.logSilent("Spawner Control Critical Setup Failure");
//Crash on Critical
if(e instanceof CriticalException)
throw new RuntimeException(e);
}
}
public class DenySet<T> extends HashSet<T>
{
@Override
public boolean add(Object val)
{
return false;
}
}
public class SCWorldTick
{
private IEventListener handler;
private boolean synchronizeSpawnerIteration = ModConfig.server.spawnercontrol.synchronizeSpawnerIteration;
private boolean removeWorldTicks = ModConfig.server.spawnercontrol.removeWorldTicks;
public SCWorldTick(IEventListener handler)
{
this.handler = handler;
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void onWorldTick(final TickEvent.WorldTickEvent event)
{
if(removeWorldTicks)
return;
//Avoid weird synchronization issues by doing the standard checks done in Spawner Control
if(event.phase == TickEvent.Phase.START || event.side == Side.CLIENT)
return;
//Confident side is server and phase end, synchronize and run original handler
if(synchronizeSpawnerIteration)
{
synchronized(this)
{
handler.invoke(event);
}
}
else
{
handler.invoke(event);
}
}
}
}
| 28.857143 | 135 | 0.769448 |
ddb1f4d5e8718bef20ec554acaa05941f85222f9 | 3,417 | package iti.suitceyes.ontology;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.manager.RemoteRepositoryManager;
import org.eclipse.rdf4j.repository.manager.RepositoryManager;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParseException;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.RDFParserHelper;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
public class TestOntology {
public static void main(String[] args) throws RDFParseException, RDFHandlerException, IOException {
// Instantiate a local repository manager and initialize it
// RepositoryManager repositoryManager = new LocalRepositoryManager(new File("."));
// repositoryManager.initialize();
RepositoryManager repositoryManager =
new RemoteRepositoryManager( "http://beaware-server.mklab.iti.gr:7200" );
//new RemoteRepositoryManager( "https://graphdb.certh.strdi.me:7200" );
repositoryManager.initialize();
// Instantiate a repository graph model
TreeModel graph = new TreeModel();
// Read repository configuration file
// InputStream config = EmbeddedGraphDB.class.getResourceAsStream("/repo-defaults.ttl");
InputStream config = RDFParserHelper.class.getResourceAsStream("\\repo-defaults.ttl");
RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE);
rdfParser.setRDFHandler(new StatementCollector(graph));
rdfParser.parse(config, RepositoryConfigSchema.NAMESPACE);
config.close();
// Retrieve the repository node as a resource
// Resource repositoryNode = GraphUtil.getUniqueSubject(graph, RDF.TYPE, RepositoryConfigSchema.REPOSITORY);
Resource repositoryNode = graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY).subjects().iterator().next();
Model model = graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY);
Iterator<Statement> iterator = model.iterator();
if (!iterator.hasNext())
throw new RuntimeException("Oops, no <http://www.openrdf.org/config/repository#> subject found!");
Statement statement = iterator.next();
Resource repositoryNodeXXNEW = statement.getSubject();
// Create a repository configuration object and add it to the repositoryManager
RepositoryConfig repositoryConfig = RepositoryConfig.create(graph, repositoryNode);
repositoryManager.addRepositoryConfig(repositoryConfig);
// Get the repository from repository manager, note the repository id set in configuration .ttl file
Repository repository = repositoryManager.getRepository("graphdb-repo");
// Open a connection to this repository
RepositoryConnection repositoryConnection = repository.getConnection();
// ... use the repository
// Shutdown connection, repository and manager
repositoryConnection.close();
repository.shutDown();
repositoryManager.shutDown();
}
}
| 42.185185 | 121 | 0.794849 |
456942c9f8e4bb4213cde8b996d34fe52066b6df | 3,897 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. * */
end_comment
begin_package
DECL|package|org.apache.hadoop.fs.adl.live
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|adl
operator|.
name|live
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileSystem
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileSystemContractBaseTest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|After
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assume
operator|.
name|*
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Before
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_comment
comment|/** * Test Base contract tests on Adl file system. */
end_comment
begin_class
DECL|class|TestAdlFileSystemContractLive
specifier|public
class|class
name|TestAdlFileSystemContractLive
extends|extends
name|FileSystemContractBaseTest
block|{
DECL|field|adlStore
specifier|private
name|FileSystem
name|adlStore
decl_stmt|;
annotation|@
name|Before
DECL|method|setUp ()
specifier|public
name|void
name|setUp
parameter_list|()
throws|throws
name|Exception
block|{
name|skipTestCheck
argument_list|()
expr_stmt|;
name|adlStore
operator|=
name|AdlStorageConfiguration
operator|.
name|createStorageConnector
argument_list|()
expr_stmt|;
if|if
condition|(
name|AdlStorageConfiguration
operator|.
name|isContractTestEnabled
argument_list|()
condition|)
block|{
name|fs
operator|=
name|adlStore
expr_stmt|;
block|}
name|assumeNotNull
argument_list|(
name|fs
argument_list|)
expr_stmt|;
block|}
annotation|@
name|After
DECL|method|tearDown ()
specifier|public
name|void
name|tearDown
parameter_list|()
throws|throws
name|Exception
block|{
if|if
condition|(
name|AdlStorageConfiguration
operator|.
name|isContractTestEnabled
argument_list|()
condition|)
block|{
name|cleanup
argument_list|()
expr_stmt|;
block|}
name|super
operator|.
name|tearDown
argument_list|()
expr_stmt|;
block|}
DECL|method|cleanup ()
specifier|private
name|void
name|cleanup
parameter_list|()
throws|throws
name|IOException
block|{
name|adlStore
operator|.
name|delete
argument_list|(
operator|new
name|Path
argument_list|(
literal|"/test"
argument_list|)
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
DECL|method|skipTestCheck ()
specifier|private
name|void
name|skipTestCheck
parameter_list|()
block|{
name|assumeTrue
argument_list|(
name|AdlStorageConfiguration
operator|.
name|isContractTestEnabled
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| 16.725322 | 816 | 0.79728 |
1a0b5bff7e754cad1be6d3a4863e5b0c514913cf | 1,342 | import java.util.concurrent.Semaphore;
public class Husbandman implements Runnable {
public static double figure = 0.009979230876253742;
public String card;
public static Semaphore waffen;
public static int lettering;
public Husbandman(String ownership) {
this.card = ownership;
}
public synchronized void run() {
double designator = 0.16869280949218257;
while (true) {
System.out.println(card + ": Waiting for bridge.");
try {
waffen.acquire();
assumePrecautions();
System.out.println(card + ": Crossing bridge step 5.");
assumePrecautions();
System.out.println(card + ": Crossing bridge step 10.");
assumePrecautions();
System.out.println(card + ": Crossing bridge step 15.");
assumePrecautions();
System.out.println(card + ": Across the bridge.");
lettering++;
System.out.println("NEON = " + lettering);
waffen.release();
} catch (InterruptedException voto) {
voto.toString();
}
}
}
public synchronized void assumePrecautions() {
String greaterConstrain = "H3984ZrnBZA";
try {
wait(1000);
} catch (InterruptedException former) {
System.out.println(former.toString());
}
}
static {
waffen = new Semaphore(1);
lettering = 0;
}
}
| 25.320755 | 64 | 0.628167 |
02adc3f1c1f38bfc8300afd4bb770282cf148208 | 406 | import java.awt.Graphics;
// Draws oval. I'm not sure what else you expected.
class OvalDraw extends Oval{
public OvalDraw(){
super(0,0,0,0);
}
public OvalDraw(int positionXIn, int positionYIn, int widthIn, int heightIn){
super(positionXIn, positionYIn, widthIn, heightIn);
}
public void paintComponent(Graphics g){
g.drawOval(getPositionX(), getPositionY(), getWidth(), getHeight());
}
} | 21.368421 | 78 | 0.721675 |
f70883ad58f9e4b2a74804bd5dc95bffcc997ffa | 2,479 | package mage.cards.d;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.abilities.keyword.UnearthAbility;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.players.Player;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class DregscapeSliver extends CardImpl {
public DregscapeSliver(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}");
this.subtype.add(SubType.SLIVER);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Each Sliver creature card in your graveyard has unearth {2}.
this.addAbility(new SimpleStaticAbility(new DregscapeSliverEffect()));
// Unearth {2}
this.addAbility(new UnearthAbility(new ManaCostsImpl("{2}")));
}
private DregscapeSliver(final DregscapeSliver card) {
super(card);
}
@Override
public DregscapeSliver copy() {
return new DregscapeSliver(this);
}
}
class DregscapeSliverEffect extends ContinuousEffectImpl {
DregscapeSliverEffect() {
super(Duration.WhileOnBattlefield, Layer.AbilityAddingRemovingEffects_6, SubLayer.NA, Outcome.AddAbility);
staticText = "Each Sliver creature card in your graveyard has unearth {2}";
}
private DregscapeSliverEffect(final DregscapeSliverEffect effect) {
super(effect);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
if (controller == null) {
return false;
}
for (UUID cardId : controller.getGraveyard()) {
Card card = game.getCard(cardId);
if (card == null || !card.isCreature(game) || !card.hasSubtype(SubType.SLIVER, game)) {
continue;
}
UnearthAbility ability = new UnearthAbility(new ManaCostsImpl("{2}"));
ability.setSourceId(cardId);
ability.setControllerId(card.getOwnerId());
game.getState().addOtherAbility(card, ability);
}
return true;
}
@Override
public DregscapeSliverEffect copy() {
return new DregscapeSliverEffect(this);
}
} | 30.9875 | 114 | 0.673659 |
f978ad33f94dceb4adfc99b3aac5986f5bd5a17a | 2,296 | /*
* Copyright 2000-2016 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 org.jetbrains.jps.backwardRefs;
import com.intellij.util.io.DataInputOutputUtil;
import com.intellij.util.io.DifferentSerializableBytesImplyNonEqualityPolicy;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import static org.jetbrains.jps.backwardRefs.LightRef.*;
public final class LightRefDescriptor implements KeyDescriptor<LightRef>, DifferentSerializableBytesImplyNonEqualityPolicy {
public static final LightRefDescriptor INSTANCE = new LightRefDescriptor();
@Override
public int getHashCode(LightRef value) {
return value.hashCode();
}
@Override
public boolean isEqual(LightRef val1, LightRef val2) {
return val1.equals(val2);
}
@Override
public void save(@NotNull DataOutput out, LightRef value) throws IOException {
value.save(out);
}
@Override
public LightRef read(@NotNull DataInput in) throws IOException {
final byte type = in.readByte();
switch (type) {
case CLASS_MARKER:
return new JavaLightClassRef(DataInputOutputUtil.readINT(in));
case ANONYMOUS_CLASS_MARKER:
return new JavaLightAnonymousClassRef(DataInputOutputUtil.readINT(in));
case METHOD_MARKER:
return new JavaLightMethodRef(DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in));
case FIELD_MARKER:
return new JavaLightFieldRef(DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in));
case FUN_EXPR_MARKER:
return new JavaLightFunExprDef(DataInputOutputUtil.readINT(in));
}
throw new AssertionError();
}
}
| 35.323077 | 137 | 0.760453 |
08628c888b84ffe6c4dc52d2e9b0196dcda0fde0 | 694 | package br.com.zupacademy.kleysson.mercadolivre.dto.request;
import com.fasterxml.jackson.annotation.JsonCreator;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import javax.validation.constraints.*;
public class LoginRequest {
@NotBlank
@Email
private String email;
@NotBlank
@Size(min = 6)
private String senha;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public LoginRequest(String email, String senha) {
this.email = email;
this.senha = senha;
}
public UsernamePasswordAuthenticationToken converter() {
return new UsernamePasswordAuthenticationToken(email, senha);
}
}
| 24.785714 | 87 | 0.736311 |
029f18815d99cf1acdde7fed984bf21d907ad423 | 587 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chapter06.command;
import de.lessvoid.nifty.controls.ConsoleCommands.ConsoleCommand;
import chapter06.controller.NiftyController;
/**
*
* @author reden
*/
public class HideCommand implements ConsoleCommand{
private NiftyController controller;
public void execute(String[] strings) {
controller.toggleConsole();
}
public void setController(NiftyController controller){
this.controller = controller;
}
}
| 22.576923 | 66 | 0.688245 |
59dfcd6759d07d6e4118c7760913bd161970f666 | 543 | package com.github.glusk.srp6_variables.wow;
import com.github.glusk.caesar.Bytes;
import com.github.glusk.caesar.Hex;
/** WoW Test Vector: session key (K). */
public final class WoWSessionKey implements Bytes {
/** Pre-set constant that represents this variable. */
private static final Bytes VALUE =
new Hex(
"3D41C92C 4D1F32BA DB7B2D41 3B6E67BC 1A8C483C"
+ "DE6FFD0D 555F922B 28617941 D6B4E394 2842E629"
);
@Override
public byte[] asArray() {
return VALUE.asArray();
}
}
| 27.15 | 58 | 0.668508 |
cd0053578cdc66c04d112cdb2cf9b4806b16e2ff | 477 | package uo.ri.ui.admin;
import alb.util.menu.BaseMenu;
/**
* Menu principal del administrador de la base de datos
*
* @author UO250999
*
*/
public class MainMenu extends BaseMenu {
public MainMenu() {
menuOptions = new Object[][] { { "Administrador", null },
{ "Gestión de mecánicos", MecanicosMenu.class },
{ "Generar bonos por 3 averías", GenerarBonosMenu.class },
};
}
public static void main(String[] args) {
new MainMenu().execute();
}
} | 19.875 | 62 | 0.658281 |
53acedc353f7b5aadfb9513f910d68c638fc91d2 | 6,893 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.spring.concourse.artifactoryresource.io;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* An ordered set of files as returned from the {@link DirectoryScanner}. In order to
* support correct timestamp generation when uploaded to Artifactory. Files in this set
* are ordered as follows within each parent folder:
* <ol>
* <li>Primary artifacts (usually the JAR)</li>
* <li>The POM</li>
* <li>Maven metadata files</li>
* <li>Additional artifacts (E.g. javadoc JARs)</li>
* </ol>
* <p>
* In addition, files may be returned in uploaded batches if multi-threaded uploads are
* being used.
*
* @author Philllip Webb
*/
public final class FileSet implements Iterable<File> {
private final Map<File, String> roots;
private final List<File> files;
private FileSet(Map<File, String> roots, List<File> files) {
this.roots = roots;
this.files = Collections.unmodifiableList(files);
}
/**
* Return a new {@link FileSet} consisting of files from this set that match the given
* predicate.
* @param predicate the filter predicate
* @return a new filtered {@link FileSet} instance
*/
public FileSet filter(Predicate<File> predicate) {
return new FileSet(this.roots, this.files.stream().filter(predicate).collect(Collectors.toList()));
}
/**
* Return the files from this set batched by {@link Category}. The contents of each
* batch can be safely uploaded in parallel.
* @return the batched files
*/
public MultiValueMap<Category, File> batchedByCategory() {
MultiValueMap<Category, File> batched = new LinkedMultiValueMap<>();
Arrays.stream(Category.values()).forEach((category) -> batched.put(category, new ArrayList<>()));
this.files.forEach((file) -> batched.add(getCategory(this.roots, file), file));
batched.entrySet().removeIf((entry) -> entry.getValue().isEmpty());
return batched;
}
@Override
public Iterator<File> iterator() {
return this.files.iterator();
}
public static FileSet of(File... files) {
Assert.notNull(files, "Files must not be null");
return of(Arrays.asList(files));
}
public static FileSet of(List<File> files) {
Assert.notNull(files, "Files must not be null");
MultiValueMap<File, File> filesByParent = getFilesByParent(files);
Map<File, String> roots = getRoots(filesByParent);
Comparator<File> comparator = Comparator.comparing(File::getParent);
comparator = comparator.thenComparing((file) -> getCategory(roots, file));
comparator = comparator.thenComparing(FileSet::getFileExtension);
comparator = comparator.thenComparing(FileSet::getNameWithoutExtension);
List<File> sorted = new ArrayList<>(files);
sorted.sort(comparator);
return new FileSet(roots, sorted);
}
private static MultiValueMap<File, File> getFilesByParent(List<File> files) {
MultiValueMap<File, File> filesByParent = new LinkedMultiValueMap<>();
files.forEach((file) -> filesByParent.add(file.getParentFile(), file));
return filesByParent;
}
private static Map<File, String> getRoots(MultiValueMap<File, File> filesByParent) {
Map<File, String> roots = new LinkedHashMap<>();
filesByParent.forEach((parent, files) -> findRoot(files).ifPresent((root) -> roots.put(parent, root)));
return roots;
}
private static Optional<String> findRoot(List<File> files) {
return files.stream().filter(FileSet::isRootCandidate).map(FileSet::getNameWithoutExtension)
.reduce(FileSet::getShortest);
}
private static boolean isRootCandidate(File file) {
if (isMavenMetaData(file) || file.isHidden() || file.getName().startsWith(".") || file.isDirectory()
|| isChecksumFile(file)) {
return false;
}
return true;
}
private static boolean isChecksumFile(File file) {
String name = file.getName().toLowerCase();
return name.endsWith(".md5") || name.endsWith("sha1");
}
private static String getShortest(String name1, String name2) {
int len1 = (StringUtils.hasLength(name1)) ? name1.length() : Integer.MAX_VALUE;
int len2 = (StringUtils.hasLength(name2)) ? name2.length() : Integer.MAX_VALUE;
return (len1 < len2) ? name1 : name2;
}
private static Category getCategory(Map<File, String> roots, File file) {
if (file.getName().endsWith(".pom")) {
return Category.POM;
}
if (file.getName().endsWith(".asc")) {
return Category.SIGNATURE;
}
if (isMavenMetaData(file)) {
return Category.MAVEN_METADATA;
}
String root = roots.get(file.getParentFile());
return getNameWithoutExtension(file).equals(root) ? Category.PRIMARY : Category.ADDITIONAL;
}
private static boolean isMavenMetaData(File file) {
return file.getName().toLowerCase().startsWith("maven-metadata.xml")
|| file.getName().toLowerCase().startsWith("maven-metadata-local.xml");
}
private static String getFileExtension(File file) {
String extension = StringUtils.getFilenameExtension(file.getName());
return (extension != null) ? extension : "";
}
private static String getNameWithoutExtension(File file) {
String name = file.getName();
String extension = StringUtils.getFilenameExtension(name);
return (extension != null) ? name.substring(0, name.length() - extension.length() - 1) : name;
}
/**
* Categorization used for ordering and batching.
*/
public enum Category {
/**
* The primary artifact (usually the JAR).
*/
PRIMARY("pimary"),
/**
* The POM file.
*/
POM("pom file"),
/**
* An ASC signature file.
*/
SIGNATURE("signature"),
/**
* Maven metadata.
*/
MAVEN_METADATA("maven metadata"),
/**
* Any artifacts that include a classifier (for example Source JARs).
*/
ADDITIONAL("additional");
private final String description;
Category(String description) {
this.description = description;
}
@Override
public String toString() {
return this.description;
}
}
}
| 31.331818 | 105 | 0.721166 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.