blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
003446ff3ebb6c5ed510234ac76059e9d1c462b6 | Java | TheIceCreamBear/TheDarknessBeyond | /src/com/joseph/thedarknessbeyond/gui/windows/StorageWindow.java | UTF-8 | 2,795 | 2.640625 | 3 | [] | no_license | package com.joseph.thedarknessbeyond.gui.windows;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.util.HashMap;
import com.joseph.thedarknessbeyond.engine.TheDarknessBeyondEngine;
import com.joseph.thedarknessbeyond.gui.Window;
import com.joseph.thedarknessbeyond.reference.Reference;
import com.joseph.thedarknessbeyond.reference.ScreenReference;
import com.joseph.thedarknessbeyond.resource.EnumResource;
import com.joseph.thedarknessbeyond.resource.Resource;
import com.joseph.thedarknessbeyond.resource.StorageManager;
/**
* The windo that shows what is in the sotres
* @author Nathan
*
*/
public class StorageWindow extends Window {
private FontRenderContext frc;
private Font font;
public StorageWindow() {
this(1700, 40, 200, 800);
}
public StorageWindow(int x, int y, int width, int height) {
super(x, y, width, height);
this.frc = TheDarknessBeyondEngine.getInstance().getFrc();
if (ScreenReference.scale == 2) {
this.font = Reference.Fonts.SCALED_UP_FONT;
} else {
this.font = Reference.Fonts.DEFAULT_FONT;
}
}
@Override
public void drawBackground(Graphics g, ImageObserver observer) {
// Background
g.setColor(Color.WHITE);
g.drawRect(x, y, width, height);
g.setColor(Color.DARK_GRAY);
g.fillRect(x + 1, y + 1, width - 1, height - 1);
// Header
g.setColor(Color.WHITE);
String s = "Stores:";
g.setFont(font);
Rectangle2D r = font.getStringBounds(s, frc);
int yOff = (int) r.getHeight();
int xOff = 5;
g.drawString(s, x + xOff, y + yOff);
}
@Override
public void drawUpdateableElements(Graphics g, ImageObserver observer) {
Rectangle2D r0 = font.getStringBounds("Stores:", frc);
int yOff = (int) r0.getHeight() * 2;
int xOff = 5;
HashMap<EnumResource, Resource> local = StorageManager.getInstance().getResources();
EnumResource[] er = EnumResource.values();
// Start at 1 to skip invalid, as invalid is only there in the event resource was constructed with the default
for (int i = 1; i < er.length; i++) {
String s = "";
if (local.get(er[i]).getAmount() == 0 && !Reference.DEBUG_MODE) {
continue;
}
s += er[i] + ": " + local.get(er[i]).getAmount();
g.drawString(s, x + xOff, y + yOff);
Rectangle2D r = font.getStringBounds(s, frc);
yOff += r.getHeight() + 5;
}
// TODO this needs to show numbers of items
}
@Override
public void updateUpdateableElements(double deltaTime) {
}
@Override
public boolean isMouseInElement() {
return false;
}
@Override
public void displayToolTip(Graphics g) {
}
} | true |
3e8596709b779ccbc479dc225172b718229c8293 | Java | Draperx/ZJU-CS-3_1 | /程序设计方法学/解释器/mua3/src/src/mua/op/judge/If.java | UTF-8 | 1,535 | 2.578125 | 3 | [] | no_license | package src.mua.op.judge;
import src.mua.Expression;
import src.mua.dataType.Bool;
import src.mua.dataType.List;
import src.mua.dataType.None;
import src.mua.interpreter.NameSpace;
import src.mua.utils.ArgumentUtil;
import src.mua.utils.RunTimeUtil;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @Method: calculate
* getOpName
* getArgNum
**/
public class If extends Expression {
public static final int firstArg = 0;
public static final int secondArg = 1;
public static final int thirdArg = 2;
public static final int firstObj = 0;
public static final int secondObj = 1;
public static final int thirdObj = 2;
final static private ArrayList<Class> argtypes = new ArrayList<Class>(Arrays.asList(
Bool.class,
List.class,
List.class
));
@Override
public String getOpName() {
return "if";
}
@Override
public None calculate(NameSpace nameSpace) throws Exception {
super.calculate(nameSpace);
ArgumentUtil.argCheck(getOpName(), argtypes, argList);
/** get three para **/
Bool cond = (Bool) argList.get(firstArg);
List listA = (List) argList.get(secondArg);
List listB = (List) argList.get(thirdArg);
if (cond.getValue()) {
RunTimeUtil.runList(nameSpace, listA);
}
else {
RunTimeUtil.runList(nameSpace, listB);
}
return new None();
}
public int getArgNum() {
return argtypes.size();
}
} | true |
72a90f539b7096d40d44a22fd0361d98b196f271 | Java | lakshmiguhan/8PMselenium | /src/test/java/com/TestNGScripts/WikiTestCase.java | UTF-8 | 2,075 | 2.578125 | 3 | [] | no_license | package com.TestNGScripts;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class WikiTestCase {
//in TestNg you test steps for test cases will be written as methods
//Test NG annotation to execute a test case
//Create a method as test case TC 1
//All methods wil be void in Test NG except data driven
//Annotation will be writed over the method name
public static WebDriver driver;
//before class annotation
//@BeforeClass //this will be executed first if this annotation is given
@BeforeClass
public void setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\guhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize(); // maximize the browser window
driver.manage().deleteAllCookies(); // delete cookies on the browser
driver.get("https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Selenium+%28software%29");
}
@BeforeMethod
public void login()
{
System.out.println("login to the application");
}
//start execution
@Test(priority='1')
public void createAccount() throws InterruptedException
{
// test steps to perform test cases goes here
// locate the text box and enter data in the text box
driver.findElement(By.id("wpName2")).sendKeys("Username1");
Thread.sleep(3000);
// Inspect password textbox and enter data in the text box
driver.findElement(By.name("wpPassword")).sendKeys("password@123");
//explicit wait
driver.findElement(By.xpath("//button[@value='Create your account']")).click();
}
@Test(priority='2')
public void MainPage()
{
driver.findElement(By.linkText("Main page")).click();
System.out.println(driver.getTitle());
}
@AfterMethod
public void logout()
{
System.out.println("logout of the application");
}
} | true |
bdab0d1b3982b9df8d21cbbeb1f84b0c4f342370 | Java | JuliaBorovets/ProTester | /backend/src/main/java/ua/project/protester/repository/OuterComponentRepository.java | UTF-8 | 12,581 | 1.859375 | 2 | [] | no_license | package ua.project.protester.repository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ua.project.protester.exception.executable.ExecutableComponentNotFoundException;
import ua.project.protester.exception.executable.OuterComponentNotFoundException;
import ua.project.protester.exception.executable.OuterComponentStepSaveException;
import ua.project.protester.exception.executable.action.ActionNotFoundException;
import ua.project.protester.model.executable.ExecutableComponent;
import ua.project.protester.model.executable.ExecutableComponentType;
import ua.project.protester.model.executable.OuterComponent;
import ua.project.protester.model.executable.Step;
import ua.project.protester.request.OuterComponentFilter;
import ua.project.protester.response.LightOuterComponentResponse;
import ua.project.protester.utils.PropertyExtractor;
import java.util.*;
@PropertySource("classpath:queries/outer-component.properties")
@Repository
@RequiredArgsConstructor
@Slf4j
public class OuterComponentRepository {
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private final Environment env;
private final ActionRepository actionRepository;
private final StepParameterRepository stepParameterRepository;
@Transactional(propagation = Propagation.MANDATORY)
public Optional<OuterComponent> saveOuterComponent(OuterComponent outerComponent, boolean isCompound) throws OuterComponentStepSaveException {
String sql = isCompound
? PropertyExtractor.extract(env, "saveCompound")
: PropertyExtractor.extract(env, "saveTestScenario");
String idColumnName = isCompound ? "compound_id" : "scenario_id";
KeyHolder keyHolder = new GeneratedKeyHolder();
namedParameterJdbcTemplate.update(
sql,
new BeanPropertySqlParameterSource(outerComponent),
keyHolder,
new String[]{idColumnName});
Integer outerComponentId = (Integer) keyHolder.getKey();
saveOuterComponentSteps(outerComponent, outerComponentId, isCompound);
try {
return Optional.of(findOuterComponentById(outerComponentId, isCompound));
} catch (OuterComponentNotFoundException e) {
log.warn(e.getMessage());
return Optional.empty();
}
}
@Transactional(propagation = Propagation.MANDATORY)
public List<OuterComponent> findAllOuterComponents(boolean areCompounds, OuterComponentFilter filter, boolean loadSteps) {
String sql = areCompounds
? PropertyExtractor.extract(env, "findAllCompounds")
: PropertyExtractor.extract(env, "findAllTestScenarios");
List<OuterComponent> allOuterComponents = namedParameterJdbcTemplate.query(
sql,
new MapSqlParameterSource()
.addValue("pageSize", filter.getPageSize())
.addValue("offset", filter.getOffset())
.addValue("filterName", filter.getOuterComponentName() + '%'),
new BeanPropertyRowMapper<>(OuterComponent.class));
ExecutableComponentType componentsType = areCompounds
? ExecutableComponentType.COMPOUND
: ExecutableComponentType.TEST_SCENARIO;
allOuterComponents
.forEach(outerComponent -> outerComponent.setType(componentsType));
if (loadSteps) {
allOuterComponents
.forEach(outerComponent ->
outerComponent.setSteps(
findAllOuterComponentStepsById(outerComponent.getId(), areCompounds)));
} else {
allOuterComponents
.forEach(outerComponent ->
outerComponent.setSteps(Collections.emptyList()));
}
return allOuterComponents;
}
public Long countOuterComponents(boolean isCompound, OuterComponentFilter filter) {
String sql = isCompound
? PropertyExtractor.extract(env, "countCompounds")
: PropertyExtractor.extract(env, "countTestScenarios");
return namedParameterJdbcTemplate.queryForObject(
sql,
new MapSqlParameterSource()
.addValue("filterName", filter.getOuterComponentName() + '%'),
Long.class);
}
@Transactional(propagation = Propagation.MANDATORY)
public OuterComponent findOuterComponentById(Integer id, boolean isCompound) throws OuterComponentNotFoundException {
String sql = isCompound
? PropertyExtractor.extract(env, "findCompoundById")
: PropertyExtractor.extract(env, "findTestScenarioById");
try {
OuterComponent outerComponent = namedParameterJdbcTemplate.queryForObject(
sql,
new MapSqlParameterSource().addValue("id", id),
new BeanPropertyRowMapper<>(OuterComponent.class));
if (outerComponent == null) {
throw new OuterComponentNotFoundException(id, isCompound);
}
List<Step> steps = findAllOuterComponentStepsById(outerComponent.getId(), isCompound);
outerComponent.setType(isCompound ? ExecutableComponentType.COMPOUND : ExecutableComponentType.TEST_SCENARIO);
outerComponent.setSteps(steps);
return outerComponent;
} catch (DataAccessException e) {
throw new OuterComponentNotFoundException(id, isCompound, e);
}
}
@Transactional(propagation = Propagation.MANDATORY)
public Optional<OuterComponent> deleteOuterComponentById(Integer id, boolean isCompound) {
String sql = isCompound
? PropertyExtractor.extract(env, "deleteCompoundById")
: PropertyExtractor.extract(env, "deleteTestScenarioById");
Optional<OuterComponent> deletedOuterComponent;
try {
deletedOuterComponent = Optional.of(findOuterComponentById(id, isCompound));
} catch (OuterComponentNotFoundException e) {
log.warn(e.getMessage());
deletedOuterComponent = Optional.empty();
}
namedParameterJdbcTemplate.update(
sql,
new MapSqlParameterSource().addValue("id", id));
return deletedOuterComponent;
}
@Transactional(propagation = Propagation.MANDATORY)
public Optional<OuterComponent> updateOuterComponent(int id, OuterComponent updatedOuterComponent, boolean isCompound) throws OuterComponentStepSaveException {
String sql = isCompound
? PropertyExtractor.extract(env, "updateCompound")
: PropertyExtractor.extract(env, "updateTestScenario");
int updatedRows = namedParameterJdbcTemplate.update(
sql,
new MapSqlParameterSource()
.addValue("id", id)
.addValue("name", updatedOuterComponent.getName())
.addValue("description", updatedOuterComponent.getDescription()));
if (updatedRows == 0) {
return Optional.empty();
}
deleteOuterComponentSteps(id, isCompound);
saveOuterComponentSteps(updatedOuterComponent, id, isCompound);
try {
return Optional.of(findOuterComponentById(id, isCompound));
} catch (OuterComponentNotFoundException e) {
log.warn(e.getMessage());
return Optional.empty();
}
}
public List<LightOuterComponentResponse> findOuterComponentsByInnerCompoundId(int id) {
try {
return namedParameterJdbcTemplate.query(
PropertyExtractor.extract(env, "findOuterComponentsByInnerCompoundId"),
new MapSqlParameterSource().addValue("id", id),
new BeanPropertyRowMapper<>(LightOuterComponentResponse.class));
} catch (DataAccessException e) {
return Collections.emptyList();
}
}
private void deleteOuterComponentSteps(Integer id, boolean isCompound) {
String sql = isCompound
? PropertyExtractor.extract(env, "deleteStepsByCompoundId")
: PropertyExtractor.extract(env, "deleteStepsByTestScenarioId");
namedParameterJdbcTemplate.update(
sql,
new MapSqlParameterSource().addValue("id", id));
}
private void saveOuterComponentSteps(OuterComponent outerComponent, Integer outerComponentId, boolean isCompound) throws OuterComponentStepSaveException {
ListIterator<Step> outerComponentStepsIterator = outerComponent.getSteps().listIterator();
Step outerComponentStep;
while (outerComponentStepsIterator.hasNext()) {
int outerComponentStepOrder = outerComponentStepsIterator.nextIndex();
outerComponentStep = outerComponentStepsIterator.next();
try {
saveOuterComponentStep(outerComponentId, isCompound, outerComponentStep, outerComponentStepOrder);
} catch (DataAccessException e) {
throw new OuterComponentStepSaveException(e);
}
}
}
private void saveOuterComponentStep(Integer outerComponentId, boolean outerComponentIsCompound, Step step, int stepOrder) {
KeyHolder keyHolder = new GeneratedKeyHolder();
namedParameterJdbcTemplate.update(
PropertyExtractor.extract(env, "saveStep"),
new MapSqlParameterSource()
.addValue("outerIsCompound", outerComponentIsCompound)
.addValue("outerCompoundId", outerComponentIsCompound ? outerComponentId : null)
.addValue("outerTestScenarioId", outerComponentIsCompound ? null : outerComponentId)
.addValue("innerIsAction", step.isAction())
.addValue("innerActionId", step.isAction() ? step.getId() : null)
.addValue("innerCompoundId", step.isAction() ? null : step.getId())
.addValue("stepOrder", stepOrder),
keyHolder,
new String[]{"step_id"});
Map<String, String> parameters = step.getParameters();
stepParameterRepository.saveAll(
(Integer) keyHolder.getKey(),
parameters);
}
private List<Step> findAllOuterComponentStepsById(Integer id, boolean isCompound) {
String sql = isCompound
? PropertyExtractor.extract(env, "findAllCompoundStepsById")
: PropertyExtractor.extract(env, "findAllTestScenarioStepsById");
return namedParameterJdbcTemplate.query(
sql,
new MapSqlParameterSource()
.addValue("id", id),
(rs, rowNum) -> initOuterComponentStep(
rs.getInt("id"),
rs.getBoolean("isAction"),
rs.getInt("actionId"),
rs.getInt("compoundId")));
}
private Step initOuterComponentStep(int id, boolean isAction, int actionId, int outerComponentId) {
try {
ExecutableComponent component =
isAction
? actionRepository.findActionById(actionId)
: findOuterComponentById(outerComponentId, true);
Map<String, String> parameters = stepParameterRepository.findAllDataSetParamsId(id);
return new Step(id, isAction, component, parameters);
} catch (OuterComponentNotFoundException | ActionNotFoundException e) {
throw new ExecutableComponentNotFoundException(e);
}
}
}
| true |
b26b347dd9962d1dc635df4bf6b2b84a338e0f93 | Java | jorgehiler/PracticaTeoria1 | /src/Modelo/AF.java | UTF-8 | 41,444 | 2.265625 | 2 | [] | no_license | package Modelo;
import Vista.FormularioPrincipal;
import controlador.controlador;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import sun.font.TrueTypeFont;
import java.util.HashSet;
import java.util.Set;
import jdk.nashorn.internal.parser.TokenType;
public class AF {
private ArrayList estados;
private matrizForma1 mat;
private JFileChooser fc;
private File fichero;
private String cadena;
private final ArrayList transicionEstadoAFD = new ArrayList();
private ArrayList simbolosEntrada;
private ArrayList particiones;
private ArrayList nuevaParticion;
private int flag;
private int numeroParticiones;
public AF() {
this.simbolosEntrada = new ArrayList();
this.estados = new ArrayList();
this.fc = new JFileChooser();
this.fichero = null;
this.particiones = new ArrayList();
this.nuevaParticion = new ArrayList();
this.flag = 0;
this.numeroParticiones = 0;
}
public void construirAutomata() {
mat = new matrizForma1(0, 0);
}
/**
*
* @param automata Autómata al que pertenecen los estados a fusionar
* @param estadosFusionar nodo que contienen los estados a fusionar
* @return objeto que contienene el objeto estado resultante y un ArrayList
* con las posiciones de los estados fusionados "indexTransiciones"
*/
public estadoFusionado fusionarEstados(AF automata, Dnode estadosFusionar) {
ArrayList listIndicesEstado = ut.getArrayDataDnode(estadosFusionar);
ArrayList indexTransiciones = new ArrayList();
int n = listIndicesEstado.size();
estado e = new estado();
if (n == 1) {
int i = (int) listIndicesEstado.get(0);
estado auxE = (estado) this.estados.get(i); //obtener nombre de estado AF actual Dnode
e.setNombreEstado(auxE.getNombreEstado());
e.setTipoEstado(auxE.getTipoEstado());
indexTransiciones.add(i);
} else { // Hace transición a más de un estado
String nuevoNombre = "";
for (int i = 0; i <= n - 1; i++) { //verificar que no exista la fusión
int j = (int) listIndicesEstado.get(i); //indice de la transicion al estado n-simo i
estado et = (estado) this.estados.get(j);
nuevoNombre = nuevoNombre + (String) et.getNombreEstado();
indexTransiciones.add(j); //Transiciones al nuevo estado
}
e.setNombreEstado(nuevoNombre);
e.setTipoEstado(this.obtenerTipoEstado(listIndicesEstado));
}
estadoFusionado ef = new estadoFusionado(e, indexTransiciones);
return ef;
}
/**
* Metodo que construye ArrayLisy con las transasiones por cada simbolo de
* entrada para un estado fusionado o no. Cada posición i del ArrayList
* representa la transicion que hace el estado fusionado k+1 debido a la
* entrada del simbolo i. El metodo almacena cada ArrayList de transiciones
* en el ArrayList "transicionEstadoAFD" en el que la posicion cero
* representa al estado 1 en el automata.
*
* @param ef Contiene un ArrayList en el que cada elemento tiene un indice
* de la posición de los estados fusionados en el AFND
*/
void construirTransicion(estadoFusionado ef) {
ArrayList transPorSimbolo = new ArrayList();
ArrayList estadosDestino;
ArrayList estadosOrigen = ef.transiciones;
int cantidadSimbolos = this.simbolosEntrada.size();
int j = 0;
while (j <= cantidadSimbolos - 1) {
estadosDestino = new ArrayList();
for (int i = 0; i <= estadosOrigen.size() - 1; i++) {
int origen = (int) estadosOrigen.get(i);
Dnode estadoDestino = this.mat.recuperNodo(origen, j);
ArrayList aux = ut.getArrayDataDnode(estadoDestino);
for (int k = 0; k <= aux.size() - 1; k++) {
estadosDestino.add(aux.get(k));
}
}
this.eliminarRepeticionesArrayList(estadosDestino);
transPorSimbolo.add(estadosDestino);
j++;
}
this.transicionEstadoAFD.add(transPorSimbolo);
}
/**
* Metodo que crea e inserta de ser necesario, los estados a los que hace
* transicion el estadoFusionado indicaod
*
* @param ef
* @param AFD Automata deterministico al que pertenece el estado fusionado.
* @return
*/
public Boolean crearInsertarEstados(estadoFusionado ef, AF AFD) {
String nombreEst = ef.e.getNombreEstado();
if (!ef.existeEstado(AFD.estados, nombreEst)) { //Si el destino del estado fusionado no existe insertarlo
estado ne = new estado(ef.e.getNombreEstado(), ef.e.getTipoEstado(), ef.e.isEstadoIncial()); //Si entra uno de aceptacion o inicial actualizar
AFD.insertarEstado(ne);
this.construirTransicion(ef); //Define las transiciones del estado destino
return true;
}
return false;
}
/**
* Convierte un AFND a AFD
*
*/
public AF transformarAFNDaAFD() {
Dnode n = this.mat.primerNodo().getLd();
AF AFD = new AF();
AFD.construirAutomata();
AFD.mat.agregarNodoCabeza(0);
estado ei = new estado(ut.getNombreEstado(estados, 0), ut.getTipoEstado(estados, 0), true); //Estado inicial nuevo
AFD.estados.add(ei); //Agregar estado inicial
AFD.setSimbolosEntrada(this.simbolosEntrada);
Dnode primerNodo = this.mat.primerNodo();
//Aumentar en una unidad la fila y agregar cantidad de columnas
tripleta aux1 = (tripleta) AFD.mat.getMat().getDato();
tripleta aux2 = (tripleta) this.mat.getMat().getDato();
aux1.setFila(1);
aux1.setColumna(aux2.getColumna());
while (primerNodo != n) {
estadoFusionado efn = this.fusionarEstados(AFD, n);
String nombreEst = efn.e.getNombreEstado();
String nombreTransicion = "";
tripleta axi = (tripleta) n.getDato();
int idAct = axi.getFila(); //Estado actual
int idS = axi.getColumna();//Simbolo de entrada actual
estado std = (estado) this.estados.get(idAct);
String estadoAct = (String) std.getNombreEstado();
String simboloE = (String) this.simbolosEntrada.get(idS);
if (this.crearInsertarEstados(efn, AFD)) { //Si el destino del fusionado existe insertarlo
nombreTransicion = nombreEst;
}
AFD.cargarTransicion(simboloE, estadoAct, nombreTransicion);
n = n.getLd();
}
tripleta auxt = (tripleta) AFD.mat.primerNodo().getDato();
Dnode x = (Dnode) auxt.getValor();
int k = 0;
ArrayList<estado> estadosAFD = AFD.estados;
while (!AFD.mat.findeRecorrido(x)) { //Recorre los estados para agregar sus transiciones
int i = 0;
estado estAux = estadosAFD.get(k + 1);
ArrayList indicesEstados = (ArrayList) this.transicionEstadoAFD.get(k); //Los indices del estado al que hace transición por entrada de cada simbolo
String nombreTransicion = "";
while (i <= this.simbolosEntrada.size() - 1) { //Po cada simbolo se inserta un estado
ArrayList a = (ArrayList) indicesEstados.get(i);
String nombreEst = this.decodificarNombreEstado(this.estados, a); //Decodifica el nombre del estado al que se hace tansicion correpondiente al simbolo de la posicion i
String tipoE = this.obtenerTipoEstado(a);
estado e = new estado(nombreEst, tipoE, false);
estadoFusionado efn = new estadoFusionado(e, (ArrayList) indicesEstados.get(i)); //Estado al que hace transicion
this.crearInsertarEstados(efn, AFD); //Si el destino del fusionado existe insertarlo, sino crearlo e insertarlo
nombreTransicion = nombreEst;
String simboloEntrada = (String) AFD.simbolosEntrada.get(i);
AFD.cargarTransicion(simboloEntrada, estAux.getNombreEstado(), nombreTransicion);
i++;
}
tripleta axt = (tripleta) x.getDato();
x = (Dnode) axt.getValor();
k++;
}
return AFD;
}
private void eliminarRepeticionesArrayList(ArrayList a) {
Set<String> set;
set = new HashSet<>(a);
a.clear();
a.addAll(set);
}
/**
* Metodo que retorna un String que indica si el estado es de "Rechazo" o
* "Aceptacion"
*
* @param indicesEstado ArrayList que contiene el indice o indices en el
* AFND del estado procesado o fusionado a evaluar.
* @return retorna un String con "Aceptacion" o "Rechazo"
*/
public String obtenerTipoEstado(ArrayList indicesEstado) {
String tipoE = "Rechazo";
int nj = indicesEstado.size();
for (int ij = 0; ij <= nj - 1; ij++) {
int j = (int) indicesEstado.get(ij);
estado et = (estado) this.estados.get(j);
if (et.getTipoEstado().equals("Aceptacion")) {
tipoE = "Aceptacion";
}
}
return tipoE;
}
/**
* Metodo que recibe un ArrayList con indices de estados como parametro y
* regresa el nombre de los parametros concatenados
*
* @param estados ArrayList con los estados de AFND
* @param arrIndiceE
* @return
*/
public String decodificarNombreEstado(ArrayList<estado> estados, ArrayList arrIndiceE) {
int n = arrIndiceE.size();
String nombreEstado = "";
for (int k = 0; k <= n - 1; k++) {
int indiceEstado = (int) arrIndiceE.get(k);
estado aux = (estado) estados.get(indiceEstado);
nombreEstado = nombreEstado + aux.getNombreEstado();
}
return nombreEstado;
}
public matrizForma1 getMat() {
return mat;
}
public ArrayList getSimbolosEntrada() {
return simbolosEntrada;
}
public void setSimbolosEntrada(ArrayList simbolosEntrada) {
this.simbolosEntrada = simbolosEntrada;
}
public ArrayList getEstados() {
return estados;
}
public String recuperSimboloEntrada(int i) {
String simbolo = simbolosEntrada.get(i).toString();
return simbolo;
}
public estado recuperEstdo(int i) {
estado state = (estado) estados.get(i);
return state;
}
public File getFichero() {
return fichero;
}
public void insertarEntrada(String entrada) {
this.simbolosEntrada.add(entrada);
tripleta t = (tripleta) mat.getMat().getDato();
t.setColumna(t.getColumna() + 1);
mat.getMat().setDato(t);
}
public void insertarEstado(estado estado) {
this.estados.add(estado);
tripleta t = (tripleta) mat.getMat().getDato();
t.setFila(t.getFila() + 1);
mat.getMat().setDato(t);
mat.agregarNodoCabeza(this.estados.lastIndexOf(estado));
}
public boolean validarExistenciaEstado(estado state, String contenido) {
boolean respuesta = false;
int i = this.estados.lastIndexOf(estados);
int j = this.simbolosEntrada.lastIndexOf(contenido);
return respuesta;
}
/**
* Metodo que inserta las transiciones en la matriz dispersa
*
* @param simboloEntrada variable que representa simbolo de entrada
* @param estado variable que representa el estado actual
* @param estadoTransicion variable q indica hacia donde se hara transicion
*/
public void cargarTransicion(String simboloEntrada, String estado, String estadoTransicion) {
int s = this.simbolosEntrada.lastIndexOf(simboloEntrada);
int eo = this.buscarEstadoEnColeccion(estado);
int ed = this.buscarEstadoEnColeccion(estadoTransicion);
mat.agregarTransicion(s, eo, ed);
mat.muestraMatriz();
}
public int buscarEstadoEnColeccion(String estado) {
int respuesta = -1;
estado st;
for (int i = 0; i < this.estados.size(); i++) {
st = (estado) this.estados.get(i);
if (st.getNombreEstado().equals(estado)) {
respuesta = i;
}
}
return respuesta;
}
public boolean evaluarTipoAutomataEstadosInciales() {
//Validemos si existen mas de dos estados iniciales
ArrayList listaEstado = this.estados;
estado st;
boolean respuesta = false;
int cont = 0;
for (int i = 0; i < listaEstado.size(); i++) {
st = (estado) listaEstado.get(i);
if (st.isEstadoIncial()) {
cont++;
}
}
if (cont > 1) {
respuesta = true;
}
return respuesta;
}
public boolean evaluarMasdeUnaTransicion() {
Dnode p, q;
ArrayList rta;
tripleta tx = null;
tripleta txs;
boolean respueta = false;
p = this.mat.primerNodo();
while (!mat.findeRecorrido(p)) {
q = p.getLd();
while (p != q) {
tx = (tripleta) q.getDato();
rta = (ArrayList) tx.getValor();
if (rta.size() == 2) {
respueta = true;
}
q = q.getLd();
}
txs = (tripleta) p.getDato();
p = (Dnode) txs.getValor();
}
return respueta;
}
public void convertirDeterministicoC1() {
//Buscar Estado Inicial
Dnode p = this.mat.primerNodo();
AF automaDete = new AF();
automaDete.construirAutomata();
Dnode q;
int estado;
estado st;
tripleta tx, txs;
ArrayList rta;
String cadena = "";
String auxCadena = "";
char c;
ArrayList simboloEntrada = this.simbolosEntrada;
for (int i = 0; i < simboloEntrada.size(); i++) {
automaDete.insertarEntrada(simboloEntrada.get(i).toString());
}
while (!mat.findeRecorrido(p)) {
tx = (tripleta) p.getDato();
estado = tx.getFila();
st = (estado) this.estados.get(estado);
if (st.isEstadoIncial()) {
automaDete.insertarEstado(st);
q = p.getLd();
while (p != q) {
txs = (tripleta) q.getDato();
rta = (ArrayList) txs.getValor();
if (rta.size() == 1) {
int est = (Integer) rta.get(0);
if (automaDete.recuperEstdo(est) == null) {
//Crear el estado
estado estate = this.recuperEstdo(est);
automaDete.insertarEstado(estate);
}
automaDete.getMat().agregarTransicion(txs.getColumna(), txs.getFila(), (Integer) rta.get(0));
} else {
for (int k = 0; k < rta.size(); k++) {
cadena = cadena + rta.get(k).toString();
}
ArrayList<Boolean> listaRespuesta = new ArrayList();
for (int kl = 0; kl < cadena.length(); kl++) {
char d = cadena.charAt(kl);
int number = (int) d;
estado std = this.recuperEstdo(number);
if (std.getTipoEstado() == "Rechazo") {
listaRespuesta.add(false);
} else {
//Aceptacion
listaRespuesta.add(true);
}
auxCadena = auxCadena + std.getNombreEstado();
}
int acepta = 0;
int rechaza = 0;
//Validando
for (int cb = 0; cb < listaRespuesta.size(); cb++) {
boolean res = listaRespuesta.get(cb);
if (res == true) {
acepta++;
} else {
rechaza++;
}
}
String tipoEstado = "";
if (rechaza == cadena.length()) {
//Estado de Rechazo
tipoEstado = "Rechazo";
} else if (acepta == cadena.length()) {
//Estado Acepte
tipoEstado = "Aceptacion";
} else if (acepta >= 1) {
//Estado acepta
tipoEstado = "Aceptacion";
}
estado estadoDeterministico = new estado(auxCadena, tipoEstado, true);
automaDete.insertarEstado(estadoDeterministico);
automaDete.getMat().agregarTransicion(txs.getColumna(), txs.getFila(), automaDete.estados.lastIndexOf(estadoDeterministico));
}
q = q.getLd();
}
//Movamonos en la matriz que ya estoy construyendo
Dnode cp, dp;
cp = automaDete.getMat().primerNodo();
while (!automaDete.getMat().findeRecorrido(cp)) {
dp = cp.getLd();
while (dp != cp) {
tripleta txsw = (tripleta) dp.getDato();
ArrayList val = (ArrayList) txsw.getValor();
int d = (Integer) val.get(0);
//automaDete.getMat().recuperaNodoCabeza(d);
String ca = String.valueOf(automaDete.getMat().recuperaNodoCabeza(d));
if (ca.length() == 1) {
//inserte normal
//Cargue la transicion
//automaDete.getMat().agregarTransicion(txsw.getColumna(),txsw.getFila(), estado);
}
if (ca.length() > 1) {
//Cocatene estados
ArrayList<Dnode> global = new ArrayList();
for (int hj = 0; hj < ca.length(); hj++) {
int id = (int) ca.charAt(hj);
Dnode pr = this.getMat().recuperaNodoCabeza(id);
Dnode pq = pr.getLd();
while (pq != pr) {
global.add(pq);
pq = pq.getLd();
}
}
}
}
}
}
tripleta tfl = (tripleta) p.getDato();
p = (Dnode) tfl.getValor();
}
}
public void agruparNodos(ArrayList<Dnode> listaNodos) {
ArrayList<Integer> entradas = new ArrayList();
for (int i = 0; i < listaNodos.size(); i++) {
Dnode p = (Dnode) listaNodos.get(i);
tripleta tx = (tripleta) p.getDato();
int number = (Integer) entradas.lastIndexOf(tx.getColumna());
if (number == -1) {
entradas.add(tx.getColumna());
}
}
for (int j = 0; j < entradas.size(); j++) {
}
}
/**
* Metodo que carga el archivo en la aplicacion
*/
public void cargaInterfaz(FormularioPrincipal view) {
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
fc.setDialogTitle("Examinar Archivo");
int result = fc.showSaveDialog(null);
String aux = "";
if (result == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "Cargo Archivo");
this.fichero = fc.getSelectedFile();
try (FileReader fr = new FileReader(fichero)) {
String cadena = "";
int valor = fr.read();
while (valor != -1) {
cadena = cadena + (char) valor;
valor = fr.read();
}
view.getAreaAutomata().setText(cadena);
view.getAreaAutomata().setEditable(false);
//view.getareaCadena().setText(cadena);
} catch (IOException e1) {
e1.printStackTrace();
}
} else if (result == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(null, "No cargo ningun archivo");
}
}
public void guardarArchivo() {
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
fc.setDialogTitle("Examinar Archivo");
int result = fc.showSaveDialog(null);
String aux = "";
if (result == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, "Cargo Archivo");
this.fichero = fc.getSelectedFile();
} else if (result == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(null, "No cargo ningun archivo");
}
}
public void convertirCadenaAutomata(String cadena, controlador c) {
String[] x = cadena.split("\n");
String[] simboloEntrada;
String[] estados;
String[] estadosIniciales;
String[] estadoAceptacion;
String[] transiciones;
System.out.println("Simbolos de entrada:" + x[0]);
simboloEntrada = x[0].split(",");
System.out.println("Estados:" + x[1]);
estados = x[1].split(",");
System.out.println("Estado Inicial:" + x[2]);
estadosIniciales = x[2].split(",");
System.out.println("Estados Aceptacion:" + x[3]);
estadoAceptacion = x[3].split(",");
boolean estadoInicial = false;
String tipoEstado = "";
for (int k = 0; k < simboloEntrada.length - 1; k++) {
this.insertarEntrada(simboloEntrada[k]);
c.agregarColumasJtable(simboloEntrada[k]);
}
for (int feet = 0; feet < estados.length - 1; feet++) {
if (validarEstadoInicial(estadosIniciales, estados[feet])) {
estadoInicial = true;
} else {
estadoInicial = false;
}
if (this.validarEstadoAceptacion(estadoAceptacion, estados[feet])) {
//Estado Aceptacion
tipoEstado = "Aceptacion";
} else {
tipoEstado = "Rechazo";
}
System.out.println(estados[feet] + tipoEstado + estadoInicial);
estado s = new estado(estados[feet], tipoEstado, estadoInicial);
this.insertarEstado(s);
c.agregarFilasJtable(estados[feet]);
}
System.out.println("Transicones");
String[] tmp;
for (int i = 4; i < x.length; i++) {
System.out.println(x[i]);
try {
tmp = x[i].split(",");
int fila = this.buscarEstadoEnColeccion(tmp[0]);
int columna = this.simbolosEntrada.lastIndexOf(tmp[1]);
cargarTransicion(tmp[1], tmp[0], tmp[2]);
c.agregarTransicionJtableDesdeArchivo(fila, columna);
} catch (Exception e) {
}
}
}
public boolean validarEstadoInicial(String[] estadoIniciales, String estado) {
boolean respuesta = false;
for (int i = 0; i < estadoIniciales.length; i++) {
if (estadoIniciales[i].equals(estado)) {
return true;
}
}
return respuesta;
}
public boolean validarEstadoAceptacion(String[] estadosAceptacion, String estado) {
boolean respuesta = false;
for (int i = 0; i < estadosAceptacion.length; i++) {
if (estadosAceptacion[i].equals(estado)) {
respuesta = true;
}
}
return respuesta;
}
public void guardarAutomataEnArchivo(String ruta) {
String entrada = "";
String estados = "";
String estadoAceptacion = "";
String estadosInciales = "";
for (int j = 0; j < this.simbolosEntrada.size(); j++) {
entrada = entrada + simbolosEntrada.get(j) + ",";
}
for (int i = 0; i < this.estados.size(); i++) {
estado st = (estado) this.estados.get(i);
estados = estados + st.getNombreEstado() + ",";
if (st.isEstadoIncial()) {
estadosInciales = estadosInciales + st.getNombreEstado() + ",";
}
if (st.getTipoEstado() == "Aceptacion") {
estadoAceptacion = estadoAceptacion + st.getNombreEstado() + ",";
}
}
//Cargar Transiciones
System.out.println("Simbolos Entrada:" + entrada);
System.out.println("Estados:" + estados);
System.out.println("Estados Inciales:" + estadoAceptacion);
System.out.println("Estados Aceptacion:" + estadoAceptacion);
System.out.println("Lista de Transiciones:");
ArrayList transi = this.cargarTransicionesArchivo();
this.loadFile(ruta, entrada, estados, estadosInciales, estadoAceptacion, transi);
}
public ArrayList cargarTransicionesArchivo() {
ArrayList listaTransiciones = new ArrayList();
int qf, qc, qv;
Dnode p, q;
tripleta tq, tp;
p = this.mat.primerNodo();
String transiciones = "";
while (!(this.mat.findeRecorrido(p))) {
q = p.getLd();
while (q != p) {
tq = (tripleta) q.getDato();
qf = tq.getFila();
qc = tq.getColumna();
//qv = (int) tq.getValor();
ArrayList k = (ArrayList) tq.getValor();
for (int i = 0; i < k.size(); i++) {
//System.out.println(qf + "-" + qc + "-" + k.get(i));
estado st = (estado) this.estados.get(qf);
String entrada = this.simbolosEntrada.get(qc).toString();
int valor = (Integer) k.get(i);
estado destino = (estado) this.estados.get(valor);
//transiciones=transiciones+st.getNombreEstado()+","+entrada+","+destino.getNombreEstado()+","+"\n";
transiciones = st.getNombreEstado() + "," + entrada + "," + destino.getNombreEstado() + ",";
System.out.println(transiciones);
listaTransiciones.add(transiciones);
}
q = q.getLd();
}
tp = (tripleta) p.getDato();
p = (Dnode) tp.getValor();
}
return listaTransiciones;
}
public void loadFile(String nombreArchivo, String entrada, String estados, String estadosInciales, String estadoAceptacion, ArrayList transiciones) {
try (PrintWriter out2 = new PrintWriter(new BufferedWriter(new FileWriter(nombreArchivo, true)))) {
//out2.println(doc + "," + nombre + "," + apellido + "," + direccion + "," + telefono);
out2.println(entrada);
out2.println(estados);
out2.println(estadosInciales);
out2.println(estadoAceptacion);
// out2.println(transiciones);
for (int i = 0; i < transiciones.size(); i++) {
if (i == transiciones.size() - 1) {
out2.print(transiciones.get(i));
} else {
out2.println(transiciones.get(i));
}
}
JOptionPane.showMessageDialog(null, "Archivo Creado");
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean probarHilera(String hilera) {
Dnode p, q;
int estadoAcutal;
int st;
//Dnode p = mat.primerNodo();
tripleta tx;
int tamHilera = hilera.length();
estado estadoActual;
boolean aceptacion = false;
int contador = 0;
int filaEstado = 0;
char ca;
for (int i = 0; i < tamHilera; i++) {
ca = hilera.charAt(i);
if (contador == 0) {
estado status = recuperEstadoIncial();
estadoActual = status;
System.out.println("Estado Incial:" + estadoActual.getNombreEstado());
filaEstado = this.estados.lastIndexOf(status);
System.out.println(filaEstado);
contador = contador + 1;
p = this.mat.recuperaNodoCabeza(filaEstado);
q = p.getLd();
while (p != q) {
tripleta txs = (tripleta) q.getDato();
int entradNumero = txs.getColumna();
String de = (String) this.simbolosEntrada.get(entradNumero);
if (String.valueOf(ca).equals(de)) {
System.out.println("Entroooo");
ArrayList listEstadoActual = (ArrayList) txs.getValor();
int posEstadoActual = (Integer) listEstadoActual.get(0);
estadoActual = this.recuperEstdo(posEstadoActual);
System.out.println(estadoActual.getNombreEstado());
//filaEstado = txs.getFila();
filaEstado = posEstadoActual;
if (estadoActual.getTipoEstado().equals("Aceptacion")) {
aceptacion = true;
} else if (estadoActual.getTipoEstado().equals("Rechazo")) {
aceptacion = false;
}
}
q = q.getLd();
}
} else {
Dnode pl = this.mat.recuperaNodoCabeza(filaEstado);
Dnode ql = pl.getLd();
while (pl != ql) {
tripleta txs = (tripleta) ql.getDato();
int entradNumero = txs.getColumna();
String de = (String) this.simbolosEntrada.get(entradNumero);
if (String.valueOf(ca).equals(de)) {
ArrayList listEstadoActual = (ArrayList) txs.getValor();
int posEstadoActual = (Integer) listEstadoActual.get(0);
estadoActual = this.recuperEstdo(posEstadoActual);
System.out.println(estadoActual.getNombreEstado());
//filaEstado = txs.getFila();
filaEstado = posEstadoActual;
if (estadoActual.getTipoEstado().equals("Aceptacion")) {
aceptacion = true;
} else if (estadoActual.getTipoEstado().equals("Rechazo")) {
aceptacion = false;
}
}
ql = ql.getLd();
}
}
}
return aceptacion;
}
public estado recuperEstadoIncial() {
Dnode p = this.mat.primerNodo();
estado st = null;
while (!mat.findeRecorrido(p)) {
tripleta txs = (tripleta) p.getDato();
int filaEstado = (Integer) txs.getFila();
st = (estado) this.estados.get(filaEstado);
if (st.isEstadoIncial()) {
return st;
}
}
return st;
}
public void simplificarAutomataDeterministico(controlador c) {
for (int i = 0; i < this.simbolosEntrada.size(); i++) {
c.agregarColumnasJtableSimplificado((String) simbolosEntrada.get(i));
}
for (int j = 0; j < this.estados.size(); j++) {
estado st = (estado) estados.get(j);
c.agregarFilasJtableSimplificado(st.getNombreEstado());
}
Dnode p = this.mat.primerNodo();
Dnode q;
while (!mat.findeRecorrido(p)) {
q = p.getLd();
while (p != q) {
tripleta tq = (tripleta) q.getDato();
int qf = tq.getFila();
int qc = tq.getColumna();
ArrayList k = (ArrayList) tq.getValor();
for (int i = 0; i < k.size(); i++) {
//System.out.println(qf + "-" + qc + "-" + k.get(i));
estado st = (estado) this.estados.get(qf);
String entrada = this.simbolosEntrada.get(qc).toString();
int valor = (Integer) k.get(i);
estado destino = (estado) this.estados.get(valor);
c.agregarTransicionesJtableSimplificado(destino.getNombreEstado(), qf, qc);
}
q = q.getLd();
}
tripleta txts = (tripleta) p.getDato();
p = (Dnode) txts.getValor();
}
}
public void convertirAutomata() {
AF AFD = this.transformarAFNDaAFD();
this.mat = AFD.mat;
this.cadena = AFD.cadena;
this.simbolosEntrada = AFD.simbolosEntrada;
this.estados = AFD.estados;
}
public void cargarAutomataConvertido(controlador c) {
for (int i = 0; i < this.simbolosEntrada.size(); i++) {
c.agregarColumnasJtable3((String) simbolosEntrada.get(i));
}
for (int j = 0; j < this.estados.size(); j++) {
estado st = (estado) estados.get(j);
c.agregarFilasJtable3(st.getNombreEstado());
}
Dnode p = this.mat.primerNodo();
Dnode q;
while (!mat.findeRecorrido(p)) {
q = p.getLd();
while (p != q) {
tripleta tq = (tripleta) q.getDato();
int qf = tq.getFila();
int qc = tq.getColumna();
ArrayList k = (ArrayList) tq.getValor();
for (int i = 0; i < k.size(); i++) {
//System.out.println(qf + "-" + qc + "-" + k.get(i));
estado st = (estado) this.estados.get(qf);
String entrada = this.simbolosEntrada.get(qc).toString();
int valor = (Integer) k.get(i);
estado destino = (estado) this.estados.get(valor);
//c.agregarTransicionesJtableSimplificado(destino.getNombreEstado(), qf, qc);
c.agregarTransicionesJtable3(destino.getNombreEstado(), qf, qc);
}
q = q.getLd();
}
tripleta txts = (tripleta) p.getDato();
p = (Dnode) txts.getValor();
}
}
/**
* Método que halla estados equivalentes
*
*/
public void calcularEstadoEquivalentes() {
Particion particionzero = new Particion();
Particion particionone = new Particion();
for (int i = 0; i < this.estados.size(); i++) {
estado tmpstate = (estado) this.estados.get(i);
if (tmpstate.getTipoEstado().equals("Rechazo")) {
//Cree la Partición 0
particionzero.setConjunto(0);
particionzero.getEstados().add(tmpstate);
}
if (tmpstate.getTipoEstado().equals("Aceptacion")) {
//Creer la Partición 1
particionone.setConjunto(1);
particionone.getEstados().add(tmpstate);
}
}
this.particiones.add(particionzero);
this.particiones.add(particionone);
this.numeroParticiones = 2;
for (int j = 0; j < this.simbolosEntrada.size(); j++) ///Simbolos
{
this.nuevaParticion = new ArrayList();
Particion nuevaPar = new Particion();
Particion basePar = new Particion();
for (int i = 0; i < this.particiones.size(); i++) //Particiones
{
int flanco = 0;
Particion particiontmp = (Particion) this.particiones.get(i);
for (int k = 0; k < particiontmp.getEstados().size(); k++) {
estado state = particiontmp.getEstados().get(k);
int indice = this.estados.lastIndexOf(state);
ArrayList respuesta = this.mat.recuperarTransicion(indice, j);
int index = (int) respuesta.get(0);
estado estadoTransicion = (estado) this.estados.get(index);
boolean response = particiontmp.verificaPertenenciaParticion(estadoTransicion);
//System.out.println("Estado Origen" + state.getNombreEstado());
//System.out.println("Hace Transicion a" + estadoTransicion.getNombreEstado());
if (!response) {
flanco++;
nuevaPar.getEstados().add(state);
} else {
//System.out.println("holal"+state.getNombreEstado());
basePar.getEstados().add(state);
//state.getNombreEstado();
}
}
if (flanco != 0) {
//Debe Agregar un nuevo Estado
//this.nuevaParticion.add(nuevaPar);
//Particion particionactualizada=this.reorganizarParticion(particiontmp);
//System.out.println("Particion---------------");
//particionactualizada.imprimirConjuntoParticion();
//basePar.imprimirConjuntoParticion();
//this.particiones.add(nuevaPar);
//this.particiones.set(i,basePar);
this.particiones=new ArrayList();
this.particiones.add(basePar);
this.particiones.add(nuevaPar);
//this.particiones.remove(i);
//this.particiones.add(basePar);
System.out.println("------Hello----");
//this.recorrerParticiones();
//System.out.println("Particion-------------------");
//nuevaPar.imprimirConjuntoParticion();
}
}
}
this.recorrerParticiones();
}
public Particion reorganizarParticion(Particion group) {
//Vieja Particion, actualiza y luego agregar la nueva particion en array list de particiones
ArrayList listadoEstado = group.getEstados();
for (int i = 0; i < listadoEstado.size(); i++) {
estado tmp = (estado) listadoEstado.get(i);
Particion parti = (Particion) this.nuevaParticion.get(0);
//int response = parti.getEstados().lastIndexOf(tmp);
boolean respon = parti.verificaPertenenciaParticion(tmp);
//System.out.println(response);
/*if (response != -1) {
listadoEstado.remove(response);
}
*/
if (respon) {
//Eliminelo
listadoEstado.remove(i);
}
}
Particion particionclonada = new Particion();
particionclonada.setEstados(listadoEstado);
return particionclonada;
}
public void recorrerParticiones() {
for (int i = 0; i < this.particiones.size(); i++) {
System.out.println("Particion");
Particion particion = (Particion) this.particiones.get(i);
particion.imprimirConjuntoParticion();
}
}
public void checkConjuntoTransicion(int simobolo, Particion group) {
ArrayList conjuntoTmp = group.getEstados();
for (int i = 0; i < conjuntoTmp.size(); i++) {
estado estadocheck = (estado) conjuntoTmp.get(i);
int filaEstado = this.estados.lastIndexOf(estadocheck);
int columna = simobolo;
ArrayList respuesta = this.mat.recuperarTransicion(filaEstado, columna);//Se recupera es un index del arraylist
int index = (int) respuesta.get(0);
estado estadoTransicion = (estado) this.estados.get(index);
boolean response = group.verificaPertenenciaParticion(estadoTransicion);
if (!response && this.nuevaParticion.size() == 0) {
Particion nuevaPar = new Particion();
nuevaPar.getEstados().add(estadocheck);
this.nuevaParticion.add(nuevaPar);
}
}
}
}
| true |
988976190a3eac6dff47eac7f244c9a7d84cc766 | Java | witnip/ChatUp | /ChatUp/app/src/main/java/com/witnip/chatup/Activities/PhoneNumberActivity.java | UTF-8 | 1,497 | 2.0625 | 2 | [] | no_license | package com.witnip.chatup.Activities;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthProvider;
import com.witnip.chatup.R;
import com.witnip.chatup.databinding.ActivityPhoneNumberBinding;
public class PhoneNumberActivity extends AppCompatActivity {
ActivityPhoneNumberBinding binding;
FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityPhoneNumberBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser() != null){
gotoMain();
}
binding.etPhoneNumber.requestFocus();
binding.btnContinue.setOnClickListener(v -> {
gotoOTPActivity();
});
}
private void gotoOTPActivity() {
Intent gotoOPTActivity = new Intent(PhoneNumberActivity.this,OTPActivity.class);
gotoOPTActivity.putExtra("phoneNumber",binding.etPhoneNumber.getText().toString().trim());
startActivity(gotoOPTActivity);
}
private void gotoMain() {
Intent gotoMainActivity = new Intent(PhoneNumberActivity.this, MainActivity.class);
startActivity(gotoMainActivity);
finish();
}
} | true |
bff2abceab3c8253fb9419e747954383bf427a80 | Java | li-zhaoyang/MyLeet | /P98/Solution.java | UTF-8 | 578 | 3.25 | 3 | [] | no_license | class Solution {
public boolean isValidBST(TreeNode root) {
return helperValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helperValid(TreeNode root, long leftBound, long rightBound){
if(root == null) return true;
if((root.val >= rightBound) || (root.val <= leftBound) ) return false;
if(root.left != null){
if(!helperValid(root.left, leftBound, root.val)) return false;
}
if(root.right != null){
if(!helperValid(root.right, root.val, rightBound)) return false;
}
return true;
}
}
| true |
57c171c14aa94a7a2390c97c79e3d7645f88e1ac | Java | wanlihua/Androidgit | /src/main/java/com/dtl/gemini/common/base/BaseFragment.java | UTF-8 | 13,324 | 1.734375 | 2 | [] | no_license | package com.dtl.gemini.common.base;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dtl.gemini.base.permission.OnBooleanListener;
import com.dtl.gemini.R;
import com.dtl.gemini.common.baserx.RxManager;
import com.dtl.gemini.common.commonutils.TUtil;
import com.dtl.gemini.common.commonutils.ToastUitl;
import com.dtl.gemini.common.commonwidget.CustomProgressDialog;
import com.dtl.gemini.model.MData;
import com.dtl.gemini.utils.DataUtil;
import com.dtl.gemini.utils.DialogUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.PlatformName;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import butterknife.ButterKnife;
/**
* des:基类fragment
* Created by xsf
* on 2016.07.12:38
*/
/***************使用例子*********************/
//1.mvp模式
//public class SampleFragment extends BaseFragment<NewsChanelPresenter, NewsChannelModel>implements NewsChannelContract.View {
// @Override
// public int getLayoutId() {
// return R.layout.activity_news_channel;
// }
//
// @Override
// public void initPresenter() {
// mPresenter.setVM(this, mModel);
// }
//
// @Override
// public void initView() {
// }
//}
//2.普通模式
//public class SampleFragment extends BaseFragment {
// @Override
// public int getLayoutResource() {
// return R.layout.activity_news_channel;
// }
//
// @Override
// public void initPresenter() {
// }
//
// @Override
// public void initView() {
// }
//}
public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends Fragment {
private OnBooleanListener onPermissionListener;
protected ShareAction shareAction;
protected ShareBoardConfig shareConfig;
protected View rootView;
public T mPresenter;
public E mModel;
public RxManager mRxManager;
private CustomProgressDialog dialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null)
rootView = inflater.inflate(getLayoutResource(), container, false);
mRxManager = new RxManager();
ButterKnife.bind(this, rootView);
EventBus.getDefault().register(this);//注册事件总线EventBus
UMShareInit();
mPresenter = TUtil.getT(this, 0);
mModel = TUtil.getT(this, 1);
if (mPresenter != null) {
mPresenter.mContext = this.getActivity();
}
initPresenter();
initView();
return rootView;
}
//获取布局文件
protected abstract int getLayoutResource();
//简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
public abstract void initPresenter();
//初始化view
protected abstract void initView();
/**
* 通过Class跳转界面
**/
public void startActivity(Class<?> cls) {
startActivity(cls, null);
}
/**
* 通过Class跳转界面
**/
public void startActivityForResult(Class<?> cls, int requestCode) {
startActivityForResult(cls, null, requestCode);
}
/**
* 含有Bundle通过Class跳转界面
**/
public void startActivityForResult(Class<?> cls, Bundle bundle,
int requestCode) {
Intent intent = new Intent();
intent.setClass(getActivity(), cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivityForResult(intent, requestCode);
}
/**
* 含有Bundle通过Class跳转界面
**/
public void startActivity(Class<?> cls, Bundle bundle) {
Intent intent = new Intent();
intent.setClass(getActivity(), cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/**
* 开启加载进度条
*/
public void startProgressDialog() {
startProgressDialog("");
}
/**
* 开启加载进度条
*
* @param msg
*/
public void startProgressDialog(String msg) {
if (dialog == null) {
dialog = CustomProgressDialog.createDialog(getActivity());
}
dialog.setMessage(msg);
dialog.show();
}
/**
* 停止加载进度条
*/
public void stopProgressDialog() {
if (dialog != null) {
dialog.dismiss();
}
}
/**
* 短暂显示Toast提示(来自String)
**/
public void showShortToast(String text) {
if (text != null && !text.equals("")) {
if (text.equals("服务器数据异常"))
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getActivity(), text + "", Toast.LENGTH_SHORT).show();
}
}
/**
* 短暂显示Toast提示(id)
**/
public void showShortToast(int resId) {
ToastUitl.showShort(resId);
}
/**
* 长时间显示Toast提示(来自res)
**/
public void showLongToast(int resId) {
ToastUitl.showLong(resId);
}
/**
* 长时间显示Toast提示(来自String)
**/
public void showLongToast(String text) {
ToastUitl.showLong(text);
}
public void showToastWithImg(String text, int res) {
ToastUitl.showToastWithImg(text, res);
}
/**
* 网络访问错误提醒
*/
public void showNetErrorTip() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
public void showNetErrorTip(String error) {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
if (mPresenter != null)
mPresenter.onDestroy();
mRxManager.clear();
UMShareAPI.get(getActivity()).release();//防止内存泄漏
EventBus.getDefault().unregister(this);//取消注册事件总线EventBus
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);//取消注册事件总线EventBus
}
public void onPermissionRequests(String permission, OnBooleanListener onBooleanListener) {
onPermissionListener = onBooleanListener;
if (ContextCompat.checkSelfPermission(getActivity(),
permission)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_CONTACTS)) {
//权限已有
onPermissionListener.onClick(true);
} else {
//没有权限,申请一下
ActivityCompat.requestPermissions(getActivity(),
new String[]{permission},
1);
}
} else {
onPermissionListener.onClick(true);
}
}
/**
* 事件总线EventBus,使子类处理消息
*/
public abstract void event(MData mData);
//
// @Override
// public void onResume() {
// super.onResume();
// MobclickAgent.onPageStart("BaseFragment");
// }
//
// @Override
// public void onPause() {
// super.onPause();
// MobclickAgent.onPageEnd("BaseFragment");
// }
private void UMShareInit() {
shareAction = new ShareAction(getActivity());
PlatformName.WEIXIN = getActivity().getResources().getString(R.string.umeng_share_weixin);
PlatformName.WEIXIN_CIRCLE = getActivity().getResources().getString(R.string.umeng_share_weixinq);
PlatformName.QZONE = getActivity().getResources().getString(R.string.umeng_share_qqc);
shareAction.setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
shareConfig = new ShareBoardConfig();
shareConfig.setShareboardPostion(ShareBoardConfig.SHAREBOARD_POSITION_BOTTOM);
shareConfig.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_CIRCULAR);
shareConfig.setCancelButtonVisibility(true);
shareConfig.setTitleText(getActivity().getResources().getString(R.string.share));
shareConfig.setCancelButtonText(getActivity().getResources().getString(R.string.umeng_share_cancel));
shareConfig.setTitleVisibility(true);
shareConfig.setShareboardBackgroundColor(0xffffffff);
shareConfig.setIndicatorVisibility(false);
shareAction.setCallback(shareListener);
}
//友盟分享回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
}
private UMShareListener shareListener = new UMShareListener() {
@Override
public void onStart(SHARE_MEDIA platform) {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.start_share), Toast.LENGTH_SHORT).show();
}
@Override
public void onResult(SHARE_MEDIA platform) {
if (platform == SHARE_MEDIA.WEIXIN) {//微信
} else if (platform == SHARE_MEDIA.WEIXIN_CIRCLE) {//朋友圈
} else if (platform == SHARE_MEDIA.QQ) {//qq
} else if (platform == SHARE_MEDIA.QZONE) {//qq空间
}
}
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
if (platform == SHARE_MEDIA.WEIXIN || platform == SHARE_MEDIA.WEIXIN_CIRCLE) {
if (!DataUtil.isWeixinAvilible(getActivity())) {
DialogUtils.showErrorDialog(getActivity(), getActivity().getResources().getString(R.string.hint), getActivity().getResources().getString(R.string.share_no_wx));
} else {
DialogUtils.showErrorDialog(getActivity(), getActivity().getResources().getString(R.string.hint), t.getMessage());
}
} else if (platform == SHARE_MEDIA.QQ || platform == SHARE_MEDIA.QZONE) {
if (!DataUtil.isQQClientAvailable(getActivity())) {
DialogUtils.showErrorDialog(getActivity(), getActivity().getResources().getString(R.string.hint), getActivity().getResources().getString(R.string.share_no_qq));
} else {
DialogUtils.showErrorDialog(getActivity(), getActivity().getResources().getString(R.string.hint), t.getMessage());
}
}
}
@Override
public void onCancel(SHARE_MEDIA platform) {
}
};
// 分享图片
public void shareImg(Bitmap bitmap) {
UMImage image = new UMImage(getActivity(), bitmap);//本地文件
UMImage thumb = new UMImage(getActivity(), R.mipmap.ic_launcher);
image.setThumb(thumb);
image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩,默认为大小压缩,适合普通很大的图
// new ShareAction(this).withMedia(image).share();
shareAction.withMedia(image);
shareAction.withText(getResources().getString(R.string.app_name));
shareAction.open(shareConfig);
}
// 分享图片
public void shareImg(String path) {
File file = new File(path);
UMImage image = new UMImage(getActivity(), file);//本地文件
UMImage thumb = new UMImage(getActivity(), R.mipmap.ic_launcher);
image.setThumb(thumb);
image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩,默认为大小压缩,适合普通很大的图
// new ShareAction(this).withMedia(image).share();
shareAction.withMedia(image);
shareAction.withText(getResources().getString(R.string.app_name));
shareAction.open(shareConfig);
}
//分享自定义信息
protected void shareCustom(String url, String title, String imgUrl, String text) {
UMWeb web = new UMWeb(url);
//标题
web.setTitle(title);
//缩略图
UMImage thumb = new UMImage(getActivity(), imgUrl);
web.setThumb(thumb);
//描述
web.setDescription(text);
shareAction.withMedia(web);
shareAction.withText(text);
//分享
shareAction.open(shareConfig);
}
}
| true |
d2d98c09d4d082938151e93e24b394569cbad11e | Java | tingley/globalsight | /main6/envoy/src/java/com/globalsight/everest/webapp/applet/admin/graphicalworkflow/gui/planview/GLine.java | UTF-8 | 1,570 | 2.203125 | 2 | [] | no_license | /**
* Copyright 2009 Welocalize, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.globalsight.everest.webapp.applet.admin.graphicalworkflow.gui.planview;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.Color;
class GLine extends GraphicalShape
{
int width = 90;
int height = 90;
public GLine(Point position)
{
super(position);
}
public boolean contains(Point point)
{
int halfHeight = height / 2;
int halfWidth = width / 2;
return(point.x > position.x-halfWidth && point.x < position.x+halfWidth
&& point.y > position.y-halfHeight && point.y < position.y+halfHeight);
}
public void dragging(java.awt.Graphics2D g2, Point p)
{
}
public void paint(java.awt.Graphics2D g2, Point p, Color c, float zoomRatio, boolean selected)
{
//g2.transform(at);
}
public void paint(java.awt.Graphics2D g2, Point p, Color c, float zoomRatio)
{
// g2.transform(at);
}
}
| true |
0ff8d1037cde7c67d78144c8fe5413ce1a84a3a0 | Java | Kirillbl9/FifthTask | /src/main/java/JDBC.java | UTF-8 | 1,170 | 2.703125 | 3 | [] | no_license | import com.sun.istack.internal.NotNull;
import java.sql.*;
public final class JDBC {
@NotNull
public static Connection con=null;
public static void main(@NotNull String[] args) throws SQLException {
try {
con=DriverManager.getConnection( "jdbc:postgresql://localhost:5432/postgres", "postgres", "tsucanovden" );
//CRUD operation:
// CreateTable.useTable();
// UpdateTable.useTable();
// ReadTable.useTable();
// DeleteTable.useTable();
//Step 3:
// ThirdTask_3_1.thirdTask_3_1();
// ThirdTask_3_2.thirdTask_3_2(1000);
// ThirdTask_3_3.thirdTask_3_3( Date.valueOf( "2006-03-03" ), Date.valueOf( "2010-03-03" ));
// ThirdTask_3_4.thirdTask_3_4( Date.valueOf( "2006-03-03" ), Date.valueOf( "2010-03-03" ));
// ThirdTask_3_5.thirdTask_3_5( Date.valueOf( "2006-03-03" ), Date.valueOf( "2010-03-03" ));
} catch (SQLException err) {
System.out.println( err.getMessage() );
} finally {
if (con != null) {
con.close();
}
}
}
}
| true |
2afcdf1ee9b22ccc984cbcea2d1c134a967911f0 | Java | tectronics/evergreen-base | /WebPalo/web-etl/test/src/com/tensegrity/webetlclient/modules/core/server/configuration/ETLServerConfiguratorTest.java | UTF-8 | 2,911 | 2.375 | 2 | [] | no_license | package com.tensegrity.webetlclient.modules.core.server.configuration;
import java.util.regex.Matcher;
import junit.framework.TestCase;
import com.tensegrity.webetlclient.modules.core.server.configuration.WebETLConfiguration.IETLServer;
public class ETLServerConfiguratorTest extends TestCase {
WebETLConfiguration webConfig;
TestConfigurator configurator;
String value = "ddd";
protected void setUp() throws Exception {
webConfig = new WebETLConfiguration();
configurator = new TestConfigurator();
}
public void testGetPropertyName() {
String name = "testProperty";
assertEquals(name, configurator.getPropertyName());
}
public void testPropertyPattern(){
assertPropertyMatches(false, "etl.server.testProperty");
assertPropertyMatches(false, "etl.server6.address");
assertPropertyMatches(false, "etl.server6g.testProperty");
assertPropertyMatches(true, "etl.server6.testProperty");
assertPropertyMatches(true, "etl.server0.testProperty");
assertPropertyMatches(true, "etl.server10.testProperty");
assertPropertyMatches(true, "etl.server513.testProperty");
assertPropertyMatches(false, "etl.server-1.testProperty");
}
private void assertPropertyMatches(boolean result, String paramName) {
Matcher m = configurator.getPattern().matcher(paramName);
assertEquals(result, m.matches());
}
public void testParse_testSetPropertyInvocation(){
String param = "etl.server5.testProperty";
Matcher m = configurator.getPattern().matcher(param);
if(m.matches()){
configurator.parse(webConfig, m, value);
}else{
fail("m.matches()==false");
}
assertEquals(value, configurator.getValue());
assertEquals(1, configurator.getInvocationCount());
}
public void testParse_nullValue(){
value = null;
String param = "etl.server5.testProperty";
Matcher m = configurator.getPattern().matcher(param);
if(m.matches()){
configurator.parse(webConfig, m, value);
}else{
fail("m.matches()==false");
}
assertNull(configurator.getValue());
}
public void testParse_nullWebConfig() {
webConfig = null;
String param = "etl.server5.testProperty";
Matcher m = configurator.getPattern().matcher(param);
try{
if (m.matches()) {
configurator.parse(webConfig, m, value);
}else{
fail("m.matches()==false");
}
fail("NullPointerException should be thrown");
}catch (NullPointerException e) {
// ok
}
}
static class TestConfigurator extends ETLServerConfigurator{
private String value;
private int count = 0;
protected String getPropertyName() {
return "testProperty";
}
protected void setProperty(IETLServer server, String value) {
this.value = value;
count++;
}
public String getValue(){
return this.value;
}
public int getInvocationCount(){
return this.count;
}
}
}
| true |
b74c845ee9b310b085bd89f2e2c0347f8b5a9475 | Java | ndw6152/javaCode | /src/randomStuff/BaseClass.java | UTF-8 | 880 | 3.375 | 3 | [] | no_license | package randomStuff;
/**
* Created by ndw6152 on 8/13/2018.
*/
class DerivedClass extends BaseClass {
@Override
public void doSomething() {
System.out.println("SOMETHING");
}
}
class DerivedOver extends BaseClass {
public void doSomething() {
System.out.println("Something better");
}
public void printWorld() {
System.out.println("hello Monde " + hello);
}
}
public abstract class BaseClass {
int hello = 100;
int world;
public abstract void doSomething();
public void printWorld() {
System.out.println("hello world");
}
public static void main(String[] args) {
DerivedClass sol = new DerivedClass();
sol.doSomething();
sol.printWorld();
DerivedOver sol2 = new DerivedOver();
sol2.doSomething();
sol2.printWorld();
}
}
| true |
7689e5a59c9ca89a80673e4ef2afbe2f1ad90a62 | Java | TahmidU/RoomDesignerAPIV1 | /src/main/java/com/aarrd/room_designer/user/security/vertification/registration/OnRegistrationComplete.java | UTF-8 | 519 | 2 | 2 | [] | no_license | package com.aarrd.room_designer.user.security.vertification.registration;
import com.aarrd.room_designer.user.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.context.ApplicationEvent;
@EqualsAndHashCode(callSuper = false)
public class OnRegistrationComplete extends ApplicationEvent
{
private final User user;
public OnRegistrationComplete(final User user) {
super(user);
this.user = user;
}
public User getUser() {
return user;
}
}
| true |
e06c8b999cf11c99c024cc5d47935b70c5bc5c82 | Java | StuartApp/kafka-connect-field-and-time-partitioner | /src/main/java/com/canelmas/kafka/connect/FieldAndTimeBasedPartitioner.java | UTF-8 | 5,516 | 1.984375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2019 Can Elmas <canelm@gmail.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.canelmas.kafka.connect;
import io.confluent.connect.storage.errors.PartitionException;
import io.confluent.connect.storage.partitioner.TimeBasedPartitioner;
import io.confluent.connect.storage.partitioner.TimestampExtractor;
import io.confluent.connect.storage.util.DataUtils;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.connect.connector.ConnectRecord;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.sink.SinkRecord;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Locale;
import java.util.Map;
public final class FieldAndTimeBasedPartitioner<T> extends TimeBasedPartitioner<T> {
private static final Logger log = LoggerFactory.getLogger(FieldAndTimeBasedPartitioner.class);
private long partitionDurationMs;
private DateTimeFormatter formatter;
private TimestampExtractor timestampExtractor;
private PartitionFieldExtractor partitionFieldExtractor;
protected void init(long partitionDurationMs, String pathFormat, Locale locale, DateTimeZone timeZone, Map<String, Object> config) {
this.delim = (String)config.get("directory.delim");
this.partitionDurationMs = partitionDurationMs;
try {
this.formatter = getDateTimeFormatter(pathFormat, timeZone).withLocale(locale);
this.timestampExtractor = this.newTimestampExtractor((String)config.get("timestamp.extractor"));
this.timestampExtractor.configure(config);
this.partitionFieldExtractor = new PartitionFieldExtractor((String)config.get("partition.field"));
} catch (IllegalArgumentException e) {
ConfigException ce = new ConfigException("path.format", pathFormat, e.getMessage());
ce.initCause(e);
throw ce;
}
}
private static DateTimeFormatter getDateTimeFormatter(String str, DateTimeZone timeZone) {
return DateTimeFormat.forPattern(str).withZone(timeZone);
}
public static long getPartition(long timeGranularityMs, long timestamp, DateTimeZone timeZone) {
long adjustedTimestamp = timeZone.convertUTCToLocal(timestamp);
long partitionedTime = adjustedTimestamp / timeGranularityMs * timeGranularityMs;
return timeZone.convertLocalToUTC(partitionedTime, false);
}
public String encodePartition(SinkRecord sinkRecord, long nowInMillis) {
final Long timestamp = this.timestampExtractor.extract(sinkRecord, nowInMillis);
final String partitionField = this.partitionFieldExtractor.extract(sinkRecord);
return this.encodedPartitionForFieldAndTime(sinkRecord, timestamp, partitionField);
}
public String encodePartition(SinkRecord sinkRecord) {
final Long timestamp = this.timestampExtractor.extract(sinkRecord);
final String partitionFieldValue = this.partitionFieldExtractor.extract(sinkRecord);
return encodedPartitionForFieldAndTime(sinkRecord, timestamp, partitionFieldValue);
}
private String encodedPartitionForFieldAndTime(SinkRecord sinkRecord, Long timestamp, String partitionField) {
if (timestamp == null) {
final String msg = "Unable to determine timestamp using timestamp.extractor " + this.timestampExtractor.getClass().getName() + " for record: " + sinkRecord;
log.error(msg);
throw new ConnectException(msg);
} else if (partitionField == null) {
final String msg = "Unable to determine partition field using partition.field '" + partitionField + "' for record: " + sinkRecord;
log.error(msg);
throw new ConnectException(msg);
} else {
final DateTime bucket = new DateTime(getPartition(this.partitionDurationMs, timestamp.longValue(), this.formatter.getZone()));
return partitionField + this.delim + bucket.toString(this.formatter);
}
}
static class PartitionFieldExtractor {
private final String fieldName;
PartitionFieldExtractor(String fieldName) {
this.fieldName = fieldName;
}
String extract(ConnectRecord<?> record) {
Object value = record.value();
if (value instanceof Struct || value instanceof Map) {
return (String) DataUtils.getNestedFieldValue(value, fieldName);
} else {
FieldAndTimeBasedPartitioner.log.error("Value is not of Struct or Map type.");
throw new PartitionException("Error encoding partition.");
}
}
}
}
| true |
46ea245baf0d42c458943b3e219917e693707962 | Java | YokoBurke/BakingApplication | /app/src/main/java/com/example/android/bakingapplication/utilities/RecipeAdapter.java | UTF-8 | 3,019 | 2.578125 | 3 | [] | no_license | package com.example.android.bakingapplication.utilities;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.android.bakingapplication.DetailActivity;
import com.example.android.bakingapplication.data.recipe;
import java.util.List;
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
private static final String LOG_TAG = RecipeAdapter.class.getSimpleName();
private List<recipe> myRecipe;
private Context myContext;
final private ListItemClickListener mOnClickListener;
public interface ListItemClickListener {
void onListItemClick(int clickedItemIndex);
}
public RecipeAdapter (Context mContext, List<recipe> mRecipe, ListItemClickListener mListener){
myRecipe = mRecipe;
myContext = mContext;
mOnClickListener = mListener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView recipeNameTextView;
public TextView servingsTextView;
public MyViewHolder(View itemView){
super(itemView);
recipeNameTextView = (TextView) itemView.findViewById(R.id.recipe_name);
servingsTextView = (TextView) itemView.findViewById(R.id.recipe_serving_number);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int clickedPosition = getAdapterPosition();
mOnClickListener.onListItemClick(clickedPosition);
// add intent here
Intent intent = new Intent(myContext, DetailActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, myRecipe.get(clickedPosition));
Log.i(LOG_TAG, "Name is " + myRecipe.get(clickedPosition).getName());
myContext.startActivity(intent);
}
}
@NonNull
@Override
public RecipeAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
int myLayoutId = R.layout.main_card_item;
View itemView = LayoutInflater.from(parent.getContext()).inflate(myLayoutId, parent, false);
MyViewHolder recipeViewHolder = new MyViewHolder(itemView);
return recipeViewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecipeAdapter.MyViewHolder holder, int position) {
String myRecipeName = myRecipe.get(position).getName();
String myServingNumber = Integer.toString(myRecipe.get(position).getServings());
holder.recipeNameTextView.setText(myRecipeName);
holder.servingsTextView.setText(myServingNumber);
}
@Override
public int getItemCount() {
if (myRecipe == null) {
return 0;
}
return myRecipe.size();
}
}
| true |
f31138cd215610e6d7c5e438f0d165b40e8bca9f | Java | CruseoGithub/pacman | /core/src/uas/lntv/pacmangame/Screens/GameScreen.java | UTF-8 | 10,180 | 2.71875 | 3 | [] | no_license | package uas.lntv.pacmangame.Screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import uas.lntv.pacmangame.Managers.Assets;
import uas.lntv.pacmangame.Maps.GameMap;
import uas.lntv.pacmangame.Maps.Tile;
import uas.lntv.pacmangame.PacManGame;
import uas.lntv.pacmangame.Scenes.ControllerButtons;
import uas.lntv.pacmangame.Scenes.ControllerJoystick;
import uas.lntv.pacmangame.Scenes.Hud;
import uas.lntv.pacmangame.Managers.PrefManager;
import uas.lntv.pacmangame.Sprites.Actor;
import uas.lntv.pacmangame.Sprites.Enemy;
import uas.lntv.pacmangame.Sprites.PacMan;
/**
* The GameScreen is the screen, where the main action takes place. It offers different PowerUps
* on designated places. There are also a lot of dots, that are supposed to be eaten by PacMan
* to get into the next level.
*/
public class GameScreen extends MapScreen {
/* Fields */
private boolean enemiesSlow = false;
private boolean itemTaken = false;
private boolean pacManSuper = false;
private boolean pauseActive = false;
private boolean paused = false;
private float itemCoolDown = 0;
private float slowDownTime;
private float supStatusTime;
/* Constructor */
/**
* Initializes the GameScreen depending on the level. It sets the moving speed of the actors
* and the number of ghosts and each ghost's difficulty.
* @param game the running PacManGame
* @param assets asset management
* @param path the path where the map is stored
*/
public GameScreen(PacManGame game, Assets assets, String path) {
super(game, assets, path, Type.GAME);
this.hud = new Hud(game, assets, this, true);
this.pacman = new PacMan(game, assets, 14 * TILE_SIZE, 21 * TILE_SIZE, this);
this.GHOSTS.add(new Enemy(13 * TILE_SIZE, 33 * TILE_SIZE, assets,this, assets.manager.get(assets.GHOST_1)));
if(PacManGame.getLevel() >= 2) {
this.GHOSTS.add(new Enemy(15 * TILE_SIZE, 30 * TILE_SIZE, assets,this, assets.manager.get(assets.GHOST_2)));
this.GHOSTS.get(1).setState(Actor.State.BOXED);
this.GHOSTS.get(1).setBoxTimer(5);
map.getTile(15 * TILE_SIZE, 30 * TILE_SIZE).enter(this.GHOSTS.get(1));
}
if(PacManGame.getLevel() >= 4) {
this.GHOSTS.add(new Enemy(12 * TILE_SIZE, 30 * TILE_SIZE, assets,this, assets.manager.get(assets.GHOST_3)));
this.GHOSTS.get(2).setState(Actor.State.BOXED);
this.GHOSTS.get(2).setBoxTimer(10);
map.getTile(12 * TILE_SIZE, 30 * TILE_SIZE).enter(this.GHOSTS.get(2));
GHOSTS.get(0).setDifficulty(Enemy.Difficulty.MEDIUM);
}
if(PacManGame.getLevel() >= 6){
GHOSTS.get(1).setDifficulty(Enemy.Difficulty.MEDIUM);
pacman.setSpeed(pacman.getSpeed()*2);
for(Enemy ghost : GHOSTS) ghost.setSpeed(pacman.getSpeed());
}
if(PacManGame.getLevel() >= 8){
GHOSTS.get(2).setDifficulty(Enemy.Difficulty.MEDIUM);
}
if(PacManGame.getLevel() >= 12){
GHOSTS.get(0).setDifficulty(Enemy.Difficulty.HARD);
}
if(PacManGame.getLevel() >= 19){
GHOSTS.get(1).setDifficulty(Enemy.Difficulty.HARD);
}
if(PacManGame.getLevel() >= 24){
pacman.setSpeed(pacman.getSpeed()*2);
for(Enemy ghost : GHOSTS) ghost.setSpeed(pacman.getSpeed());
}
if(PacManGame.getLevel() >= 30){
GHOSTS.get(2).setDifficulty(Enemy.Difficulty.HARD);
}
}
/* Accessors */
public boolean isPacManSuper() { return pacManSuper; }
/* Mutators */
public void setPauseActive(boolean bool) { pauseActive = bool; }
/* Methods */
/**
* Updates the timer of the cool-down and checks, if the different time thresholds are reached.
* Compares the remaining cool-down time with the amount of items on the map and acts according
* to it.
*/
private void updateCoolDown(){
if(itemTaken){
itemCoolDown -= Gdx.graphics.getDeltaTime();
switch(map.countItems()){
case 4:
itemTaken = false;
break;
case 3:
if(itemCoolDown < 0) this.map.generateSpecialItem();
break;
case 2:
if(itemCoolDown < 10) this.map.generateSpecialItem();
break;
case 1:
if(itemCoolDown < 20) this.map.generateSpecialItem();
break;
case 0:
if(itemCoolDown < 30) this.map.generateSpecialItem();
break;
}
}
}
/**
* Updates the timer of the hunting buff and checks if the time is up.
* Changes back to normal PacMan after the Hunter-Item-Time is over.
* Ghosts also return to the difficulty they previously had and stop running away.
*/
private void updateHunter(){
if(pacManSuper) {
supStatusTime -= Gdx.graphics.getDeltaTime();
if (supStatusTime < 0) {
pacManSuper = false;
switchMusicGame();
pacman.setTexture(ASSETS.manager.get(ASSETS.PAC_MAN));
pacman.setSpeed(pacman.getSpeed()/2);
for (Enemy ghost : GHOSTS) {
ghost.resetDifficulty();
}
}
}
}
/**
* Updates the timer of the SloMo buff and checks if the time is up.
* After the SloMo buff ends, the Ghosts return to their normal speed.
*/
private void updateSloMo(){
if(enemiesSlow){
slowDownTime -= Gdx.graphics.getDeltaTime();
if(slowDownTime < 0){
for (Enemy ghost : GHOSTS) {
ghost.correctPosition(ghost.getDirection());
ghost.setSpeed(ghost.getSpeed()*2);
}
enemiesSlow = false;
}
}
}
/**
* Additional pause activation via SPACE bar.
*/
@Override
protected boolean handleInput(){
if(Gdx.input.isKeyPressed(Input.Keys.SPACE)) pauseActive = true;
return super.handleInput();
}
/**
* Buffs of the different items that can be picked up.
*/
public void activateBuff(Tile.Item buffType){
switch (buffType) {
case HUNTER:
this.itemTaken = true;
this.itemCoolDown += 10;
this.supStatusTime = 10;
if (!pacManSuper) {
this.switchMusicHunting();
this.pacman.setTexture(ASSETS.manager.get(ASSETS.SUPER_PAC));
this.pacman.correctPosition(pacman.getDirection());
this.pacman.setSpeed(this.pacman.getSpeed() * 2);
this.pacManSuper = true;
}
break;
case SLO_MO:
this.itemTaken = true;
this.itemCoolDown += 10;
this.slowDownTime = 10;
if(!enemiesSlow) {
for (Enemy ghost : GHOSTS) ghost.setSpeed(ghost.getSpeed() / 2);
this.enemiesSlow = true;
}
break;
case TIME:
this.itemTaken = true;
this.itemCoolDown += 10;
this.hud.updateTime(-10);
this.hud.resetTimeStamp();
break;
case LIFE:
this.itemTaken = true;
this.itemCoolDown += 10;
if(PacManGame.getLives() < 3) {
PacManGame.addLive();
hud.resetLives();
} else{
PacManGame.increaseScore(75);
}
break;
}
}
/**
* Checks for updates on the screen, renders the game and updates the hud.
* @param delta time parameter used by libGDX
*/
@Override
public void render(float delta) {
update(delta);
super.render(delta);
hud.update();
if (pacman.getState() == Actor.State.DIEING) {
hud.animateLives(delta);
}
hud.getStage().draw();
}
/**
* Game over when time hits 0, Level up when all dots are eaten.
* When Pause is active the PauseScreen is opened.
*/
@Override
public void update(float dt) {
super.update(dt);
if(ready) hud.updateTime(Gdx.graphics.getDeltaTime());
updateCoolDown();
updateHunter();
updateSloMo();
if(hud.getTime() < 0){
this.dispose();
if(PacManGame.prefManager.addScore(PacManGame.getScore(), "Time elapsed", PacManGame.getLevel() + 1)){
GAME.setScreen(new ScoreScreen(GAME, ASSETS, ASSETS.SCORE_MAP));
} else {
GAME.setScreen(new MenuScreen(GAME, ASSETS, ASSETS.MENU_MAP));
}
PacManGame.resetLives();
PacManGame.resetScore();
PacManGame.resetLevel();
}
if(GameMap.getCollectedDots() == GameMap.TOTAL_DOTS){
PacManGame.levelUp();
PacManGame.increaseScore((int)hud.getTime());
this.dispose();
GAME.setScreen(new GameScreen(GAME, ASSETS, hud.getMap()));
}
if(paused) {
if(PrefManager.isJoystick()) this.controller = new ControllerJoystick(ASSETS, this);
else this.controller = new ControllerButtons(ASSETS,this);
if(PrefManager.isMusicOn()){
if(pacManSuper) ASSETS.manager.get(ASSETS.HUNTING_MUSIC).play();
else music.play();
}
paused = false;
pauseActive = false;
}
if(pauseActive){
if(music.isPlaying()) music.pause();
if(ASSETS.manager.get(ASSETS.HUNTING_MUSIC).isPlaying()) ASSETS.manager.get(ASSETS.HUNTING_MUSIC).pause();
GAME.setScreen(new PauseScreen(GAME, ASSETS, ASSETS.PAUSE, this, hud));
paused = true;
}
}
} | true |
899ab4d4bf76dea919d77d1fdd03a068d942114a | Java | iTitus/advent-of-code | /src/main/java/io/github/ititus/aoc/aoc21/day07/Day07.java | UTF-8 | 2,896 | 3.203125 | 3 | [
"MIT"
] | permissive | package io.github.ititus.aoc.aoc21.day07;
import io.github.ititus.aoc.common.Aoc;
import io.github.ititus.aoc.common.AocInput;
import io.github.ititus.aoc.common.AocSolution;
import io.github.ititus.aoc.common.AocStringInput;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntUnaryOperator;
import java.util.Arrays;
import java.util.stream.IntStream;
@Aoc(year = 2021, day = 7)
public class Day07 implements AocSolution {
IntList positions;
private static int distance(int a, int b) {
return Math.abs(b - a);
}
private static IntUnaryOperator simpleDistanceTo(int b) {
return a -> distance(a, b);
}
private static IntUnaryOperator advancedDistanceTo(int b) {
return a -> {
int n = distance(a, b);
return (n * (n + 1)) / 2;
};
}
@Override
public void executeTests() {
AocInput input = new AocStringInput("16,1,2,0,4,2,7,1,2,14");
readInput(input);
System.out.println(part1());
System.out.println(part2());
}
@Override
public void readInput(AocInput input) {
positions = Arrays.stream(input.readString().split(",".trim()))
.map(String::strip)
.mapToInt(Integer::parseInt)
.sorted()
.collect(IntArrayList::new, IntList::add, IntList::addAll);
}
@Override
public Object part1() {
// the cheapest will always be the median, because the median will minimize the mean absolute error
int median;
boolean medianRounded;
if (positions.size() % 2 == 0) {
int l = positions.getInt(positions.size() / 2 - 1);
int r = positions.getInt(positions.size() / 2);
if (l == r) {
median = l;
medianRounded = false;
} else {
int sum = l + r;
median = sum / 2;
medianRounded = sum % 2 != 0;
}
} else {
median = positions.getInt(positions.size() / 2);
medianRounded = false;
}
return IntStream.rangeClosed(median, medianRounded ? median + 1 : median)
.mapToObj(Day07::simpleDistanceTo)
.mapToInt(d -> positions.intStream().map(d).sum())
.min().orElseThrow();
}
@Override
public Object part2() {
// the cheapest will always be the mean +- 1/2
double mean = positions.intStream().average().orElseThrow();
int start = (int) Math.floor(mean - 0.5);
int end = (int) Math.ceil(mean + 0.5);
return IntStream.rangeClosed(start, end)
.mapToObj(Day07::advancedDistanceTo)
.mapToInt(d -> positions.intStream().map(d).sum())
.min().orElseThrow();
}
}
| true |
abf988849923e01f2d7a42161cdc96cd0aa3e6aa | Java | ClaRadu/java-jogl-primitive-s--wall | /joglcubes/objs/Text.java | UTF-8 | 1,886 | 2.78125 | 3 | [
"MIT"
] | permissive | // thanks to NeHe: http://nehe.gamedev.net/
package joglcubes.objs;
import com.jogamp.opengl.GLAutoDrawable;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import com.jogamp.opengl.util.awt.TextRenderer;
import java.text.DecimalFormat;
public class Text {
GLAutoDrawable drw;
private TextRenderer textRenderer;
private String msg = "Primitive(s) Wall ( java+jogl ) - C.R.G. 2018";
private DecimalFormat formatter = new DecimalFormat("###0.00");
private int textPosX; // x-position of the text
private int textPosY; // y-position of the text
public Text(GLAutoDrawable drawable) {
drw = drawable;
// Allocate textRenderer with the chosen font
textRenderer = new TextRenderer(new Font("SansSerif", Font.BOLD, 14));
Rectangle2D bounds = textRenderer.getBounds(msg);
int textWidth = (int)bounds.getWidth();
int textHeight = (int)bounds.getHeight();
// Centralize text on the canvas
textPosX = (drawable.getSurfaceWidth() - textWidth) / 2;
// textPosY = (drawable.getSurfaceHeight() - textHeight) / 2 - textHeight;
textPosY = (drawable.getSurfaceHeight() - textHeight*2);
}
public void Display() {
// Prepare to draw text
textRenderer.beginRendering(drw.getSurfaceWidth(), drw.getSurfaceHeight());
// Pulsing colors based on text position, set color in RGBA
textRenderer.setColor(0.5f, // R
0.5f, // G
1f, // B
0.8f); // Alpha
// 2D text using int (x, y) coordinates in OpenGL coordinates system,
// i.e., (0,0) at the bottom-left corner, instead of Java Graphics coordinates.
// x is set to between (+/-)10. y is set to be (+/-)80.
textRenderer.draw(msg, // string
(int)textPosX, // x
(int)textPosY); // y
textRenderer.endRendering(); // finish rendering
}
}
| true |
108ae81fd78c047443860ede1d3bc64c2dc29a64 | Java | ax003d/YiBo | /YiBo/src/com/shejiaomao/weibo/service/listener/EditMicroBlogEmotionClickListener.java | UTF-8 | 1,606 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package com.shejiaomao.weibo.service.listener;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import com.shejiaomao.weibo.service.adapter.EmotionsGridAdapter;
import com.shejiaomao.weibo.widget.EmotionViewController;
public class EditMicroBlogEmotionClickListener implements OnClickListener {
private Context context;
private EmotionViewController emotionViewController;
public EditMicroBlogEmotionClickListener(Context context) {
this.context = context;
emotionViewController = new EmotionViewController((Activity)context);
EmotionsGridAdapter emotionsGridAdapter = new EmotionsGridAdapter(context);
emotionViewController.setEmotionGridViewAdapter(emotionsGridAdapter);
EditMicroBlogEmotionItemClickListener itemClickListener =
new EditMicroBlogEmotionItemClickListener(context);
emotionViewController.setEmotionGridViewOnItemClickListener(itemClickListener);
}
@Override
public void onClick(View v) {
if (emotionViewController.getEmotionViewVisibility() == View.VISIBLE) {
emotionViewController.hideEmotionView();
} else {
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
((Activity) context).getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
emotionViewController.showEmotionView();
}
}
}
| true |
29cc4a409cc58f30b0163cb1066984b308d5b1b5 | Java | Alleinx/CUMCM | /CUMCM2018_B/case2_error/Controller.java | UTF-8 | 760 | 2.65625 | 3 | [] | no_license |
public class Controller {
public int getSystemRunningTime() {
return systemRunningTime;
}
public void addSystemRunningTime(int time) {
systemRunningTime += time;
}
/* operationTime means the minimum cost value */
public boolean couldRun(int operationTime) {
return (TIMELIMIT - systemRunningTime) >= operationTime;
}
public static Controller getInstance() {
return HolderClass.instance;
}
public void start() {
rgv.running();
}
private Controller() {
this.rgv = RGV.getInstance();
this.rgv.setController(this);
}
public static class HolderClass {
private final static Controller instance = new Controller();
}
private RGV rgv;
private final int TIMELIMIT = 60 * 60 * 8;
private int systemRunningTime = 0;
}
| true |
b076007f6ff828812f94bbb962d9dd27f851c149 | Java | SourceFramework/J2EE_B2C | /J2EE_B2C/J2EE_B2C_project/taotao-rest/src/main/java/com/taotao/rest/service/ItemCatService.java | UTF-8 | 329 | 1.757813 | 2 | [] | no_license | package com.taotao.rest.service;
import com.taotao.rest.pojo.CategoryResult;
/**
* 商品分类模块业务层
* @author mbc1996
*
*/
public interface ItemCatService {
/**
* 返回商品的所有分类信息,实现前台商品分类显示功能
* @return 自定义pojo
*/
public CategoryResult getItemCatList();
}
| true |
d0dd90b46d13eb175ec0cc3aeef9c354580f6264 | Java | nopenigita/huajuan-mybatis | /activiti01/src/test/java/com/itheima/test/ActivitiTest.java | UTF-8 | 770 | 2.328125 | 2 | [] | no_license | package com.itheima.test;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.junit.Test;
/**
* @author : Hiccup
* create at : 2020/9/16 8:52 下午
* description :
* remark : 测试Activiti所需要的25张表的生成
**/
public class ActivitiTest {
@Test
public void testGenTable() {
// 创建ProcessEngineConfiguration对象
ProcessEngineConfiguration configuration = ProcessEngineConfiguration.
createProcessEngineConfigurationFromResource("activiti.cfg.xml");
// 创建ProcessEngine对象
ProcessEngine processEngine = configuration.buildProcessEngine();
// 输出processEngine对象
System.out.println(processEngine);
}
}
| true |
3c2c3b974071b5920860f415eeab723dfaaac4b4 | Java | pskorupinski/JavaStreamMineOperatorPlacer | /source/org/microcloud/manager/core/placer/placement/Full/steps/PlacementStepOne.java | UTF-8 | 6,869 | 2.078125 | 2 | [] | no_license | package org.microcloud.manager.core.placer.placement.Full.steps;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.microcloud.manager.core.model.clientquery.ClientQuery;
import org.microcloud.manager.core.model.datacenter.Host;
import org.microcloud.manager.core.model.datasourcedef.DataSourceKeysDistribution;
import org.microcloud.manager.core.model.datasourcedef.DataSourceType;
import org.microcloud.manager.core.model.key.Key;
import org.microcloud.manager.core.model.workeralgorithm.WorkerAlgorithm;
import org.microcloud.manager.core.model.workeralgorithm.WorkerAlgorithmProfileNode;
import org.microcloud.manager.manager.core.model.datacenter.DataCenter;
import org.microcloud.manager.manager.core.model.solution.SolutionConnection;
import org.microcloud.manager.manager.core.model.solution.SolutionGraph;
import org.microcloud.manager.manager.core.model.solution.SolutionSource;
import org.microcloud.manager.manager.core.model.solution.destination.GeneralSolutionDestination;
import org.microcloud.manager.persistence.EntityLoader;
import org.microcloud.manager.structures.UniqueBiMapping;
public class PlacementStepOne implements PlacementStep {
Set<DataSourceKeysDistribution> keysHostsMapsSet;
ClientQuery clientQuery;
public PlacementStepOne(Set<DataSourceKeysDistribution> keysHostsMapsSet, ClientQuery clientQuery) {
this.keysHostsMapsSet = keysHostsMapsSet;
this.clientQuery = clientQuery;
}
////////////////////////////////////////////
////PUBLIC METHODS
////////////////////////////////////////////
@Override
public void run() {
SolutionGraph solutionGraph;
/*
* 1. Prepare the full graph based on data received in Set<DataSourceKeysDistribution>.
* It will contain all possible SolutionSources, SolutionConnections, SolutionDestinations
*/
solutionGraph = runPart1();
/*
* 2. Analyze client query to get max time.
* This will include a size of all the data per data source type.
*
* Scenarios:
* I. historical + time given:
* -> tmax - given by user
* -> worker slices - counted from tmax & data size
* II. historical + price given:
* -> worker slices - data sizes & guessed few times
* -> tmax - counted from worker slices no.
* III. real-time:
* -> tmax - time of execution of real-time
* -> worker slices - counted from tmax & data size (to process data real-time)
* IV. hybrid:
* -> tmax - bounded by real-time execution
* -> worker slices - counted from tmax & data size + those needed to process real-time
* */
runPart2();
/*
* 3. Copy a graph and delete in a new version those nodes (and their connections)
* which will not be available during the time needed.
*/
/*
* 4. Count PRICEi, PRICEj, PRICEi->j, PRICEij, ROUTE_COST c, capacity C
*/
/*
* 5. Present the data as an input do simplex algorighm, run it.
*/
/*
* 6. In some cases, rerun algorithm
*/
}
@Override
public Object getOutcome() {
// TODO Auto-generated method stub
return null;
}
////////////////////////////////////////////
////PRIVATE METHODS
////////////////////////////////////////////
private SolutionGraph runPart1() {
// solution sources list
List<SolutionSource> solutionSources = new ArrayList<>();
for( DataSourceKeysDistribution distr : keysHostsMapsSet ) {
UniqueBiMapping<Host, Key> keysHostsMap = distr.getHostKeysMapping();
int numberCols = keysHostsMap.getColumnsNumber();
for(int i=0; i<numberCols; i++) {
Set<Host> hostsForKey = keysHostsMap.getRowsOfColIndex(i);
Key key = keysHostsMap.getColumn(i);
for(Host host : hostsForKey) {
SolutionSource solutionSource = new SolutionSource(host, key);
solutionSources.add(solutionSource);
}
}
}
// solution destinations list
List<GeneralSolutionDestination> solutionDestinations = new ArrayList<>();
@SuppressWarnings("unchecked")
List<DataCenter> dataCentersList = EntityLoader.getInstance().getDataCenters();
for(DataCenter dc : dataCentersList) {
GeneralSolutionDestination sd = new GeneralSolutionDestination(dc);
solutionDestinations.add(sd);
}
// solution connections list
List<SolutionConnection> solutionConnections = new ArrayList<>();
for(SolutionSource ss : solutionSources) {
for(GeneralSolutionDestination sd : solutionDestinations) {
SolutionConnection sc = new SolutionConnection(ss, sd);
solutionConnections.add(sc);
}
}
return new SolutionGraph(solutionSources, solutionDestinations, solutionConnections);
}
private void runPart2() {
int aproxTime;
int workeropSlicesProp;
/*
* 2.1 Decide on which kind of scenario do we have
*/
/* 2.1.1 Check whether are historical and/or real-time */
boolean historical = false;
boolean realtime = false;
for(DataSourceKeysDistribution dskd : keysHostsMapsSet) {
DataSourceType dst = dskd.getDataSource().getDataSourceDefinition().getDataSourceTech().getDataSourceType();
if(dst == DataSourceType.HISTORICAL) {
historical = true;
}
else if(dst == DataSourceType.REAL_TIME) {
realtime = true;
}
}
/* 2.1.2 Check what is defined in client query */
boolean priceNotTime = false;
if(clientQuery.getPrice() != null)
priceNotTime = true;
/*
* 2.2 MB/s of data retrieved from sources
*/
int retrievedPerSecond = 0;
for(DataSourceKeysDistribution dskd : keysHostsMapsSet) {
retrievedPerSecond += dskd.getRetrievalSizePerSecond();
}
/*
* 2.3 Worker algorithm
*/
WorkerAlgorithm workerAlgorithm = EntityLoader.getInstance().getWorkerAlgorithm(clientQuery.getWorkerAlgorighmType());
Set<WorkerAlgorithmProfileNode> workerProfileSet = workerAlgorithm.getWorkerAlgorithmProfileNodes();
List<WorkerAlgorithmProfileNode> workerProfileList = new ArrayList<>(workerProfileSet);
java.util.Collections.sort(workerProfileList);
WorkerAlgorithmProfileNode n0 = null;
for(WorkerAlgorithmProfileNode wapn : workerProfileList) {
// TODO some parameter so that we set that velocity of workerops will be surely enough
if( wapn.getVelocity() > retrievedPerSecond /* * costam */ ) {
n0 = wapn;
}
}
if( n0 == null )
n0 = workerProfileList.get(workerProfileList.size()-1);
/*
* 2.4 Various scenarios
*/
/* 2.4.1 historical + time given */
if ( historical && !realtime && !priceNotTime ) {
}
/* 2.4.2 historical + price given */
else if ( historical && !realtime && priceNotTime ) {
}
/* 2.4.3 realtime */
else if ( !historical && realtime ) {
aproxTime = clientQuery.getTime();
workeropSlicesProp = n0.getSlicesNo();
}
/* 2.4.4 hybrid */
else if ( historical && realtime ) {
}
}
}
| true |
4b4de15937dc5be5f9c4c903eeeec2bc2dc3ea73 | Java | canvaser/App | /app/src/main/java/com/summer/app/ui/info/workdetail/fragment/WorkDetailsFrag.java | UTF-8 | 1,611 | 1.796875 | 2 | [] | no_license | package com.summer.app.ui.info.workdetail.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import com.summer.app.R;
import com.summer.app.ui.info.workdetail.ope.WorkDetailsDAOpe;
import com.summer.lib.constant.ValueConstant;
import com.summer.lib.base.ui.fragment.BaseNurseFrag;
import com.summer.lib.base.ui.ope.BaseNurseOpes;
import com.summer.app.ui.info.workdetail.bean.adpterbean.WorkDetailAdapterBean;
import com.summer.app.ui.info.workdetail.ope.WorkDetailsUIOpe;
/**
* Created by ${viwmox} on 2016-12-08.
*/
public class WorkDetailsFrag extends BaseNurseFrag {
WorkDetailsUIOpe workDetailsUIOpe;
WorkDetailsDAOpe workDetailsDAOpe;
@Override
public BaseNurseOpes getOpe() {
return null;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() == null || getArguments().getSerializable(ValueConstant.DATA_DATA) == null) {
return;
}
workDetailsUIOpe = new WorkDetailsUIOpe(activity, getView());
workDetailsDAOpe = new WorkDetailsDAOpe(activity);
workDetailsDAOpe.setWorkDetailAdapterBean((WorkDetailAdapterBean) getArguments().getSerializable(ValueConstant.DATA_DATA));
workDetailsUIOpe.initMid(workDetailsDAOpe.getWorkDetailAdapterBean().getDate());
workDetailsUIOpe.initList(workDetailsDAOpe.getWorkDetailAdapterBean());
}
@Override
public int getContainView() {
return R.layout.frag_workdetails;
}
}
| true |
2d51914d81d9c192a8fa6e39be0057f4d2b11ab2 | Java | 1136200149/Geek | /src/main/java/com/geek/utils/ErrorMessageModel.java | UTF-8 | 448 | 2.421875 | 2 | [] | no_license | package com.geek.utils;
public class ErrorMessageModel {
private String field;
private String msg;
public ErrorMessageModel() {
}
public ErrorMessageModel(String field, String msg) {
this.field = field;
this.msg = msg;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| true |
6ed1c6ca83134f92c0a6938855ed3ba4ede80210 | Java | sherkergavin/test20171206 | /inas-all-webapp/src/main/java/com/inas/web/smcontroller/MessageTemplateController.java | UTF-8 | 2,619 | 2.046875 | 2 | [] | no_license | package com.inas.web.smcontroller;
import com.inas.model.Tree;
import com.inas.model.system.MessageTemplate;
import com.inas.service.system.MessageTemplateService;
import com.inas.util.JSONUtil;
import com.inas.util.TreeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zs on 2016/1/27.
*/
@Controller
@RequestMapping("/msgTemplate")
public class MessageTemplateController {
@Resource(name="messageTemplateService")
private MessageTemplateService messageTemplateService;
@RequestMapping(value = "/queryMsgTemplateTree", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String queryMsgTemplateTree(HttpServletRequest request){
List<MessageTemplate> list=messageTemplateService.queryTmeplateByEn(null);
List<Tree> listTree=new ArrayList<Tree>();
for (MessageTemplate tmp:list){
Tree tree=new Tree();
tree.setId(tmp.getId());
tree.setText(tmp.getTitle());
tree.setLo(tmp.getLo());
listTree.add(tree);
}
String s = JSONUtil.toExtResultTreeJson(TreeUtil.getExtTreeRoot(listTree, true));
return s;
}
@RequestMapping(value = "/queryTemplateByEn", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String queryTemplateByEn(HttpServletRequest request,MessageTemplate messageTemplate){
List<MessageTemplate> list=messageTemplateService.queryTmeplateByEn(messageTemplate);
return JSONUtil.toExtFormJson(true,null,list);
}
@RequestMapping(value = "/addTemplate", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String addTemplate(HttpServletRequest request,MessageTemplate messageTemplate){
messageTemplateService.addTemplate(messageTemplate);
return JSONUtil.toExtFormJson(true,null);
}
@RequestMapping(value = "/updateTemplate", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String updateTemplate(HttpServletRequest request,MessageTemplate messageTemplate){
messageTemplateService.updateTemplate(messageTemplate);
return JSONUtil.toExtFormJson(true,null);
}
}
| true |
5a359ac460742cb21420cda34b7d3c3c37096675 | Java | kwu78/Ontobuilder-Research-Environment | /src/main/java/ac/technion/schemamatching/experiments/pairwise/SSEnsembleExperiment.java | UTF-8 | 12,716 | 2.140625 | 2 | [] | no_license | package ac.technion.schemamatching.experiments.pairwise;
import java.util.ArrayList;
import java.util.Properties;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import ac.technion.iem.ontobuilder.matching.match.MatchInformation;
import ac.technion.schemamatching.experiments.OBExperimentRunner;
import ac.technion.schemamatching.matchers.firstline.FirstLineMatcher;
import ac.technion.schemamatching.matchers.secondline.SecondLineMatcher;
import ac.technion.iem.ontobuilder.core.ontology.Term;
import ac.technion.schemamatching.statistics.BinaryGolden;
import ac.technion.schemamatching.statistics.K2Statistic;
import ac.technion.schemamatching.statistics.MatchDistance;
import ac.technion.schemamatching.statistics.NBGolden;
import ac.technion.schemamatching.statistics.NBGoldenAtDynamicK;
import ac.technion.schemamatching.statistics.NBGoldenAtK;
import ac.technion.schemamatching.statistics.NBGoldenAtR;
import ac.technion.schemamatching.statistics.Statistic;
import ac.technion.schemamatching.testbed.ExperimentSchemaPair;
import ac.technion.schemamatching.statistics.predictors.MatrixPredictors;
/**
* This match experiment is a session of a evaluations fused into a single evaluation.
* The experiment matches a given schema pair using specific 1LM and 2LM given by arguments.
* Returns precision and recall.
* @author Shachaf Lemberger & Shay Shusterman
*
*/
public class SSEnsembleExperiment implements PairWiseExperiment {
private ArrayList<MatchInformation> miflMl;
private ArrayList<MatchInformation> mislMl;
private ArrayList<FirstLineMatcher> flM;
private ArrayList<SecondLineMatcher> slM;
private Properties properties;
private boolean isMemory;
private String method;
public static final String ExpName = "SSEnsemble";
/*
* @param ExperimentSchemaPair esp - the tested Schema Pair
* @return ArrayList<Statistic> evaluations - Holds all the evaluations concluded by the Experiment
* @see ac.technion.schemamatching.experiments.MatchingExperiment#runExperiment(ac.technion.schemamatching.experiments.ExperimentSchemaPair)
*/
public ArrayList<Statistic> runExperiment(ExperimentSchemaPair esp) {
// Using all 1st line matchers
ArrayList<Statistic> evaluations = new ArrayList<Statistic>();
for (FirstLineMatcher m : flM)
{
MatchInformation mi = null;
mi = esp.getSimilarityMatrix(m, false);
// Saving Match Information for each 1st line matcher
miflMl.add(mi);
//Using all 2nd line matchers
for (SecondLineMatcher s : slM)
{
if (properties == null || !s.init(properties))
System.err.println("Initialization of " + s.getName() +
"failed, we hope the author defined default values...");
double startTime = System.currentTimeMillis();
MatchInformation mi1 = s.match(mi);
double endTime = System.currentTimeMillis();
System.out.println(s.getName() + " Runtime: " + (endTime - startTime));
evaluations = this.calculateSlmStatistics(evaluations, mi1, esp, m.getName(), s.getName(), s.getConfig());
//Saving Match Information for each 2nd line matcher
mislMl.add(mi1);
}
}
// Fusing Match Information
MatchInformation fusedMi = this.fuseMatchInformationObjArray(miflMl, esp, this.method);
// Calculating all results for 2nd line matchers for the fused matrix
for (SecondLineMatcher s : slM)
{
if (properties == null || !s.init(properties))
System.err.println("Initialization of " + s.getName() +
"failed, we hope the author defined default values...");
double startTime = System.currentTimeMillis();
MatchInformation mi1 = s.match(fusedMi);
double endTime = System.currentTimeMillis();
System.out.println(s.getName() + " Runtime: " + (endTime - startTime));
evaluations = this.calculateSlmStatistics(evaluations, mi1, esp, ExpName, s.getName(), s.getConfig());
// Saving Match Information of the fused mi for each 2nd line matcher.
mislMl.add(fusedMi);
}
return evaluations;
}
/*
* @desc This function takes all the Match Information for each FlM and creates a new matrix that holds the re-evaluated confidence estimation between two terms
* @param ArrayList<MatchInformation> FlmMiArray - Array that holds all Match Information for each FlM
* @param ExperimentSchemaPair esp - The tested Schema Pair
* @param String method - Argument for method of fusion, defined @properties file
* @return MatchInformation fusedMi - The new fused matrix
*/
public MatchInformation fuseMatchInformationObjArray(ArrayList<MatchInformation> FlmMiArray, ExperimentSchemaPair esp, String method)
{
// Create MatchInformation obj from the given schema pair
MatchInformation fusedMi = new MatchInformation(esp.getCandidateOntology(), esp.getTargetOntology());
for (Term candidateTerm : esp.getCandidateOntology().getTerms(true))
{
for (Term targetTerm : esp.getTargetOntology().getTerms(true))
{
fusedMi.getMatrix().setMatchConfidence(candidateTerm, targetTerm, 0.0);
}
}
if (method.equals("Predictors_Ensenble"))
{
// Calculate the sum of all predicator evaluations for all FlM
double sumWightedPred = 0.0;
for (MatchInformation currentMi : FlmMiArray)
{
Statistic mv = new MatrixPredictors();
mv.init(ExpName, currentMi);
List<String[]> temp = mv.getData();
String[] h = temp.get(0);
int numPredictors = h.length -1;
double weightedMatrixPrediction = 0.0;
for (int i = 0; i < numPredictors; i++)
{
double p = Double.parseDouble(mv.getData().get(0)[i]);
weightedMatrixPrediction += p;
}
sumWightedPred += weightedMatrixPrediction;
}
// Calculate the fused similarity matrix from the similarity cube
for (MatchInformation currentMi : FlmMiArray)
{
Statistic mv1 = new MatrixPredictors();
mv1.init(ExpName, currentMi);
List<String[]> temp = mv1.getData();
String[] h = temp.get(0);
int numPredictors = h.length -1;
double currentPred = 0.0;
// Calculate current matrix predicator evaluation for current FlM
for (int i = 0; i < numPredictors; i++)
{
double p = Double.parseDouble(mv1.getData().get(0)[i]);
currentPred += p;
}
// Calculate the relative weight of current MatchInformation Matrix
double weight = currentPred / sumWightedPred;
for (Term candidateTerm : esp.getCandidateOntology().getTerms(true))
{
for (Term targetTerm : esp.getTargetOntology().getTerms(true))
{
double tempValue = (double)currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm);
double fusedValue = (double)fusedMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm);
fusedMi.getMatrix().setMatchConfidence(candidateTerm, targetTerm, (tempValue*weight) + fusedValue);
}
}
}
}
if (method.equals("SS"))
{
// Calculate confidence score for each MatchInformation matrix
double sumConfidence = 0.0;
for (MatchInformation currentMi : FlmMiArray)
{
sumConfidence += this.calcMinMaxInterval(currentMi, esp);
}
// Calculate the fused similarity matrix from the similarity cube
for (MatchInformation currentMi : FlmMiArray)
{
double currentConfidence = this.calcMinMaxInterval(currentMi, esp);
double weight = currentConfidence / sumConfidence;
for (Term candidateTerm : esp.getCandidateOntology().getTerms(true))
{
for (Term targetTerm : esp.getTargetOntology().getTerms(true))
{
double tempValue = (double)currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm);
double fusedValue = (double)fusedMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm);
fusedMi.getMatrix().setMatchConfidence(candidateTerm, targetTerm, (tempValue)*weight + fusedValue);
}
}
}
}
return fusedMi;
}
/*
* @desc Initializer
* @param OBExperimentRunner oer - Experiment Name
* @param Properties properties - Properties file name
* @param ArrayList<FirstLineMatcher> flM - Array list that holds all FlM identifiers for current experiment
* @param ArrayList<SecondLineMatcher> slM - Array list that holds all SlM identifiers for current experiment
* @param boolean isMemory - Not used, inherited
* @return Boolean - True - indicating success
*/
public boolean init(OBExperimentRunner oer, Properties properties, ArrayList<FirstLineMatcher> flM, ArrayList<SecondLineMatcher> slM ,boolean isMemory)
{
this.miflMl = new ArrayList<MatchInformation>();
this.mislMl = new ArrayList<MatchInformation>();
this.flM = flM;
this.slM = slM;
this.isMemory = isMemory;
//using property files allows to modify experiment parameters at runtime
this.properties = new Properties();
this.properties = properties;
for (Object key : properties.keySet())
{
if (key.equals("method"))
{
this.method = properties.getProperty((String)key);
}
}
return true;
}
/*
* @dexc Inherited
* @see ac.technion.schemamatching.experiments.MatchingExperiment#getDescription()
*/
public String getDescription()
{
return "SSEnsemble experiment";
}
/*
* @desc Inherited
*/
public ArrayList<Statistic> summaryStatistics()
{
//unused
return null;
}
/*
* @desc Function calculates the Non Binary statistics necessary for evaluation of FlM
* @param ArrayList<Statistic> evaluations - Hold all evaluations estimated in current run
* @param MatchInformation mi - Holds currently tested MatchInformation
* @param ExperimentSchemaPair esp - The tested Schema Pair
* @param String mName - Matcher Name
* @return ArrayList<Statistic> evaluations - Holds all the evaluations concluded by the Experiment
*/
public ArrayList<Statistic> calculateFlmStatistics(ArrayList<Statistic> evaluations, MatchInformation mi, ExperimentSchemaPair esp, String mName) {
//Calculate Non-Binary Precision and Recall
K2Statistic nb = new NBGolden();
String instanceDesc = esp.getID() + "," + mName;
nb.init(instanceDesc, mi,esp.getExact());
evaluations.add(nb);
//Calculate Non-Binary Precision and Recall @ K
K2Statistic nbk = new NBGoldenAtK();
nbk.init(instanceDesc, mi,esp.getExact());
evaluations.add(nbk);
//Calculate Non-Binary Precision and Recall @ KA
K2Statistic nbka = new NBGoldenAtDynamicK();
nbka.init(instanceDesc, mi,esp.getExact());
evaluations.add(nbka);
//Calculate Non-Binary Precision @ R
K2Statistic nbr = new NBGoldenAtR();
nbr.init(instanceDesc, mi,esp.getExact());
evaluations.add(nbr);
//Calculate MatchDisatance
K2Statistic md = new MatchDistance();
md.init(instanceDesc, mi,esp.getExact());
evaluations.add(md);
return evaluations;
}
/*
* @desc Function calculates the Binary Golden statistics necessary for evaluation of SlM
* @param ArrayList<Statistic> evaluations - Hold all evaluations estimated in current run
* @param MatchInformation mi - Holds currently tested MatchInformation
* @param ExperimentSchemaPair esp - The tested Schema Pair
* @param String mName - Matcher Name
* @return ArrayList<Statistic> evaluations - Holds all the evaluations concluded by the Experiment
*/
public ArrayList<Statistic> calculateSlmStatistics(ArrayList<Statistic> evaluations, MatchInformation mi1, ExperimentSchemaPair esp, String mName, String sName, String sConfigName) {
//calculate Precision and Recall
K2Statistic b2 = new BinaryGolden();
String instanceDesc = esp.getID() + "," + mName + "," + sName+ "," + sConfigName;
b2.init(instanceDesc, mi1,esp.getExact());
evaluations.add(b2);
return evaluations;
}
/*
* @desc Function calculates the difference between minimum and maximum values in table
* @param MatchInformation currentMi - Holds currently tested MatchInformation
* @param ExperimentSchemaPair esp - The tested Schema Pair
* @return double - difference between minimum and maximum values in table
*/
public double calcMinMaxInterval(MatchInformation currentMi, ExperimentSchemaPair esp)
{
double minValue = 2.0;
double maxValue = -1.0;
for (Term candidateTerm : esp.getCandidateOntology().getTerms(true)){
for (Term targetTerm : esp.getTargetOntology().getTerms(true)){
if (currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm) > maxValue)
{
maxValue = currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm);
}
if (currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm) < minValue && currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm) != 0)
{
minValue = currentMi.getMatrix().getMatchConfidence(candidateTerm, targetTerm);
}
}
}
return maxValue - minValue;
}
} | true |
7d5d91d37980abf47052c7cef1bc2e2c2e1c6bce | Java | myxland/wms-cloud | /wms-saas/src/main/java/com/zlsrj/wms/saas/rest/TenantCustomerLinkmanRestController.java | UTF-8 | 12,298 | 1.96875 | 2 | [] | no_license | package com.zlsrj.wms.saas.rest;
import java.util.Date;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlsrj.wms.api.dto.TenantCustomerLinkmanQueryParam;
import com.zlsrj.wms.api.entity.TenantInfo;
import com.zlsrj.wms.api.entity.TenantCustomerLinkman;
import com.zlsrj.wms.api.vo.TenantCustomerLinkmanVo;
import com.zlsrj.wms.common.api.CommonResult;
import com.zlsrj.wms.saas.service.IIdService;
import com.zlsrj.wms.saas.service.ITenantInfoService;
import com.zlsrj.wms.saas.service.ITenantCustomerLinkmanService;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@Api(value = "用户联系人", tags = { "用户联系人操作接口" })
@RestController
@Slf4j
public class TenantCustomerLinkmanRestController {
@Autowired
private ITenantCustomerLinkmanService tenantCustomerLinkmanService;
@Autowired
private ITenantInfoService tenantInfoService;
@Autowired
private IIdService idService;
@ApiOperation(value = "根据ID查询用户联系人")
@RequestMapping(value = "/tenant-customer-linkmans/{id}", method = RequestMethod.GET)
public TenantCustomerLinkmanVo getById(@PathVariable("id") Long id) {
TenantCustomerLinkman tenantCustomerLinkman = tenantCustomerLinkmanService.getById(id);
return entity2vo(tenantCustomerLinkman);
}
@ApiOperation(value = "根据参数查询用户联系人列表")
@RequestMapping(value = "/tenant-customer-linkmans", method = RequestMethod.GET)
public Page<TenantCustomerLinkmanVo> page(@RequestBody TenantCustomerLinkmanQueryParam tenantCustomerLinkmanQueryParam,
@RequestParam(value = "page", defaultValue = "1") int page, //
@RequestParam(value = "rows", defaultValue = "10") int rows, //
@RequestParam(value = "sort") String sort, // 排序列字段名
@RequestParam(value = "order") String order // 可以是 'asc' 或者 'desc',默认值是 'asc'
) {
IPage<TenantCustomerLinkman> pageTenantCustomerLinkman = new Page<TenantCustomerLinkman>(page, rows);
QueryWrapper<TenantCustomerLinkman> queryWrapperTenantCustomerLinkman = new QueryWrapper<TenantCustomerLinkman>();
queryWrapperTenantCustomerLinkman.orderBy(StringUtils.isNotEmpty(sort), "asc".equals(order), sort);
queryWrapperTenantCustomerLinkman.lambda()
.eq(tenantCustomerLinkmanQueryParam.getId() != null, TenantCustomerLinkman::getId, tenantCustomerLinkmanQueryParam.getId())
.eq(tenantCustomerLinkmanQueryParam.getTenantId() != null, TenantCustomerLinkman::getTenantId, tenantCustomerLinkmanQueryParam.getTenantId())
.eq(tenantCustomerLinkmanQueryParam.getCustomerId() != null, TenantCustomerLinkman::getCustomerId, tenantCustomerLinkmanQueryParam.getCustomerId())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanName() != null, TenantCustomerLinkman::getLinkmanName, tenantCustomerLinkmanQueryParam.getLinkmanName())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanAddress() != null, TenantCustomerLinkman::getLinkmanAddress, tenantCustomerLinkmanQueryParam.getLinkmanAddress())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanMainOn() != null, TenantCustomerLinkman::getLinkmanMainOn, tenantCustomerLinkmanQueryParam.getLinkmanMainOn())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanSex() != null, TenantCustomerLinkman::getLinkmanSex, tenantCustomerLinkmanQueryParam.getLinkmanSex())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanBirthday() != null, TenantCustomerLinkman::getLinkmanBirthday, tenantCustomerLinkmanQueryParam.getLinkmanBirthday())
.ge(tenantCustomerLinkmanQueryParam.getLinkmanBirthdayStart() != null, TenantCustomerLinkman::getLinkmanBirthday,tenantCustomerLinkmanQueryParam.getLinkmanBirthdayStart() == null ? null: DateUtil.beginOfDay(tenantCustomerLinkmanQueryParam.getLinkmanBirthdayStart()))
.le(tenantCustomerLinkmanQueryParam.getLinkmanBirthdayEnd() != null, TenantCustomerLinkman::getLinkmanBirthday,tenantCustomerLinkmanQueryParam.getLinkmanBirthdayEnd() == null ? null: DateUtil.endOfDay(tenantCustomerLinkmanQueryParam.getLinkmanBirthdayEnd()))
.eq(tenantCustomerLinkmanQueryParam.getLinkmanMobile() != null, TenantCustomerLinkman::getLinkmanMobile, tenantCustomerLinkmanQueryParam.getLinkmanMobile())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanTel() != null, TenantCustomerLinkman::getLinkmanTel, tenantCustomerLinkmanQueryParam.getLinkmanTel())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanEmail() != null, TenantCustomerLinkman::getLinkmanEmail, tenantCustomerLinkmanQueryParam.getLinkmanEmail())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanPersonalWx() != null, TenantCustomerLinkman::getLinkmanPersonalWx, tenantCustomerLinkmanQueryParam.getLinkmanPersonalWx())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanQq() != null, TenantCustomerLinkman::getLinkmanQq, tenantCustomerLinkmanQueryParam.getLinkmanQq())
.eq(tenantCustomerLinkmanQueryParam.getLinkmanRemark() != null, TenantCustomerLinkman::getLinkmanRemark, tenantCustomerLinkmanQueryParam.getLinkmanRemark())
;
IPage<TenantCustomerLinkman> tenantCustomerLinkmanPage = tenantCustomerLinkmanService.page(pageTenantCustomerLinkman, queryWrapperTenantCustomerLinkman);
Page<TenantCustomerLinkmanVo> tenantCustomerLinkmanVoPage = new Page<TenantCustomerLinkmanVo>(page, rows);
tenantCustomerLinkmanVoPage.setCurrent(tenantCustomerLinkmanPage.getCurrent());
tenantCustomerLinkmanVoPage.setPages(tenantCustomerLinkmanPage.getPages());
tenantCustomerLinkmanVoPage.setSize(tenantCustomerLinkmanPage.getSize());
tenantCustomerLinkmanVoPage.setTotal(tenantCustomerLinkmanPage.getTotal());
tenantCustomerLinkmanVoPage.setRecords(tenantCustomerLinkmanPage.getRecords().stream()//
.map(e -> entity2vo(e))//
.collect(Collectors.toList()));
return tenantCustomerLinkmanVoPage;
}
@ApiOperation(value = "新增用户联系人")
@RequestMapping(value = "/tenant-customer-linkmans", method = RequestMethod.POST)
public TenantCustomerLinkmanVo save(@RequestBody TenantCustomerLinkman tenantCustomerLinkman) {
if (tenantCustomerLinkman.getId() == null || tenantCustomerLinkman.getId().compareTo(0L) <= 0) {
tenantCustomerLinkman.setId(idService.selectId());
}
boolean success = tenantCustomerLinkmanService.save(tenantCustomerLinkman);
if (success) {
TenantCustomerLinkman tenantCustomerLinkmanDatabase = tenantCustomerLinkmanService.getById(tenantCustomerLinkman.getId());
return entity2vo(tenantCustomerLinkmanDatabase);
}
log.info("save TenantCustomerLinkman fail,{}", ToStringBuilder.reflectionToString(tenantCustomerLinkman, ToStringStyle.JSON_STYLE));
return null;
}
@ApiOperation(value = "更新用户联系人全部信息")
@RequestMapping(value = "/tenant-customer-linkmans/{id}", method = RequestMethod.PUT)
public TenantCustomerLinkmanVo updateById(@PathVariable("id") Long id, @RequestBody TenantCustomerLinkman tenantCustomerLinkman) {
tenantCustomerLinkman.setId(id);
boolean success = tenantCustomerLinkmanService.updateById(tenantCustomerLinkman);
if (success) {
TenantCustomerLinkman tenantCustomerLinkmanDatabase = tenantCustomerLinkmanService.getById(id);
return entity2vo(tenantCustomerLinkmanDatabase);
}
log.info("update TenantCustomerLinkman fail,{}", ToStringBuilder.reflectionToString(tenantCustomerLinkman, ToStringStyle.JSON_STYLE));
return null;
}
@ApiOperation(value = "根据参数更新用户联系人信息")
@RequestMapping(value = "/tenant-customer-linkmans/{id}", method = RequestMethod.PATCH)
public TenantCustomerLinkmanVo updatePatchById(@PathVariable("id") Long id, @RequestBody TenantCustomerLinkman tenantCustomerLinkman) {
TenantCustomerLinkman tenantCustomerLinkmanWhere = TenantCustomerLinkman.builder()//
.id(id)//
.build();
UpdateWrapper<TenantCustomerLinkman> updateWrapperTenantCustomerLinkman = new UpdateWrapper<TenantCustomerLinkman>();
updateWrapperTenantCustomerLinkman.setEntity(tenantCustomerLinkmanWhere);
updateWrapperTenantCustomerLinkman.lambda()//
//.eq(TenantCustomerLinkman::getId, id)
// .set(tenantCustomerLinkman.getId() != null, TenantCustomerLinkman::getId, tenantCustomerLinkman.getId())
.set(tenantCustomerLinkman.getTenantId() != null, TenantCustomerLinkman::getTenantId, tenantCustomerLinkman.getTenantId())
.set(tenantCustomerLinkman.getCustomerId() != null, TenantCustomerLinkman::getCustomerId, tenantCustomerLinkman.getCustomerId())
.set(tenantCustomerLinkman.getLinkmanName() != null, TenantCustomerLinkman::getLinkmanName, tenantCustomerLinkman.getLinkmanName())
.set(tenantCustomerLinkman.getLinkmanAddress() != null, TenantCustomerLinkman::getLinkmanAddress, tenantCustomerLinkman.getLinkmanAddress())
.set(tenantCustomerLinkman.getLinkmanMainOn() != null, TenantCustomerLinkman::getLinkmanMainOn, tenantCustomerLinkman.getLinkmanMainOn())
.set(tenantCustomerLinkman.getLinkmanSex() != null, TenantCustomerLinkman::getLinkmanSex, tenantCustomerLinkman.getLinkmanSex())
.set(tenantCustomerLinkman.getLinkmanBirthday() != null, TenantCustomerLinkman::getLinkmanBirthday, tenantCustomerLinkman.getLinkmanBirthday())
.set(tenantCustomerLinkman.getLinkmanMobile() != null, TenantCustomerLinkman::getLinkmanMobile, tenantCustomerLinkman.getLinkmanMobile())
.set(tenantCustomerLinkman.getLinkmanTel() != null, TenantCustomerLinkman::getLinkmanTel, tenantCustomerLinkman.getLinkmanTel())
.set(tenantCustomerLinkman.getLinkmanEmail() != null, TenantCustomerLinkman::getLinkmanEmail, tenantCustomerLinkman.getLinkmanEmail())
.set(tenantCustomerLinkman.getLinkmanPersonalWx() != null, TenantCustomerLinkman::getLinkmanPersonalWx, tenantCustomerLinkman.getLinkmanPersonalWx())
.set(tenantCustomerLinkman.getLinkmanQq() != null, TenantCustomerLinkman::getLinkmanQq, tenantCustomerLinkman.getLinkmanQq())
.set(tenantCustomerLinkman.getLinkmanRemark() != null, TenantCustomerLinkman::getLinkmanRemark, tenantCustomerLinkman.getLinkmanRemark())
;
boolean success = tenantCustomerLinkmanService.update(updateWrapperTenantCustomerLinkman);
if (success) {
TenantCustomerLinkman tenantCustomerLinkmanDatabase = tenantCustomerLinkmanService.getById(id);
return entity2vo(tenantCustomerLinkmanDatabase);
}
log.info("partial update TenantCustomerLinkman fail,{}",
ToStringBuilder.reflectionToString(tenantCustomerLinkman, ToStringStyle.JSON_STYLE));
return null;
}
@ApiOperation(value = "根据ID删除用户联系人")
@RequestMapping(value = "/tenant-customer-linkmans/{id}", method = RequestMethod.DELETE)
public CommonResult<Object> removeById(@PathVariable("id") Long id) {
boolean success = tenantCustomerLinkmanService.removeById(id);
return success ? CommonResult.success(success) : CommonResult.failed();
}
private TenantCustomerLinkmanVo entity2vo(TenantCustomerLinkman tenantCustomerLinkman) {
if (tenantCustomerLinkman == null) {
return null;
}
String jsonString = JSON.toJSONString(tenantCustomerLinkman);
TenantCustomerLinkmanVo tenantCustomerLinkmanVo = JSON.parseObject(jsonString, TenantCustomerLinkmanVo.class);
if (StringUtils.isEmpty(tenantCustomerLinkmanVo.getTenantName())) {
TenantInfo tenantInfo = tenantInfoService.getById(tenantCustomerLinkman.getTenantId());
if (tenantInfo != null) {
tenantCustomerLinkmanVo.setTenantName(tenantInfo.getTenantName());
}
}
return tenantCustomerLinkmanVo;
}
}
| true |
d490ad14d873c16e04ecf650e7f3b969564a5197 | Java | filipenyakaterina/TestAutomation.JavaTasks | /src/test/java/classes/container/PhoneList.java | UTF-8 | 1,204 | 3.109375 | 3 | [] | no_license | package classes.container;
import classes.entity.Address;
import classes.entity.Phone;
import java.util.ArrayList;
public class PhoneList extends Container<Phone> {
public PhoneList() {
super();
Add(new Phone(0, "Ivan","Ivanovich","Ivanov",new Address("Gikalo",1,2),13,145,12,13));
Add(new Phone(1, "Petr","Petrovich","Petrov",new Address("Kolasa",2,12),173,45,152,53));
Add(new Phone(2, "Oleg","Olegovich","Olegov",new Address("Gikalo",3,25),113,245,0,23));
Add(new Phone(3, "Pavel","Pavlovich","Pavlov",new Address("Kolasa",31,22),133,13,122,173));
Add(new Phone(4, "Ivan","Ivanovich","Ivanov",new Address("Gikalo",13,12),153,19,0,183));
Add(new Phone(5, "Maksim","Maksimovich","Maksimov",new Address("Marksa",14,2),139,15,102,103));
}
public ArrayList<Phone> getSubscriberWithTimeOfCityCallsMoreThan(int timeOfCityCalls){
return findWhere(x->x.getCity()>timeOfCityCalls);
}
public ArrayList<Phone> getSubscribesWhoUseIntercityCalls(){
return findWhere(x->x.getIntercity()>0);
}
public ArrayList<Phone> sortSubscribesWithAlphabetOrder(){
return sortByAscending(Phone::getSurname);
}
}
| true |
98ef40506cec50ccd376c6ef901730dbf73bed10 | Java | crnk-project/crnk-framework | /crnk-core/src/main/java/io/crnk/core/engine/error/ErrorResponseBuilder.java | UTF-8 | 756 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package io.crnk.core.engine.error;
import io.crnk.core.engine.document.ErrorData;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ErrorResponseBuilder {
private Collection<ErrorData> data;
private int status;
public ErrorResponseBuilder setErrorData(Collection<ErrorData> errorObjects) {
this.data = errorObjects;
return this;
}
public ErrorResponseBuilder setSingleErrorData(ErrorData errorData) {
List<ErrorData> errorDatas = new ArrayList<>();
errorDatas.add(errorData);
this.data = errorDatas;
return this;
}
public ErrorResponseBuilder setStatus(int status) {
this.status = status;
return this;
}
public ErrorResponse build() {
return new ErrorResponse(data, status);
}
} | true |
f68979a5935f30240787785b206e4ba23fb63732 | Java | tsotnep/secondTask | /src/Main.java | UTF-8 | 4,782 | 2.515625 | 3 | [] | no_license | import asm.AsmAnalyzer;
import asm.AsmLoader;
import asm.AsmReader;
import asm.InstrReader;
import org.antlr.v4.gui.Trees;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import java.io.*;
import java.util.ArrayList;
import java.util.Map;
/**
* @author Hannes Kinks
* @since 26.11.2015
*/
public class Main {
public static final String INPUT_FILE = "data/input.lang";
public static final String OUTPUT_ASM = "data/output.asm";
public static final String OUTPUT_BIN = "data/output.bin";
public static final String INSTRUCTIONS_CONF = "data/instructions.conf";
public static final boolean DRAW_TREE = false;
public static final int BIT_WIDTH = 8;
public static void main(String[] args) {
try {
// feed input stream to antlr
ANTLRInputStream input = new ANTLRInputStream(new FileInputStream(INPUT_FILE));
LangLexer lexer = new LangLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
LangParser parser = new LangParser(tokens);
if (DRAW_TREE) {
drawTree(parser);
} else {
// convert language to assembler
convertToAsm(parser);
}
// convert assembler to machine code
convertToBin();
} catch (IOException e) {
System.err.println("[ERR] File " + INPUT_FILE + " not found.");
}
}
private static void drawTree(LangParser parser) {
//draw tree in gui
System.out.println("[INFO] Drawing tree.");
ParserRuleContext ruleContext = parser.prog();
/* updated in 4.5.1 */
Trees.inspect(ruleContext, parser);
/* deprecated: ruleContext.inspect(parser); */
}
private static void convertToAsm(LangParser parser) {
//walk the tree
ParseTree tree = parser.prog();
EvalVisitor eval = new EvalVisitor();
eval.visit(tree);
// Write the ASM lines into a file
try {
FileWriter fileWriter = new FileWriter(OUTPUT_ASM);
for (String line : eval.lineArray) {
fileWriter.write(line + "\n");
}
fileWriter.close();
} catch (IOException e) {
System.err.println("[ERR] File cannot be created or opened. Make sure it is not already open somewhere " +
"or you have the required permissions.");
}
}
/**
* Running picoASM which converts assembler to machinecode
*/
private static void convertToBin() {
// parse the instructions from conf file
Map<String, String[]> instructionMap = null;
try {
InputStream is = new FileInputStream(INSTRUCTIONS_CONF);
InstrReader instrReader = new InstrReader();
instructionMap = instrReader.readInstr(is, false);
} catch (FileNotFoundException e) {
System.err.println("[ERR] Operation codes file " + INSTRUCTIONS_CONF + " not found.");
} catch (Exception e) {
System.err.println("[ERR] Error reading the instructions.");
}
// parse the assembler code
AsmLoader asmLoader = null;
try {
InputStream asmStream = new FileInputStream(OUTPUT_ASM);
AsmReader asmReader = new AsmReader();
asmLoader = asmReader.readAsm(asmStream, false);
} catch (FileNotFoundException e) {
System.err.println("[ERR] Output file was not found at " + OUTPUT_ASM);
} catch (Exception e) {
System.err.println("[ERR] Error parsing the assembler code.");
}
// get the machine code output
AsmAnalyzer analyzer = new AsmAnalyzer();
if (instructionMap != null && asmLoader != null) {
ArrayList<String> machineCode = analyzer.analyze(instructionMap,
asmLoader.getLabelList(),
asmLoader.getConstList(),
asmLoader.getFileBuf(),
BIT_WIDTH);
File file = new File(OUTPUT_BIN);
String outputBuf = "";
for (String line : machineCode) {
outputBuf += line + "\n";
}
// write the machine code output to a file
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outputBuf);
bw.close();
} catch (IOException e) {
System.err.println("[ERR] Writing binary file failed.");
}
}
}
}
| true |
147646141ccd760d64fa7888d81658efec586cc1 | Java | zihanbobo/alphadog | /profile-service-provider/src/main/java/com/moseeker/profile/config/AppConfig.java | UTF-8 | 4,397 | 1.945313 | 2 | [] | no_license | package com.moseeker.profile.config;
import com.moseeker.profile.service.impl.talentpoolmvhouse.constant.ProfileMoveConstant;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jack on 17/05/2017.
*/
@Configuration
@EnableRabbit
@ComponentScan({"com.moseeker.profile", "com.moseeker.common.aop.iface", "com.moseeker.entity"})
@PropertySource("classpath:common.properties")
@Import(com.moseeker.baseorm.config.AppConfig.class)
public class AppConfig {
@Autowired
private Environment env;
@Bean
public ConnectionFactory connectionFactory() {
ConnectionFactory cf = new ConnectionFactory();
cf.setHost(env.getProperty("rabbitmq.host").trim());
cf.setPort(Integer.valueOf(env.getProperty("rabbitmq.port").trim()));
cf.setUsername(env.getProperty("rabbitmq.username").trim());
cf.setPassword(env.getProperty("rabbitmq.password").trim());
return cf;
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory());
RetryTemplate retryTemplate = new RetryTemplate();
// 重试机制
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(500);
backOffPolicy.setMultiplier(10.0);
backOffPolicy.setMaxInterval(10000);
retryTemplate.setBackOffPolicy(backOffPolicy);
rabbitTemplate.setRetryTemplate(retryTemplate);
return rabbitTemplate;
}
@Bean
public CachingConnectionFactory cachingConnectionFactory() {
return new CachingConnectionFactory(connectionFactory());
}
@Bean
public AmqpAdmin amqpAdmin() {
RabbitAdmin rabbitAdmin = new RabbitAdmin(cachingConnectionFactory());
rabbitAdmin.setIgnoreDeclarationExceptions(true);
return rabbitAdmin;
}
/**
* listener 容器 (consumer 需要手动确认消息)
* @return
*/
@Bean
public RabbitListenerContainerFactory rabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory listenerContainerFactory = new SimpleRabbitListenerContainerFactory();
listenerContainerFactory.setConnectionFactory(cachingConnectionFactory());
// 设置手动 ACK
listenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
return listenerContainerFactory;
}
/**
* listener 容器 (AcknowledgeMode:auto)
* @return
*/
@Bean
public RabbitListenerContainerFactory rabbitListenerContainerFactoryAutoAck() {
SimpleRabbitListenerContainerFactory listenerContainerFactory = new SimpleRabbitListenerContainerFactory();
listenerContainerFactory.setConnectionFactory(cachingConnectionFactory());
return listenerContainerFactory;
}
@Bean
public TopicExchange exchange() {
// 简历搬家交换机
return new TopicExchange(ProfileMoveConstant.PROFILE_MOVE_EXCHANGE_NAME, true, false);
}
@Bean
public Queue mvHouseQueue() {
// 简历搬家队列
return new Queue(ProfileMoveConstant.PROFILE_MOVE_QUEUE, true, false, false);
}
@Bean
public List<Binding> bindingMvHouseQueue() {
return new ArrayList<Binding>() {{
add(BindingBuilder.bind(mvHouseQueue()).to(exchange()).with(ProfileMoveConstant.PROFILE_MOVE_ROUTING_KEY_RESPONSE));
}};
}
}
| true |
b82f73ed11c2de0d181aeb4d88787c20c2a8957a | Java | GregBrannon/EventBusCalculator | /EBCalculatorController.java | UTF-8 | 4,100 | 3.203125 | 3 | [] | no_license | package com.gdbrannon.study.eventbus.calculator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
//*************************************************************
// Name : EBCalculatorController.java
// Author: GregBrannon, August 2013
// Based on a tutorial written by : Stuart Davidson
// Original Date : 12/05/2007
// Description : A demonstration of how to create a simple MVC
// calculator using the EventBus programming structure
// or design pattern. Rather than accepting instances
// of the model and view from the main() method as in
// traditional MVC, the controller subscribes to events
// and is notified of those events by the EventBus.
//
// As in traditional MVC, the controller then uses those
// event notifications to provide the necessary responses
// to the view in order to respond
// appropriately to user input, and coordinates the
// application's response to user input using the
// model, displaying the results in the view.
// Original tutorial from the Guidebook MVC Tutorial at:
//http://www.macs.hw.ac.uk/guidebook/?name=Using%20The%20GUI&page=1
//
// EventBus information gleaned from the Google Guava EventBus
// API and the following links:
// http://www.javacodegeeks.com/2013/06/guavas-eventbus-simple-publishersubscriber.html
// http://www.javacodegeeks.com/2012/11/google-guava-eventbus-for-event-programming.html
//*************************************************************
public class EBCalculatorController implements Runnable
{
EBCalculatorModel model;
EBCalculatorView view;
private EventBus calculatorEB;
// constructor CalculatorController()
public EBCalculatorController( EventBus calculatorEB )
{
this.calculatorEB = calculatorEB;
/* The old way - being replaced by Event Subscriptions
// method actionPerformed() matches actions from the view to the
// appropriate responses by first determining the action's source
// and then using a string of if/else statements. the purpose of
// this study is to explore whether there are more economical and
// efficient options to this particular feature of the traditional
// MVC pattern
public void actionPerformed( ActionEvent ae )
{
String action_com = ae.getActionCommand();
if(action_com.equals( "+" ))
{
model.doAddition( view.getFieldText() );
}
else if ( action_com.equals( "-" ) )
{
model.doSubtraction( view.getFieldText() );
}
else if ( action_com.equals( "*" ) )
{
model.doMultiply( view.getFieldText() );
}
else if ( action_com.equals( "/" ) )
{
model.doDivision( view.getFieldText() );
}
view.setFieldText( "" + model.getAnswer() );
} // end method actionPerformed()
*/ // End of the old way
} // end constructor CalculatorController()
// method run() is used to complete any initialization needed
@Override
public void run()
{
calculatorEB.register( this );
} // end method run()
@Subscribe
public void handleAdditionButtonEvent( AdditionButtonEvent abe )
{
calculatorEB.post( new AddEvent( abe.value ) );
}
@Subscribe
public void handleSubtractionButtonEvent( SubtractionButtonEvent sbe )
{
calculatorEB.post( new SubtractEvent( sbe.value ) );
}
@Subscribe
public void handleMultiplicationButtonEvent( MultiplicationButtonEvent mbe )
{
calculatorEB.post( new MultiplyEvent( mbe.value ) );
}
@Subscribe
public void handleDivisionButtonEvent( DivisionButtonEvent dbe )
{
calculatorEB.post( new DivideEvent( dbe.value ) );
}
@Subscribe
public void handleModelResultEvent( ModelResultEvent mre )
{
calculatorEB.post( new UpdateDisplayEvent( mre.value ) );
}
} // end class CalculatorController
| true |
7c858d66f56b970fd74997bb26f7edc13145e028 | Java | WebPudge/design_patterns | /src/five/StatSingleton.java | UTF-8 | 370 | 2.71875 | 3 | [] | no_license | package five;
public class StatSingleton {
private static StatSingleton uniqueInstance = new StatSingleton();
private StatSingleton () {}
public static StatSingleton getInstance(){
return uniqueInstance;
}
// other useful methods here
public String getDescription() {
return "I'm a statically initialized Singleton!";
}
}
| true |
23229e30650c0e3c2ae5c08bafbd9ae84ef227c5 | Java | bitwaves/first-wave | /ch.bitwave.parser.delphi/src/main/java/ch/bitwave/lang/delphi/mapping/DelphiASTPrinter.java | UTF-8 | 1,861 | 2.921875 | 3 | [] | no_license | package ch.bitwave.lang.delphi.mapping;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Stack;
import ch.bitwave.lang.delphi.ast.DelphiSyntaxAdapter;
import ch.bitwave.lang.delphi.ast.Node;
public class DelphiASTPrinter extends DelphiSyntaxAdapter {
private Writer writer;
private String currentIndent;
private Stack<String> indentStack;
private void append(final String text) {
try {
this.writer.write(text);
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to append text to writer due to: %s",
e.getMessage()), e);
}
}
private void indent() {
this.indentStack.push(this.currentIndent);
this.currentIndent = this.currentIndent + " ";
}
private void undent() {
this.currentIndent = this.indentStack.pop();
}
private void writeIndent() {
append(this.currentIndent);
}
public DelphiASTPrinter(final Writer writer) {
super();
this.writer = writer;
this.currentIndent = "";
this.indentStack = new Stack<String>();
}
public static String writeToString(final Node node) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Writer streamWriter = new OutputStreamWriter(bos);
DelphiASTPrinter printer = new DelphiASTPrinter(streamWriter);
printer.writeNode(node);
streamWriter.close();
return bos.toString();
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to write node %s to a string.", node));
}
}
public void writeNode(final Node node) {
descend(node);
}
@Override
protected void descend(final Node node) {
writeIndent();
append(node.getClass().getSimpleName());
append("\r\n");
indent();
super.descend(node);
undent();
}
}
| true |
393fb1d0d0b74ca8e08ecfc1d50dd19227d2fbcb | Java | AlphaMediaConsultant/rutilahu | /app/src/main/java/com/alphamedia/rutilahu/DataPenerimaRealmIO.java | UTF-8 | 13,255 | 1.695313 | 2 | [
"MIT"
] | permissive | package com.alphamedia.rutilahu;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
public class DataPenerimaRealmIO extends ActionBarActivity implements LoaderManager.LoaderCallbacks<String> {
//private GridView mGridView;
private DataPenerimaAdapter mAdapter;
private ListView mListView;
private Realm realm;
RealmConfiguration realmConfiguration;
private boolean mSearchOpened = false;
private String mSearchQuery = "";
private EditText mSearchEt;
private MenuItem mSearchAction;
private Drawable mIconCloseSearch;
private Drawable mIconOpenSearch;
RealmResults<Penerima> result;
private static final int LOAD_NETWORK_A = 1;
private static final int LOAD_NETWORK_B = 2;
private static final int LOAD_NETWORK_C = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_penerima_realm_io);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getLoaderManager().initLoader(LOAD_NETWORK_C, null, this).forceLoad();
mIconOpenSearch = getResources()
.getDrawable(R.drawable.ic_search_black_18dp);
mIconCloseSearch = getResources()
.getDrawable(R.drawable.ic_clear_black_18dp);
realmConfiguration = new RealmConfiguration.Builder(this).build();
}
@Override
protected void onStart() {
super.onStart();
realm = Realm.getInstance(this);
}
@Override
protected void onStop() {
super.onStop();
realm.close();
Realm.deleteRealm(realmConfiguration);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchAction = menu.findItem(R.id.action_search);
//menu.findItem(R.id.action_save).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_data_penerima_realm_io, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
item.setIcon(R.drawable.ic_settings_black_18dp);
startActivity(new Intent(this, SettingsaActivity.class));
return true;
}
if (id == R.id.action_search) {
if (mSearchOpened) {
closeSearchBar();
} else {
openSearchBar(mSearchQuery);
}
return true;
}
if (id == R.id.action_downloads) {
Intent download = new Intent(getApplicationContext(),Download.class);
startActivity(download);
return true;
}
if (id == R.id.action_upload) {
Intent upload = new Intent(getApplicationContext(),UploadActivity.class);
startActivity(upload);
return true;
}
if (id == R.id.action_refresh) {
refreshView();
return true;
}
return super.onOptionsItemSelected(item);
}
private void refreshView()
{
mAdapter = new DataPenerimaAdapter(this);
result = realm.where(Penerima.class).findAll();
result.sort("namalengkap", RealmResults.SORT_ORDER_ASCENDING);
mAdapter.setData(result);
mListView = (ListView) findViewById(R.id.custom_list);
mListView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mListView.invalidate();
realm.close();
}
private void openSearchBar(String queryText) {
// Set custom view on action bar.
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.search_bar);
// Search edit text field setup.
mSearchEt = (EditText) actionBar.getCustomView()
.findViewById(R.id.etSearch);
mSearchEt.addTextChangedListener(new SearchWatcher());
mSearchEt.setText(queryText);
mSearchEt.requestFocus();
mSearchAction.setIcon(mIconCloseSearch);
mSearchOpened = true;
}
private void closeSearchBar() {
getSupportActionBar().setDisplayShowCustomEnabled(false);
mSearchAction.setIcon(mIconOpenSearch);
mSearchEt.setText("");
mSearchOpened = false;
refreshView();
}
/**
* Responsible for handling changes in search edit text.
*/
private class SearchWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence c, int i, int i2, int i3) {
Log.i("Status TextWatcher: ", "beforeTextChanged");
}
@Override
public void onTextChanged(CharSequence c, int i, int i2, int i3) {
Log.i("Status TextWatcher: ", "onTextChanged");
}
@Override
public void afterTextChanged(Editable editable) {
mSearchQuery = mSearchEt.getText().toString();
Log.i("Query Search: ", mSearchQuery);
result = realm.where(Penerima.class)
.contains("namalengkap", mSearchQuery, false)
.or()
.contains("jalan_desa", mSearchQuery, false)
.or()
.contains("desa", mSearchQuery, false)
.or()
.contains("kecamatan", mSearchQuery, false)
.or()
.contains("kabupaten", mSearchQuery, false)
.findAll();
result.sort("namalengkap", RealmResults.SORT_ORDER_ASCENDING);
mAdapter = new DataPenerimaAdapter(getApplicationContext());
mAdapter.setData(result);
mListView = (ListView) findViewById(R.id.custom_list);
mListView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
public List<Penerima> loadPenerima() throws IOException {
return realm.allObjects(Penerima.class);
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
@Override
public Loader<String> onCreateLoader(int i, Bundle bundle) {
//return new ApiLoaderTask(this, DataPenerimaRealmIO.class, "C.json");
switch (i) {
case LOAD_NETWORK_C:
return new ApiLoaderTask(this, DataPenerimaRealmIO.class, "data.json");
default:
return new ApiLoaderTask(this, DataPenerimaRealmIO.class, "data.json");
}
}
@Override
public void onLoadFinished(Loader<String> loader, String string) {
if(mAdapter == null) {
List<Penerima> penerima = null;
try {
penerima = loadPenerima();
} catch (IOException e) {
e.printStackTrace();
}
mAdapter = new DataPenerimaAdapter(this);
mAdapter.setData(penerima);
mListView = (ListView) findViewById(R.id.custom_list);
mListView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mListView.invalidate();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
TextView textView = (TextView) findViewById(R.id.nama);
TextView ktp = (TextView) findViewById(R.id.ktp);
Toast.makeText(getApplicationContext(),
"Nama: " + textView.getText().toString() + " - " +
"KTP: " + ktp.getText().toString(),
Toast.LENGTH_SHORT)
.show();
Intent i = new Intent(DataPenerimaRealmIO.this, DetailActivity.class);
i.putExtra("ktp", ktp.getText().toString());
startActivity(i);
}
});
}
}
@Override
public void onLoaderReset(Loader<String> loader) {
}
public static class ApiLoaderTask extends AsyncTaskLoader<String> {
private String mFile;
private Class mClass;
private Realm realm;
public ApiLoaderTask(Context context, Class klass, String file) {
super(context);
mFile = file;
mClass = klass;
}
@Override
public String loadInBackground() {
Log.d("Loader", mFile);
realm = Realm.getInstance(getContext());
if (!mClass.equals(DataPenerimaRealmIO.class)) {
try {
loadJsonFromStream(realm);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
loadJsonFromStream(realm);
} catch (IOException e) {
e.printStackTrace();
}
}
realm.close();
return "";
}
@Override
protected void onStartLoading() {
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
}
private void loadJsonFromStream(Realm realm) throws IOException {
File initialFile = new File(Config.DATA_DIR);
if(initialFile.exists())
{
InputStream stream = new FileInputStream(initialFile);
realm.beginTransaction();
try {
realm.createAllFromJson(Penerima.class, stream);
realm.commitTransaction();
} catch (IOException e) {
Log.e("Error: ", e.getMessage() + " - getStackTrace: " + e.getStackTrace().toString());
realm.cancelTransaction();
} finally {
if (stream != null) {
stream.close();
}
}
} else
{
String message = "File tidak ditemukan, download file terlebih dahulu.";
AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
builder.setMessage(message).setTitle("Peringatan")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/* panggil inten download ? */
}
});
AlertDialog alert = builder.create();
alert.show();
Log.e("Error: ", message);
}
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(DataPenerimaRealmIO.this).setMessage(
R.string.exit_message).setTitle(
R.string.exit_title).setCancelable(false)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
setResult(RESULT_CANCELED);
Intent i = new Intent();
quit(false,i);
}
}).setNeutralButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
private void quit(boolean success, Intent i) {
setResult((success) ? -1:0, i);
this.finish();
}
}
| true |
5ffe2b3049902774bc72112b4f09685f2486a3ca | Java | MorvanL/RasendeRoboter_PC2R | /PC2R_Projet_Nea_Lassauzay/serveur/src/app/Main.java | UTF-8 | 653 | 2.96875 | 3 | [] | no_license | package app;
import java.io.IOException;
import java.net.UnknownHostException;
import server.ThreadPooledServer;
import util.Logger;
public class Main {
public static void main(String[] args) throws IOException {
// Address must be specify
if (args.length == 1) {
try {
// Create and launch server
ThreadPooledServer tps = new ThreadPooledServer(args[0]);
tps.run();
}
// Invalid address
catch (UnknownHostException e) {
Logger.forceLogln("The follow address is invalid : " + args[0]);
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
Logger.forceLogln("Usage: ant run adress");
}
}
}
| true |
c8c91c0ba6b1257018284502b92a9309488c3056 | Java | 121-cloud/srv-auth | /src/main/java/otocloud/auth/verticle/UserComponent.java | UTF-8 | 2,464 | 2.03125 | 2 | [] | no_license | package otocloud.auth.verticle;
import com.google.inject.Inject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import otocloud.auth.handler.*;
import otocloud.auth.handler.messagechecker.UserCreationChecker;
import otocloud.framework.core.OtoCloudComponentImpl;
import otocloud.framework.core.OtoCloudEventHandlerRegistry;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhangye on 2015-10-14.
*/
//@LazySingleton
public class UserComponent extends OtoCloudComponentImpl {
private static final String USER_COMPONENT_NAME = "user-management";
protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
public static final String MANAGE_USER_ADDRESS = "users";//响应用户注册
@Inject
private UserRegisterHandler userRegisterHandler;
@Inject
private UserLoginHandler userLoginHandler;
@Inject
private UserLogoutHandler userLogoutHandler;
@Inject
private UserUpdateHandler userUpdateHandler;
@Inject
private UserDeleteHandler userDeleteHandler;
@Inject
private CellNoQueryHandler cellNoQueryHandler;
@Inject
private TokenQueryHandler tokenQueryHandler;
@Inject
private DepartmentQueryHandler departmentQueryHandler;
@Inject
private UserQueryHandler userQueryHandler;
@Inject
private ErpUserLoginHandler erpUserLoginHandler;
@Inject
private ErpUserImportHandler erpUserImportHandler;
@Inject
private UserCreationHandler userCreationHandler;
@Override
public String getName() {
return USER_COMPONENT_NAME;
}
public static String getComponentName(){
return USER_COMPONENT_NAME;
}
@Override
public List<OtoCloudEventHandlerRegistry> registerEventHandlers() {
List<OtoCloudEventHandlerRegistry> ret = new ArrayList<OtoCloudEventHandlerRegistry>();
ret.add(userRegisterHandler);
ret.add(userLoginHandler);
ret.add(userLogoutHandler);
ret.add(userUpdateHandler);
ret.add(userDeleteHandler);
ret.add(cellNoQueryHandler);
ret.add(tokenQueryHandler);
ret.add(departmentQueryHandler);
ret.add(userQueryHandler);
ret.add(erpUserLoginHandler);
ret.add(erpUserImportHandler);
ret.add(userCreationHandler);
return ret;
}
}
| true |
685b3517bd20223cea397be74f5b990dabd9ddeb | Java | DefiantBurger/SkyblockItems | /Dependencies/work/decompile-00fabbe5/net/minecraft/world/level/levelgen/structure/templatesystem/DefinedStructureRuleTestType.java | UTF-8 | 1,345 | 1.8125 | 2 | [] | no_license | package net.minecraft.world.level.levelgen.structure.templatesystem;
import com.mojang.serialization.Codec;
import net.minecraft.core.IRegistry;
public interface DefinedStructureRuleTestType<P extends DefinedStructureRuleTest> {
DefinedStructureRuleTestType<DefinedStructureTestTrue> ALWAYS_TRUE_TEST = a("always_true", DefinedStructureTestTrue.CODEC);
DefinedStructureRuleTestType<DefinedStructureTestBlock> BLOCK_TEST = a("block_match", DefinedStructureTestBlock.CODEC);
DefinedStructureRuleTestType<DefinedStructureTestBlockState> BLOCKSTATE_TEST = a("blockstate_match", DefinedStructureTestBlockState.CODEC);
DefinedStructureRuleTestType<DefinedStructureTestTag> TAG_TEST = a("tag_match", DefinedStructureTestTag.CODEC);
DefinedStructureRuleTestType<DefinedStructureTestRandomBlock> RANDOM_BLOCK_TEST = a("random_block_match", DefinedStructureTestRandomBlock.CODEC);
DefinedStructureRuleTestType<DefinedStructureTestRandomBlockState> RANDOM_BLOCKSTATE_TEST = a("random_blockstate_match", DefinedStructureTestRandomBlockState.CODEC);
Codec<P> codec();
static <P extends DefinedStructureRuleTest> DefinedStructureRuleTestType<P> a(String s, Codec<P> codec) {
return (DefinedStructureRuleTestType) IRegistry.a(IRegistry.RULE_TEST, s, (Object) (() -> {
return codec;
}));
}
}
| true |
baeff60d35e4c63e45b3a960655457dd211af621 | Java | cobaltblueocean/OG-Platform | /sesame/sesame-function/src/main/java/com/opengamma/sesame/component/RetrievalPeriod.java | UTF-8 | 8,050 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.sesame.component;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.threeten.bp.Period;
/**
* Temporary bean to represent a period in Joda bean so it can be deserialised.
*/
@BeanDefinition(builderScope = "private")
public final class RetrievalPeriod implements ImmutableBean {
/**
* The retrieval period.
*/
@PropertyDefinition(validate = "notNull")
private final Period _retrievalPeriod;
/**
* Create an instance with the specified period.
*
* @param period the required retrieval period
* @return a RetrievalPeriod
*/
public static RetrievalPeriod of(Period period) {
return new RetrievalPeriod(period);
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code RetrievalPeriod}.
* @return the meta-bean, not null
*/
public static RetrievalPeriod.Meta meta() {
return RetrievalPeriod.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(RetrievalPeriod.Meta.INSTANCE);
}
private RetrievalPeriod(
Period retrievalPeriod) {
JodaBeanUtils.notNull(retrievalPeriod, "retrievalPeriod");
this._retrievalPeriod = retrievalPeriod;
}
@Override
public RetrievalPeriod.Meta metaBean() {
return RetrievalPeriod.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
//-----------------------------------------------------------------------
/**
* Gets the retrieval period.
* @return the value of the property, not null
*/
public Period getRetrievalPeriod() {
return _retrievalPeriod;
}
//-----------------------------------------------------------------------
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
RetrievalPeriod other = (RetrievalPeriod) obj;
return JodaBeanUtils.equal(getRetrievalPeriod(), other.getRetrievalPeriod());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(getRetrievalPeriod());
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(64);
buf.append("RetrievalPeriod{");
buf.append("retrievalPeriod").append('=').append(JodaBeanUtils.toString(getRetrievalPeriod()));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code RetrievalPeriod}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code retrievalPeriod} property.
*/
private final MetaProperty<Period> _retrievalPeriod = DirectMetaProperty.ofImmutable(
this, "retrievalPeriod", RetrievalPeriod.class, Period.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"retrievalPeriod");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -1497501163: // retrievalPeriod
return _retrievalPeriod;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends RetrievalPeriod> builder() {
return new RetrievalPeriod.Builder();
}
@Override
public Class<? extends RetrievalPeriod> beanType() {
return RetrievalPeriod.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code retrievalPeriod} property.
* @return the meta-property, not null
*/
public MetaProperty<Period> retrievalPeriod() {
return _retrievalPeriod;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -1497501163: // retrievalPeriod
return ((RetrievalPeriod) bean).getRetrievalPeriod();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code RetrievalPeriod}.
*/
private static final class Builder extends DirectFieldsBeanBuilder<RetrievalPeriod> {
private Period _retrievalPeriod;
/**
* Restricted constructor.
*/
private Builder() {
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case -1497501163: // retrievalPeriod
return _retrievalPeriod;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case -1497501163: // retrievalPeriod
this._retrievalPeriod = (Period) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public RetrievalPeriod build() {
return new RetrievalPeriod(
_retrievalPeriod);
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(64);
buf.append("RetrievalPeriod.Builder{");
buf.append("retrievalPeriod").append('=').append(JodaBeanUtils.toString(_retrievalPeriod));
buf.append('}');
return buf.toString();
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| true |
c9cf8b3b544fc521ae33ded4d60f588f82260652 | Java | SrinathKushnoore/AssignmentWork | /src/test/java/TestOrganization/ForeclosuresTest/Test1.java | UTF-8 | 2,156 | 2.390625 | 2 | [] | no_license | package TestOrganization.ForeclosuresTest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test1 {
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","C:\\31TestFolder\\New folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
//Launching sample website
driver.get("https://sso.eservices.jud.ct.gov/foreclosures/Public/PendPostbyTownList.aspx");
//Get list of Cities
List<WebElement> allLinks = driver.findElements(By.xpath("//*[contains(@id,'Body_Panel1')]//a"));
//Traversing through the list and checking city matches with the given list
for(WebElement link:allLinks)
{
String town = link.getText();
if(town == "Milford"|| town == "Trumbull"|| town == "Norwalk"|| town == "Stamford"|| town == "Shelton"|| town == "Fairfield")
{
System.out.println("Opened city is" + " - " + town);
//Navigated to specific city sales list in new browser
driver.get(link.getAttribute("href"));
List<WebElement> datesList = driver.findElements(By.xpath("//span[contains(@id, 'Label1')]"));
for(WebElement date:datesList)
{
String salesDate = date.getText();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
LocalDateTime now = LocalDateTime.now();
System.out.println("today date is"+sdf.format(now));
if(salesDate.compareTo(sdf.format(now))<7){
driver.findElement(By.xpath("//a[text()='View Full Notice']")).sendKeys(Keys.CONTROL +"t");
}
}
}
}
}
}
| true |
753260d0af4513241288fd4777bb8f6e8e980645 | Java | Poorvankbhatia/Leetcode | /src/string/hard/ClosestPalindrome.java | UTF-8 | 2,557 | 3.96875 | 4 | [] | no_license | /*
Given an integer n, find the closest integer (not including itself), which is a palindrome.
The 'closest' is defined as absolute difference minimized between two integers.
Example 1:
Input: "123"
Output: "121"
Note:
The input n is a positive integer represented by string, whose length will not exceed 18.
If there is a tie, return the smaller one as answer.
*/
package string.hard;
/**
* Created by poorvank on 24/04/17.
*/
public class ClosestPalindrome {
public String nearestPalindromic(String n) {
if (n.length() >= 2 && checkNine(n)) {
StringBuilder s = new StringBuilder("1");
for (int i = 0; i < n.length() - 1; i++) {
s.append("0");
}
s.append("1");
return s.toString();
}
boolean hasOddLength = (n.length() % 2 != 0);
String left = n.substring(0, (n.length() + 1) / 2);
long[] increment = {-1, 0, +1};
String ret = n;
long minDiff = Long.MAX_VALUE;
for (long i : increment) {
StringBuilder s = new StringBuilder(getPalindrome(Long.toString(Long.parseLong(left) + i), hasOddLength));
if (n.length() >= 2 && (s.length() != n.length() || Long.parseLong(s.toString()) == 0)) {
s = new StringBuilder();
for (int j = 0; j < n.length() - 1; j++) {
s.append("9");
}
}
long diff = s.toString().equals(n) ? Long.MAX_VALUE : Math.abs(Long.parseLong(s.toString()) - Long.parseLong(n));
if (diff < minDiff) {
minDiff = diff;
ret = s.toString();
}
}
return ret;
}
private String getPalindrome(String s, boolean isOdd) {
String right = new StringBuilder(s).reverse().toString();
return isOdd ? s.substring(0, s.length() - 1) + right : s + right;
}
private boolean checkNine(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '9') {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s = "100";
System.out.println(new ClosestPalindrome().nearestPalindromic(s));
}
}
/*
We first need to find the higher palindrome and lower palidrome respectively. and return the one who has the least different with the input number.
For the higher palindrome, the low limit is number + 1 while for the lower palindrome, the high limit is number - 1.
*/ | true |
daa2f17fd33d098e09528c39bdf06e0938e9ab79 | Java | PatrikBrosell/EDAF10 | /ComputerProject/src/operations/Halt.java | UTF-8 | 267 | 2.328125 | 2 | [] | no_license | package operations;
import computer.Memory;
import computer.ProgramCounter;
public class Halt extends Operation {
public Halt() {
}
protected void run(Memory memory, ProgramCounter pc) {
pc.setIndex(-1);
}
public String toString() {
return "HLT";
}
}
| true |
984e910309a30f0356fda05947284762f56049ae | Java | Biocodings/kourami | /src/Node.java | UTF-8 | 2,623 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | /*
Part of Kourami HLA typer/assembler
(c) 2017 by Heewook Lee, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
//import java.util.HashSet;
public class Node{
public Node(char b, int ci){
this.base = Character.toUpperCase(b);
this.colIndex = ci;
this.iBase = this.base2Index();
//this.rHash = new HashSet<Integer>();
//moved rHash to CustomWeightedEdge
}
public Node(int ib, int ci){
}
//moved rHash to CustomWeightedEdge
/*
public void addAllReadsFrom(HashSet<Integer> otherRHash){
this.rHash.addAll(otherRHash);
}
public HashSet<Integer> getReadHashSet(){
return this.rHash;
}*/
public Node(Base b){
this(b.getBase(), b.getColPos());
}
public int getIBase(){
return this.iBase;
}
public char getBase(){
return this.base;
}
public Character getBaseObj(){
return new Character(this.base);
}
public int getColIndex(){
return this.colIndex;
}
public void setColIndex(int ni){
this.colIndex = ni;
}
public boolean equals(Node other){
if(this.base == other.getBase()){
if(this.colIndex == other.getColIndex())
return true;
}
return false;
}
public int base2Index(){
if(this.base == 'A' || this.base == 'a')
return 0;
else if(this.base == 'C' || this.base == 'c')
return 1;
else if(this.base == 'G' || this.base == 'g')
return 2;
else if(this.base == 'T' || this.base == 't')
return 3;
else if(this.base == '-' || this.base == '.')
return 4;
else
return 5;
}
public String toString(){
return "[" + base + "," + colIndex + "]";
}
/*
public void incrementNumPathInBubbleFwd(int inc){
this.numPathInBubbleFwd += inc;
}
public void incrementNumPathInBubbleRev(int inc){
this.numPathInBubbleFwd += inc;
}
public void setNumInBubbleFwd(int n){
this.numPathInBubbleFwd = n;
}
public void setNumInBubbleRev(int n){
this.numPathInBubbleRev = n;
}
public int getNumInBubbleFwd(){
return this.numPathInBubbleFwd;
}
public int getNumInBubbleRev(){
return this.numPathInBubbleRev;
}
public void initBubblePathsCounters(){
this.numPathInBubbleFwd = 0;
this.numPathInBubbleRev = 0;
}
*/
private char base;
private int iBase;
private int colIndex;
private int numPathInBubbleFwd;
private int numPathInBubbleRev;
//moved rHash to CustomWeightedEdge
/*
public void addRead(int readNum){
this.rHash.add(new Integer(readNum));
}
private HashSet<Integer> rHash;
*/
}
| true |
25cbb8dcd7dd5616c5a4cd56be30656607838a75 | Java | MaxCE24/SuiviProduction | /src/net/atos/suivi_production/forms/CreationDemandeDAchatForm.java | ISO-8859-1 | 14,310 | 2.125 | 2 | [] | no_license | package net.atos.suivi_production.forms;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.atos.suivi_production.beans.Collaborateur;
import net.atos.suivi_production.beans.DemandeDAchat;
import net.atos.suivi_production.beans.Validation;
import net.atos.suivi_production.dao.CollaborateurDAO;
import net.atos.suivi_production.dao.DemandeDAchatDAO;
import net.atos.suivi_production.dao.ValidationDAO;
public class CreationDemandeDAchatForm {
public static final String CHAMP_NUMERO = "numeroDemandeDAchat";
public static final String CHAMP_DATE = "dateDemandeDAchat";
public static final String CHAMP_DESCRIPTION = "descriptionDemandeDAchat";
public static final String CHAMP_STATUT = "statutDemandeDAchat";
public static final String CHAMP_NUMERO_DE_BON_DE_COMMANDE = "numeroDeBonDeCommandeDemandeDAchat";
public static final String CHAMP_NOM_COLLABORATEUR = "nomCollaborateur";
public static final String CHAMP_PRENOM_COLLABORATEUR = "prenomCollaborateur";
private static final String CHAMP_CHOIX_COLLABORATEUR = "choixNouveauCollaborateur";
private static final String ANCIEN_COLLABORATEUR = "ancienCollaborateur";
private static final String CHAMP_COLLABORATEUR = "listeCollaborateurs";
private static final String CHAMP_COLLABORATEUR_1 = "listeCollaborateurs1";
public static final String CHAMP_DATE_VALIDATION_1 = "dateValidation1DemandeDAchat";
private static final String CHAMP_COLLABORATEUR_2 = "listeCollaborateurs2";
public static final String CHAMP_DATE_VALIDATION_2 = "dateValidation2DemandeDAchat";
private static final String CHAMP_COLLABORATEUR_3 = "listeCollaborateurs3";
public static final String CHAMP_DATE_VALIDATION_3 = "dateValidation3DemandeDAchat";
private static final String CHAMP_COLLABORATEUR_4 = "listeCollaborateurs4";
public static final String CHAMP_DATE_VALIDATION_4 = "dateValidation4DemandeDAchat";
private static final String CHAMP_COLLABORATEUR_5 = "listeCollaborateurs5";
public static final String CHAMP_DATE_VALIDATION_5 = "dateValidation5DemandeDAchat";
private static final String CHAMP_COLLABORATEUR_6 = "listeCollaborateurs6";
public static final String CHAMP_DATE_VALIDATION_6 = "dateValidation6DemandeDAchat";
private static final String FORMAT_DATE = "yyyy-MM-dd";
private static final String ATT_COLLABORATEURS = "collaborateurs";
private String resultat;
private Map<String, String> erreurs = new HashMap<String, String>();
public Map<String, String> getErreurs() {
return erreurs;
}
public String getResultat() {
return resultat;
}
@SuppressWarnings("unchecked")
public DemandeDAchat creerDemandeDAchat(HttpServletRequest request)
throws IOException, SQLException, ParseException {
DemandeDAchat demandeDAchat = new DemandeDAchat();
String numero = getValeurChamp(request, CHAMP_NUMERO);
String date = getValeurChamp(request, CHAMP_DATE);
String description = getValeurChamp(request, CHAMP_DESCRIPTION);
String statut = getValeurChamp(request, CHAMP_STATUT);
String numeroDeBonDeCommande = getValeurChamp(request, CHAMP_NUMERO_DE_BON_DE_COMMANDE);
String dateValidation1 = getValeurChamp(request, CHAMP_DATE_VALIDATION_1);
String collaborateur1 = getValeurChamp(request, CHAMP_COLLABORATEUR_1);
String dateValidation2 = getValeurChamp(request, CHAMP_DATE_VALIDATION_2);
String collaborateur2 = getValeurChamp(request, CHAMP_COLLABORATEUR_2);
String dateValidation3 = getValeurChamp(request, CHAMP_DATE_VALIDATION_3);
String collaborateur3 = getValeurChamp(request, CHAMP_COLLABORATEUR_3);
String dateValidation4 = getValeurChamp(request, CHAMP_DATE_VALIDATION_4);
String collaborateur4 = getValeurChamp(request, CHAMP_COLLABORATEUR_4);
String dateValidation5 = getValeurChamp(request, CHAMP_DATE_VALIDATION_5);
String collaborateur5 = getValeurChamp(request, CHAMP_COLLABORATEUR_5);
String dateValidation6 = getValeurChamp(request, CHAMP_DATE_VALIDATION_6);
String collaborateur6 = getValeurChamp(request, CHAMP_COLLABORATEUR_6);
int valeurNumero = -1;
try {
valeurNumero = validationNumero(numero);
} catch (Exception e) {
setErreur(CHAMP_NUMERO, e.getMessage());
}
demandeDAchat.setNumero(valeurNumero);
SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATE);
Date parsedDate = new Date();
try {
validationDate(date);
parsedDate = format.parse(date);
} catch (Exception e) {
setErreur(CHAMP_DATE, e.getMessage());
}
demandeDAchat.setDate(parsedDate);
try {
validationDescription(description);
} catch (Exception e) {
setErreur(CHAMP_DESCRIPTION, e.getMessage());
}
demandeDAchat.setDescription(description);
try {
validationStatut(statut);
} catch (Exception e) {
setErreur(CHAMP_STATUT, e.getMessage());
}
demandeDAchat.setStatut(statut);
int valeurNumeroDeBonDeCommande = -1;
try {
valeurNumeroDeBonDeCommande = validationNumeroDeBonDeCommande(numeroDeBonDeCommande);
} catch (Exception e) {
setErreur(CHAMP_NUMERO_DE_BON_DE_COMMANDE, e.getMessage());
}
demandeDAchat.setNumeroDeBonDeCommande(valeurNumeroDeBonDeCommande);
Collaborateur collaborateur = null;
String choixNouveauCollaborateur = getValeurChamp(request, CHAMP_CHOIX_COLLABORATEUR);
if (ANCIEN_COLLABORATEUR.equals(choixNouveauCollaborateur)) {
try {
if (getValeurChamp(request, CHAMP_COLLABORATEUR) != null) {
Integer idCollaborateur = Integer.parseInt(getValeurChamp(request, CHAMP_COLLABORATEUR));
HttpSession session = request.getSession();
collaborateur = (Collaborateur) ((Map<Integer, Collaborateur>) session
.getAttribute(ATT_COLLABORATEURS)).get(idCollaborateur);
} else
throw new Exception("Merci de slectionner un collaborateur.");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
setErreur(CHAMP_NOM_COLLABORATEUR, e.getMessage());
}
demandeDAchat.setCollaborateur(collaborateur);
} else {
CreationCollaborateurForm collaborateurForm = new CreationCollaborateurForm();
collaborateur = collaborateurForm.creerCollaborateur(request);
boolean cEstUnNouveauCollaborateur = false;
try {
validationNomCollaborateur(collaborateur);
cEstUnNouveauCollaborateur = true;
} catch (Exception e) {
setErreur(CHAMP_NOM_COLLABORATEUR, e.getMessage());
cEstUnNouveauCollaborateur = false;
}
try {
validationPrenomCollaborateur(collaborateur);
cEstUnNouveauCollaborateur = true;
} catch (Exception e) {
setErreur(CHAMP_PRENOM_COLLABORATEUR, e.getMessage());
cEstUnNouveauCollaborateur = false;
}
try {
if (cEstUnNouveauCollaborateur) {
collaborateur.setId(CollaborateurDAO.getID());
new CollaborateurDAO().creer(collaborateur);
}
} catch (SQLException e) {
e.printStackTrace();
}
demandeDAchat.setCollaborateur(collaborateur);
}
int idDemandeDAchat = 1;
try {
try {
idDemandeDAchat = DemandeDAchatDAO.getID();
} catch (Exception e) {
}
} catch (Exception e) {
}
demandeDAchat.setId(idDemandeDAchat);
if ((dateValidation1 != null) && (collaborateur1 != null)) {
Collaborateur valideur1 = null;
Validation validation1 = null;
try {
Integer idValideur1 = Integer.parseInt(collaborateur1);
HttpSession session = request.getSession();
valideur1 = (Collaborateur) ((Map<Integer, Collaborateur>) session.getAttribute(ATT_COLLABORATEURS))
.get(idValideur1);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
}
validation1 = new Validation(ValidationDAO.getID(), format.parse(dateValidation1), valideur1,
demandeDAchat);
new ValidationDAO().creer(validation1);
demandeDAchat.setValidations(new TreeMap<Integer, Validation>());
demandeDAchat.getValidations().put(validation1.getId(), validation1);
}
if ((dateValidation2 != null) && (collaborateur2 != null)) {
Collaborateur valideur2 = null;
Validation validation2 = null;
try {
Integer idValideur2 = Integer.parseInt(collaborateur2);
HttpSession session = request.getSession();
valideur2 = (Collaborateur) ((Map<Integer, Collaborateur>) session.getAttribute(ATT_COLLABORATEURS))
.get(idValideur2);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
}
validation2 = new Validation(ValidationDAO.getID(), format.parse(dateValidation2), valideur2,
demandeDAchat);
new ValidationDAO().creer(validation2);
demandeDAchat.setValidations(new TreeMap<Integer, Validation>());
demandeDAchat.getValidations().put(validation2.getId(), validation2);
}
if ((dateValidation3 != null) && (collaborateur3 != null)) {
Collaborateur valideur3 = null;
Validation validation3 = null;
try {
Integer idValideur3 = Integer.parseInt(collaborateur3);
HttpSession session = request.getSession();
valideur3 = (Collaborateur) ((Map<Integer, Collaborateur>) session.getAttribute(ATT_COLLABORATEURS))
.get(idValideur3);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
}
validation3 = new Validation(ValidationDAO.getID(), format.parse(dateValidation3), valideur3,
demandeDAchat);
new ValidationDAO().creer(validation3);
demandeDAchat.getValidations().put(validation3.getId(), validation3);
}
if ((dateValidation4 != null) && (collaborateur4 != null)) {
Collaborateur valideur4 = null;
Validation validation4 = null;
try {
Integer idValideur4 = Integer.parseInt(collaborateur4);
HttpSession session = request.getSession();
valideur4 = (Collaborateur) ((Map<Integer, Collaborateur>) session.getAttribute(ATT_COLLABORATEURS))
.get(idValideur4);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
}
validation4 = new Validation(ValidationDAO.getID(), format.parse(dateValidation4), valideur4,
demandeDAchat);
new ValidationDAO().creer(validation4);
demandeDAchat.getValidations().put(validation4.getId(), validation4);
}
if ((dateValidation5 != null) && (collaborateur5 != null)) {
Collaborateur valideur5 = null;
Validation validation5 = null;
try {
Integer idValideur5 = Integer.parseInt(collaborateur5);
HttpSession session = request.getSession();
valideur5 = (Collaborateur) ((Map<Integer, Collaborateur>) session.getAttribute(ATT_COLLABORATEURS))
.get(idValideur5);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
}
validation5 = new Validation(ValidationDAO.getID(), format.parse(dateValidation5), valideur5,
demandeDAchat);
new ValidationDAO().creer(validation5);
demandeDAchat.setValidations(new TreeMap<Integer, Validation>());
demandeDAchat.getValidations().put(validation5.getId(), validation5);
}
if ((dateValidation6 != null) && (collaborateur6 != null)) {
Collaborateur valideur6 = null;
Validation validation6 = null;
try {
Integer idValideur6 = Integer.parseInt(collaborateur6);
HttpSession session = request.getSession();
valideur6 = (Collaborateur) ((Map<Integer, Collaborateur>) session.getAttribute(ATT_COLLABORATEURS))
.get(idValideur6);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
}
validation6 = new Validation(ValidationDAO.getID(), format.parse(dateValidation6), valideur6,
demandeDAchat);
new ValidationDAO().creer(validation6);
demandeDAchat.setValidations(new TreeMap<Integer, Validation>());
demandeDAchat.getValidations().put(validation6.getId(), validation6);
}
if (erreurs.isEmpty()) {
resultat = "Succs de la cration de la demande d'achat.";
} else {
resultat = "chec de la cration de la demande d'achat.";
}
return demandeDAchat;
}
private int validationNumero(String numero) throws Exception {
int temp = -1;
if (numero == null) {
throw new Exception("Merci d'entrer un numro.");
} else {
temp = Integer.parseInt(numero);
}
return temp;
}
private void validationDate(String date) throws Exception {
if (date == null || date.trim().equals("")) {
{
throw new Exception("Merci d'entrer une date.");
}
}
}
private void validationDescription(String description) throws Exception {
if (description == null) {
throw new Exception("Merci d'entrer une description de la demande d'achat.");
}
}
private void validationStatut(String statut) throws Exception {
if (statut == null) {
throw new Exception("Merci d'entrer un statut de la demande d'achat.");
}
}
private int validationNumeroDeBonDeCommande(String numeroDeBonDeCommande) throws Exception {
int temp = -1;
if (numeroDeBonDeCommande == null) {
throw new Exception("Merci d'entrer un numro de bon de commande.");
} else {
temp = Integer.parseInt(numeroDeBonDeCommande);
}
return temp;
}
private void validationNomCollaborateur(Collaborateur collaborateur) throws Exception {
if (collaborateur.getNom() != null) {
if (collaborateur.getNom().length() < 2) {
throw new Exception("Le nom du collaborateur doit contenir au moins 2 caractres.");
}
} else {
throw new Exception("Merci d'entrer le nom du collaborateur.");
}
}
private void validationPrenomCollaborateur(Collaborateur collaborateur) throws Exception {
if (collaborateur.getPrenom() != null) {
if (collaborateur.getPrenom().length() < 2) {
throw new Exception("Le prnom du collaborateur doit contenir au moins 2 caractres.");
}
} else {
throw new Exception("Merci d'entrer le prnom du collaborateur.");
}
}
private static String getValeurChamp(HttpServletRequest request, String nomChamp) {
String valeur = request.getParameter(nomChamp);
if (valeur == null || valeur.trim().length() == 0) {
return null;
} else {
return valeur;
}
}
private void setErreur(String champ, String message) {
erreurs.put(champ, message);
}
}
| true |
0338392f1adeaada0ceba158e08f9332d3e36166 | Java | Mr1Ng/2018-07-09-10-17-19-1531131439 | /src/main/java/practice04/Student.java | GB18030 | 545 | 3.609375 | 4 | [] | no_license | package practice04;
import practice04.Person;
public class Student extends Person{
private int klass;
public Student(String name,int age,int klass) {
super(name,age);
this.klass = klass;
}
public int getKlass() {
return klass;
}
public void setKlass(int klass) {
this.klass = klass;
}
@Override
//Ը֤@OverrideķǷ㸸еģûоͻᱨ
public String introduce() {
return String.format("I am a studen. I am at Class %d.", this.getKlass());
}
}
| true |
49b0d2ddd81a4a814c2c7f0f8902893dae295e9a | Java | hanghaifeng1994/java | /java的老年大学项目/testing/trunk/testing-service/src/main/java/com/learnyeai/testing/web/TestingTestController.java | UTF-8 | 1,338 | 1.976563 | 2 | [] | no_license | package com.learnyeai.testing.web;
import com.learnyeai.learnai.context.CtxHeadUtil;
import com.learnyeai.learnai.support.BaseController;
import com.learnyeai.learnai.support.BaseService;
import com.learnyeai.learnai.support.IBusinessContext;
import com.learnyeai.testing.model.TestingTest;
import com.learnyeai.testing.service.TestingTestWyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author twang
*/
@RestController
@RequestMapping("${adminPath}" + TestingTestController.BASE_URL)
public class TestingTestController extends BaseController<TestingTest> {
public static final String BASE_URL = "/TestingTest/";
@Autowired
private TestingTestWyService testingTestWyService;
@Override
protected BaseService<TestingTest> getService() {
return testingTestWyService;
}
@Override
public Object execute(IBusinessContext ctx) {
String method = CtxHeadUtil.getControllerMethod();
if("save".equals(method)){
return testingTestWyService.saveData(ctx);
}
if("delete".equals(method)){
return testingTestWyService.deleteData(ctx);
}
return super.execute(ctx);
}
}
| true |
52c7212628d7c1dc64d3e58575eb084bbba353b1 | Java | outkst/CS1530_Laboon_Chess | /src/main/java/chess/view/VideoPanel.java | UTF-8 | 1,724 | 2.546875 | 3 | [] | no_license | package chess;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // awt.* does not import Action or Event Listeners
import java.io.*;
import javax.imageio.*;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.layout.BorderPane;
public class VideoPanel extends JPanel {
protected static MediaPlayer player;
public VideoPanel() {
this.setLayout(new BorderLayout());
//Adding the video to the dialog box
Platform.setImplicitExit(false);
JFXPanel web = new JFXPanel();
String url= "";
String resultsOfGame = BoardPanel.my_rulebook.resultsOfGame;
if(resultsOfGame.equals("win")) {
url = this.getClass().getResource("/nyan.mp4").toExternalForm();
}
else if(resultsOfGame.equals("loss")) {
url = this.getClass().getResource("/rickroll.mp4").toExternalForm();
}
else if(resultsOfGame.equals("draw")) {
url = this.getClass().getResource("/ross.mp4").toExternalForm();
}
player = new MediaPlayer(new Media(url));
player.setAutoPlay(true);
// create mediaView and add media player to the viewer
MediaView mediaView = new MediaView();
mediaView.setFitHeight(450); //Sets video height
mediaView.setMediaPlayer(player);
BorderPane pane = new BorderPane();
pane.setCenter(mediaView);
Scene scene = new Scene(pane, Color.BLACK);
web.setScene(scene);
this.add(web, BorderLayout.CENTER);
}
public void exit() {
if(player != null) {
player.stop();
player.dispose();
}
}
}
| true |
b7d11b5051c1ed2c1e9f240f9b25f200217ac255 | Java | Octogonapus/chart-fx | /chartfx-dataset/src/main/java/de/gsi/dataset/event/EventRateLimiter.java | UTF-8 | 5,983 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | package de.gsi.dataset.event;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import de.gsi.dataset.utils.DoubleCircularBuffer;
/**
* EventRateLimiter that acts as an {@link EventListener} and forwards the received {@link UpdateEvent}s to a secondary
* {@link EventListener} at a predefined maximum rate. This class may be useful in an UI contexts where the
* visualisation cannot be updated in time due to its numerical complexity, or for contexts where the numerical
* post-processing can be skipped or dropped if new UpdateEvents arrive.
* <p>
* Basic usage:
*
* <pre>
* {@code
* evtSource.addListener(new EventRateLimiter(evt -> { ... do stuff with the event ... }, MAX_UPDATE_PERIOD));
* // or, more explicitly:
* evtSource.addListener(new EventRateLimiter(evt -> { ... do stuff with the event ... }, MAX_UPDATE_PERIOD,
* UpdateStrategy.INSTANTANEOUS_RATE));
* }
* </pre>
*
* @author rstein
*/
public class EventRateLimiter implements EventListener {
private static final int MAX_RATE_BUFFER = 20;
private static final AtomicInteger serialCounter = new AtomicInteger(0);
private final Timer timer = new Timer(EventRateLimiter.class.getSimpleName() + serialCounter.getAndIncrement(), true);
private final AtomicBoolean rateLimitActive = new AtomicBoolean(false);
private final Object lock = new Object();
private final DoubleCircularBuffer rateEstimatorBuffer = new DoubleCircularBuffer(MAX_RATE_BUFFER);
private final EventListener eventListener;
private final long minUpdatePeriod;
private final double maxUpdateRate;
private final UpdateStrategy updateStrategy;
private long lastUpdateMillis;
private UpdateEvent lastUpdateEvent;
/**
* @param eventListener the secondary event listener that should be called if the time-out or rate-limited is not
* activated
* @param minUpdatePeriod the minimum time in milliseconds. With {@link UpdateStrategy#INSTANTANEOUS_RATE} this implies
* a minimum update time-out
* defaults to {@link UpdateStrategy#INSTANTANEOUS_RATE}, see {@link UpdateStrategy} for details
*/
public EventRateLimiter(final EventListener eventListener, final long minUpdatePeriod) {
this(eventListener, minUpdatePeriod, null);
}
/**
* @param eventListener the secondary event listener that should be called if the time-out or rate-limited is not
* activated
* @param minUpdatePeriod the minimum time in milliseconds. With {@link UpdateStrategy#INSTANTANEOUS_RATE} this implies
* a minimum update time-out
* @param updateStrategy if null defaults to {@link UpdateStrategy#INSTANTANEOUS_RATE}, see {@link UpdateStrategy} for
* details
*/
public EventRateLimiter(final EventListener eventListener, final long minUpdatePeriod, final UpdateStrategy updateStrategy) {
super();
lastUpdateMillis = System.currentTimeMillis();
this.eventListener = eventListener;
this.minUpdatePeriod = minUpdatePeriod;
maxUpdateRate = 1000.0 / minUpdatePeriod;
this.updateStrategy = updateStrategy == null ? UpdateStrategy.INSTANTANEOUS_RATE : updateStrategy;
rateEstimatorBuffer.put(lastUpdateMillis);
}
public double getRateEstimate() {
synchronized (lock) {
final long now = System.currentTimeMillis();
if (rateEstimatorBuffer.available() <= 1) {
final long diff = Math.abs(now - lastUpdateMillis);
return diff >= 1 ? 1000.0 / diff : 1.0;
}
double lastUpate = now;
final int nData = rateEstimatorBuffer.available();
double diff = 0.0;
for (int i = 0; i < nData; i++) {
final double timeStamp = rateEstimatorBuffer.get(i);
diff += Math.abs(timeStamp - lastUpate);
lastUpate = timeStamp;
}
final double avgPeriod = diff / nData;
return 2000.0 / avgPeriod;
}
}
@Override
public void handle(UpdateEvent event) {
final long now = System.currentTimeMillis();
synchronized (lock) {
lastUpdateEvent = event;
final long diff = now - lastUpdateMillis;
boolean suppressUpdate = false;
switch (updateStrategy) {
case AVERAGE_RATE:
suppressUpdate = getRateEstimate() > maxUpdateRate;
break;
case INSTANTANEOUS_RATE:
default:
suppressUpdate = diff < minUpdatePeriod;
break;
}
if (suppressUpdate) {
if (rateLimitActive.compareAndSet(false, true)) {
timer.schedule(new DelayedUpdateTask(), minUpdatePeriod);
}
return;
}
rateEstimatorBuffer.put(now);
lastUpdateMillis = now;
}
eventListener.handle(event);
}
/**
* EventRateLimter UpdateStrategy
* <ul>
* <li>{@link #INSTANTANEOUS_RATE} notify if the time w.r.t. the last {@link UpdateEvent} is larger than time threshold
* <li>{@link #AVERAGE_RATE} notify if the average {@link UpdateEvent} rate is smaller than frequency threshold
* </ul>
*
* @author rstein
*/
public enum UpdateStrategy {
INSTANTANEOUS_RATE, // update if diff time w.r.t. the last {@link UpdateEvent} is larger than time threshold
AVERAGE_RATE; // update if the average {@link UpdateEvent} rate is smaller than frequency threshold
}
protected class DelayedUpdateTask extends TimerTask {
@Override
public void run() {
rateLimitActive.set(false);
EventRateLimiter.this.handle(lastUpdateEvent);
}
}
}
| true |
aa9473c647152c8fe0d5344dc33760ca6d353534 | Java | tigresdevelopers/proyecto_empresarial | /Domain/src/main/java/com/network/social/domain/entities/GrupoUsuarioId.java | UTF-8 | 1,839 | 2.4375 | 2 | [] | no_license | package com.network.social.domain.entities;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
*
* @author :Alexander Chavez Simbron
* @date :19/10/2015
* @time :17:25 P.M
*/
@Embeddable
public class GrupoUsuarioId extends BaseBean {
private static final long serialVersionUID = 1L;
private Integer idgrupo;
private Integer idusuario;
public GrupoUsuarioId() {
}
public GrupoUsuarioId(Integer idgrupo, Integer idusuario) {
this.idgrupo = idgrupo;
this.idusuario = idusuario;
}
@Column(name = "IDGRUPO", nullable = false, precision = 22, scale = 0)
public Integer getIdgrupo() {
return this.idgrupo;
}
public void setIdgrupo(Integer idgrupo) {
this.idgrupo = idgrupo;
}
@Column(name = "IDUSUARIO", nullable = false, precision = 22, scale = 0)
public Integer getIdusuario() {
return this.idusuario;
}
public void setIdusuario(Integer idusuario) {
this.idusuario = idusuario;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof GrupoUsuarioId))
return false;
GrupoUsuarioId castOther = (GrupoUsuarioId) other;
return ((this.getIdgrupo() == castOther.getIdgrupo()) || (this.getIdgrupo() != null
&& castOther.getIdgrupo() != null && this.getIdgrupo().equals(castOther.getIdgrupo())))
&& ((this.getIdusuario() == castOther.getIdusuario()) || (this.getIdusuario() != null
&& castOther.getIdusuario() != null && this.getIdusuario().equals(castOther.getIdusuario())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getIdgrupo() == null ? 0 : this.getIdgrupo().hashCode());
result = 37 * result + (getIdusuario() == null ? 0 : this.getIdusuario().hashCode());
return result;
}
}
| true |
2827a222ea2fea124fe120720c64fb1fb37dfcb5 | Java | praghantas/Feb2020Selenium | /src/main/java/SeleniumSessions/RIghtClickUsingByLocator.java | UTF-8 | 1,248 | 2.515625 | 3 | [] | no_license | package SeleniumSessions;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class RIghtClickUsingByLocator {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html");
By rightClickMe = By.xpath("//span[text()='right click me']");
By option = By.xpath("//ul/li[contains(@class,'context-menu-icon')]/span");
ElementUtil elementUtil = new ElementUtil(driver);
WebElement righClick =elementUtil.getElement(rightClickMe);
List<WebElement> optionsList=elementUtil.getElements(option);
List<String> optionsValueList =elementUtil.getRightClickOptions(optionsList, righClick);
System.out.println("the total number of options in the right click menu is:"+optionsValueList.size());
System.out.println("the options values of the right click menu are:"+optionsValueList );
elementUtil.doRightClick(optionsList, righClick, "Copy");
System.out.println("the Copy option got clicked");
}
}
| true |
9dfeab962f87f34ded57e3afb2896d52de46a7bc | Java | junhuac/Firejack-Platform | /platform/src/main/java/net/firejack/platform/service/registry/endpoint/RegistryEndpoint.java | UTF-8 | 59,450 | 1.609375 | 2 | [
"Apache-2.0"
] | permissive | /*
* 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 net.firejack.platform.service.registry.endpoint;
import com.sun.jersey.multipart.FormDataParam;
import net.firejack.platform.api.OPFEngine;
import net.firejack.platform.api.content.domain.FileInfo;
import net.firejack.platform.api.deployment.domain.WebArchive;
import net.firejack.platform.api.registry.domain.*;
import net.firejack.platform.api.registry.domain.Package;
import net.firejack.platform.api.registry.domain.System;
import net.firejack.platform.api.registry.model.PageType;
import net.firejack.platform.core.domain.SimpleIdentifier;
import net.firejack.platform.core.request.ServiceRequest;
import net.firejack.platform.core.response.ServiceResponse;
import net.firejack.platform.core.utils.Paging;
import net.firejack.platform.core.utils.SortOrder;
import net.firejack.platform.core.validation.annotation.DomainType;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@Component
@Path("registry")
public class RegistryEndpoint implements IRegistryEndpoint {
/**
* Check valid url
*
* @param request url data
* @return check result
*/
@POST
@Path("/url/check")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<CheckUrl> testSystemStatus(ServiceRequest<CheckUrl> request) {
return OPFEngine.RegistryService.testSystemStatus(request.getData());
}
/**
* Load sub nodes
*
* @param registryNodeId parent node id
* @param pageType page type
*
* @return children nodes
*/
@GET
@Path("/children/{registryNodeId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> getRegistryNodeChildren(
@PathParam("registryNodeId") Long registryNodeId,
@QueryParam("pageType") PageType pageType,
@QueryParam("packageLookup") String packageLookup) {
return OPFEngine.RegistryService.getRegistryNodeChildren(registryNodeId, pageType, packageLookup);
}
@GET
@Path("/check/{path}/{type}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse checkName(@PathParam("path") String path, @QueryParam("name") String name, @PathParam("type") DomainType type) {
return OPFEngine.RegistryService.checkName(path, name, type);
}
/**
* Load sub tree
*
* @param registryNodeId parent node id
* @param pageType page type
*
* @return all sab tree
*/
@GET
@Path("/children/expanded-by-id/{registryNodeId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> getRegistryNodeWithExpandedByIdChildren(
@PathParam("registryNodeId") Long registryNodeId,
@QueryParam("pageType") PageType pageType) {
return OPFEngine.RegistryService.getRegistryNodeWithExpandedByIdChildren(registryNodeId, pageType);
}
/**
* Load sub tree
*
* @param registryNodeLookup parent node lookup
* @param pageType page type
*
* @return all sub tree
*/
@GET
@Path("/children/expanded-by-lookup/{registryNodeLookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> getRegistryNodeWithExpandedByLookupChildren(
@PathParam("registryNodeLookup") String registryNodeLookup,
@QueryParam("pageType") PageType pageType) {
return OPFEngine.RegistryService.getRegistryNodeWithExpandedByLookupChildren(registryNodeLookup, pageType);
}
/**
* Get all Domains, Entities and Fields for package lookup
*
* @param entityId parent node id
*
* @return all tree nodes
*/
@GET
@Path("/entity-fields/{entityId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> getRegistryNodeFieldsByEntity(@PathParam("entityId") Long entityId) {
return OPFEngine.RegistryService.getRegistryNodeFieldsByEntity(entityId);
}
// CREATE-REQUEST
// /rest/registry/domain --> POST method
/**
* Move nodes in tree
*
* @param request request with move data
*
* @return new position in tree
*/
@PUT
@Path("/change/position")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<MoveRegistryNodeTree> moveRegistryNode(ServiceRequest<MoveRegistryNodeTree> request) {
return OPFEngine.RegistryService.moveRegistryNode(request.getData());
}
/**
* Search tree nodes element
*
* @param term it is a search term
* @param registryNodeId sub tree root id
* @param lookup prefix lookup
* @param assetType type nodes
* @param offset index start element
* @param limit result size
* @param sortColumn sort column name
* @param sortDirection sort direction
*
* @return founded nodes
*/
@GET
@Path("/search")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Search> getSearchResult(
@QueryParam("term") String term,
@QueryParam("registryNodeId") Long registryNodeId,
@QueryParam("lookup") String lookup,
@QueryParam("assetType") String assetType,
@QueryParam("start") Integer offset,
@QueryParam("limit") Integer limit,
@QueryParam("sort") String sortColumn,
@QueryParam("dir") SortOrder sortDirection) {
Paging paging = new Paging(offset, limit, sortColumn, sortDirection);
return OPFEngine.RegistryService.getSearchResult(term, registryNodeId, lookup, assetType, paging);
}
/**
* Retrieves directories from server by provided path
*
* @param path it is a directory path
* @param directoryOnly is directory only
*
* @return founded nodes
*/
@GET
@Path("/filemanager/directory")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<FileTree> readDirectoryStructure(
@QueryParam("path") String path,
@QueryParam("directoryOnly") Boolean directoryOnly) {
return OPFEngine.RegistryService.readDirectory(path, directoryOnly);
}
/**
* Read action by id
*
* @param actionId action Id
*
* @return found action
*/
@GET
@Path("/action/{actionId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Action> readAction(@PathParam("actionId") Long actionId) {
return OPFEngine.RegistryService.readAction(actionId);
}
/**
* Read all actions
*
* @return found actions
*/
@GET
@Path("/action")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Action> readAllActions() {
return OPFEngine.RegistryService.readAllActions();
}
/**
* Found action by lookup
*
* @param packageLookup action lookup
*
* @return found action
*/
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/action/cached/{packageLookup}")
public ServiceResponse<Action> readActionsFromCache(@PathParam("packageLookup") String packageLookup) {
return OPFEngine.RegistryService.readActionsFromCache(packageLookup);
}
// CREATE-REQUEST:
// /rest/registry/action --> POST method
// this differs from the domain create, because it also adds all the fields for the action. Fields are only saved when the entire action is saved so the administrator can work with and test the configurations before saving.
/**
* Create new action
*
* @param request Action data
*
* @return created action
*/
@POST
@Path("/action")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createAction(ServiceRequest<Action> request) {
return OPFEngine.RegistryService.createAction(request.getData());
}
// UPDATE-REQUEST:
// /rest/registry/action/[id] --> PUT method
/**
* Update Action by id
*
* @param id action id
* @param request action data
*
* @return updated action
*/
@PUT
@Path("/action/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateAction(
@PathParam("id") Long id, ServiceRequest<Action> request) {
return OPFEngine.RegistryService.updateAction(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/action/[id] --> DELETE method
/**
* Delete Action by Id
*
* @param id action d
*
* @return deleted action
*/
@DELETE
@Path("/action/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Action> deleteAction(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteAction(id);
}
// READ-ONE-REQUEST:
// /rest/registry/domain/[id] --> GET method
/**
* Read domain by id
*
* @param id domain id
*
* @return founded domain
*/
@GET
@Path("/domain/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Domain> readDomain(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readDomain(id);
}
// READ-ALL-REQUEST:
// /rest/registry/domain --> GET method
/**
* Read all domains
*
* @return founded domains
*/
@GET
@Path("/domain")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Domain> readAllDomains() {
return OPFEngine.RegistryService.readAllDomains();
}
// CREATE-REQUEST
// /rest/registry/domain --> POST method
/**
* Create new domain
*
* @param request domain data
*
* @return created domain
*/
@POST
@Path("/domain")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createDomain(ServiceRequest<Domain> request) {
return OPFEngine.RegistryService.createDomain(request.getData());
}
//TODO need to add to package.xml
@POST
@Path("/domain/parent-lookup")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Domain> createDomainByParentLookup(ServiceRequest<Domain> request) {
return OPFEngine.RegistryService.createDomainByParentLookup(request.getData());
}
/**
* Service creates domain and database and can do reverse engineering
*
* @param request - request containing the domain with database to be created
* @param reverseEngineer - if true then reverse engineer data
*
* @return domain with newly created database
*/
@POST
@Path("/domain/database")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Domain> createDomainDatabase(ServiceRequest<Domain> request,
@QueryParam("reverseEngineer") Boolean reverseEngineer) {
return OPFEngine.RegistryService.createDomainDatabase(request.getData(), reverseEngineer);
}
// UPDATE-REQUEST
// /rest/registry/domain/[id] --> PUT method
/**
* Updated domain by id
*
* @param id domain id
* @param request domain data
*
* @return updated domain
*/
@PUT
@Path("/domain/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateDomain(@PathParam("id") Long id, ServiceRequest<Domain> request) {
return OPFEngine.RegistryService.updateDomain(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/domain/[id] --> DELETE method
/**
* Delete domain by id
*
* @param id domain id
*
* @return deleted domain
*/
@DELETE
@Path("/domain/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Domain> deleteDomain(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteDomain(id);
}
@GET
@Path("/domains/by-lookup/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Domain> readDomainsByPackageLookup(@PathParam("lookup") String lookup) {
return OPFEngine.RegistryService.readDomainsByPackageLookup(lookup);
}
// READ-ONE-REQUEST:
// /rest/registry/entity/[id] --> GET method
// note: this will bring back the fields for the entity as well.
/**
* Read entity By Id
*
* @param id entity id
*
* @return founded entity
*/
@GET
@Path("/entity/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Entity> readEntity(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readEntity(id);
}
/**
* Read entity By Lookup
* @param entityLookup entity lookup
*
* @return entity with specified lookup if found. Otherwise null
*/
@GET
@Path("/entity/by-lookup/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Override
public ServiceResponse<Entity> readEntityByLookup(@PathParam("lookup") String entityLookup) {
return OPFEngine.RegistryService.readEntityByLookup(entityLookup);
}
//todo need to describe it in package.xml
/**
* Search entity By Domain
* @param terms
*
* @return entity with specified lookup if found. Otherwise null
*/
@GET
@Path("/entity/search")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Override
public ServiceResponse<Entity> searchEntityByDomain(
@QueryParam("terms") String terms,
@QueryParam("domainId") Long domainId,
@QueryParam("packageLookup") String packageLookup) {
return OPFEngine.RegistryService.searchEntityByDomain(terms, domainId, packageLookup);
}
/**
* Read entity By Lookup
* @param entityLookup entity lookup
*
* @return entity with specified lookup if found. Otherwise null
*/
@GET
@Path("/entity/parent-types/by-lookup/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Override
public ServiceResponse<Entity> readParentEntityTypesByEntityLookup(@PathParam("lookup") String entityLookup) {
return OPFEngine.RegistryService.readParentEntityTypesByEntityLookup(entityLookup);
}
@GET
@Path("/entity/direct-children-types-by-lookup")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Override
public ServiceResponse<Entity> readDirectChildrenTypes(@QueryParam("entityLookup") String entityLookup) {
return OPFEngine.RegistryService.readDirectChildrenTypes(entityLookup);
}
/**
* Read entity By Lookup
* @param entityLookup entity lookup
*
* @return entity with specified lookup if found. Otherwise null
*/
@GET
@Path("/entity/hierarchy-types-up/by-lookup/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Override
public ServiceResponse<Entity> readEntitiesFromHierarchyByEntityLookup(@PathParam("lookup") String entityLookup) {
return OPFEngine.RegistryService.readEntitiesUpInHierarchyByLookup(entityLookup);
}
/**
* Read all entities by type and super entity
*
* @param type entity type
* @param exceptId extended entity id
*
* @return founded entities
*/
@GET
@Path("/entity/{type:(standard|classifier|data|security-enabled)}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Entity> readAllEntities(@PathParam("type") String type, @QueryParam("exceptId") Long exceptId) {
return OPFEngine.RegistryService.readAllEntities(type, exceptId);
}
@GET
@Path("/entities/by-lookup/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Entity> readEntitiesByPackageLookup(@PathParam("lookup") String lookup) {
return OPFEngine.RegistryService.readEntitiesByPackageLookup(lookup);
}
// CREATE-REQUEST:
// /rest/registry/entity --> POST method
// this differs from the domain create, because it also adds all the fields for the entity. Fields are only saved when the entire entity is saved so the administrator can work with and test the configurations before saving.
/**
* Create new entity
*
* @param request entity data
*
* @return created entity
*/
@POST
@Path("/entity")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createEntity(ServiceRequest<Entity> request) {
return OPFEngine.RegistryService.createEntity(request.getData());
}
// UPDATE-REQUEST:
// /rest/registry/entity/[id] --> PUT method
/**
* Updated entity by id
*
* @param id entity id
* @param request entity data
*
* @return updated entity
*/
@PUT
@Path("/entity/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateEntity(@PathParam("id") Long id, ServiceRequest<Entity> request) {
return OPFEngine.RegistryService.updateEntity(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/entity/[id] --> DELETE method
/**
* Delete entity by id
*
* @param id entity id
*
* @return deleted entity
*/
@DELETE
@Path("/entity/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Entity> deleteEntity(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteEntity(id);
}
//todo need to add to package.xml
@POST
@Path("/form")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Form> createForm(ServiceRequest<Form> request) {
return OPFEngine.RegistryService.createForm(request.getData());
}
@GET
@Path("/entity/by-type/{entityTypeId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<SecuredEntity> getSecuredEntitiesByType(@PathParam("entityTypeId") Long entityTypeId) {
return OPFEngine.RegistryService.readSecuredEntitiesByType(entityTypeId);
}
@GET
@Path("/entity/security-enabled-by-lookup")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<SimpleIdentifier<Boolean>> getSecurityEnabledFlagForEntity(
@QueryParam("entityLookup") String entityLookup) {
return OPFEngine.RegistryService.getSecurityEnabledFlagForEntity(entityLookup);
}
/**
* Upload package archive (*.ofr)
*
* @param inputStream stream data
*
* @return Information about uploaded package
*
* @throws java.io.IOException Can't serialized response data
*/
//todo: not valid in terms of OPF action abstraction
@POST
@Path("/installation/package/upload")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadPackageArchive(@FormDataParam("file") InputStream inputStream) throws IOException {
ServiceResponse<UploadPackageArchive> response = OPFEngine.RegistryService.uploadPackageArchive(inputStream);
String responseData = (new ObjectMapper()).writeValueAsString(response);
return Response.ok(responseData).type(MediaType.TEXT_HTML_TYPE).build();
}
public ServiceResponse<UploadPackageArchive> uploadPackageArchive(FileInfo info) {
return OPFEngine.RegistryService.uploadPackageArchive(info.getStream());
}
/**
* Installed uploaded package archive
*
* @param uploadedFilename uploaded file name
* @param versionName version name
* @param doAsCurrent setup current version
* @param doArchive setup archive version
*
* @return complete result
*/
@GET
@Path("/installation/package/perform")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse performPackageArchive(
@QueryParam("uploadedFilename") String uploadedFilename,
@QueryParam("versionName") String versionName,
@QueryParam("doAsCurrent") Boolean doAsCurrent,
@QueryParam("doArchive") Boolean doArchive) {
return OPFEngine.RegistryService.performPackageArchive(uploadedFilename, versionName, doAsCurrent, doArchive);
}
/**
* Check unique package version
*
* @param packageId package id
* @param versionName version name
*
* @return complete result
*/
@GET
@Path("/installation/package/check/unique/version/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse checkUniquePackageVersion(
@PathParam("packageId") Long packageId,
@QueryParam("versionName") String versionName) {
return OPFEngine.RegistryService.checkUniquePackageVersion(packageId, versionName);
}
/**
* Install package archive to remote server
*
* @return install logs
*/
@POST
@Path("/installation/package/install")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse installPackageArchive(ServiceRequest<PackageAction> request) {
return OPFEngine.RegistryService.installPackageArchive(request.getData());
}
@POST
@Path("/installation/package/migrate")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse migrateDatabase(ServiceRequest<PackageAction> request) {
return OPFEngine.RegistryService.migrateDatabase(request.getData());
}
/**
* Uninstall package archive with remote server
*
* @return complete result
*/
@POST
@Path("/installation/package/uninstall")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse uninstallPackageArchive(ServiceRequest<PackageAction> request) {
return OPFEngine.RegistryService.uninstallPackageArchive(request.getData());
}
@GET
@Path("/installation/package/redeploy/{packageLookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse redeployPackageArchive(@PathParam("packageLookup") String packageLookup) {
return OPFEngine.RegistryService.redeployPackageArchive(packageLookup);
}
// READ-ONE-REQUEST:
// /rest/registry/package/[id] ?version=[version]--> GET method
/**
* Read package by id
*
* @param id package id
*
* @return founded package
*/
@GET
@Path("/package/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Package> readPackage(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readPackage(id);
}
// READ-ALL-REQUEST:
// /rest/registry/package --> GET method
/**
* Read all packages
*
* @return founded packages
*/
@GET
@Path("/package")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Package> readAllPackages() {
return OPFEngine.RegistryService.readAllPackages();
}
// CREATE-REQUEST:
// /rest/registry/package --> POST method
/**
* Create new package
*
* @param request package data
*
* @return created package
*/
@POST
@Path("/package")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createPackage(ServiceRequest<Package> request) {
return OPFEngine.RegistryService.createPackage(request.getData());
}
// UPDATE-REQUEST:
// /rest/registry/package/[id] --> PUT method
// note this is different than the domain update method (slightly) because it allows the "current-version" field to be set. "current-version" is null for all other types of nodes.
/**
* Update package by id
*
* @param id package id
* @param request package data
*
* @return updated package
*/
@PUT
@Path("/package/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updatePackage(@PathParam("id") Long id, ServiceRequest<Package> request) {
return OPFEngine.RegistryService.updatePackage(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/package/[id] --> DELETE method
/**
* Delete package by id
*
* @param id package id
*
* @return deleted package
*/
@DELETE
@Path("/package/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Package> deletePackage(@PathParam("id") Long id) {
return OPFEngine.RegistryService.deletePackage(id);
}
/**
* Download package archive
*
* @param packageId package id
* @param packageFilename downloaded file name
*
* @return stream data
*/
//todo: not valid in terms of OPF action abstraction
@GET
@Path("/package/download/{packageId}/{packageFilename}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public StreamingOutput getPackageArchive(@PathParam("packageId") final Long packageId, @PathParam("packageFilename") final String packageFilename) {
return new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
InputStream stream = OPFEngine.RegistryService.getPackageArchive(packageId, packageFilename);
if (stream != null) {
IOUtils.copy(stream, output);
IOUtils.closeQuietly(stream);
}
}
};
}
public ServiceResponse<FileInfo> getPackageArchiveWS(Long packageId, String packageFilename) {
InputStream stream = OPFEngine.RegistryService.getPackageArchive(packageId, packageFilename);
return new ServiceResponse<FileInfo>(new FileInfo(packageFilename, stream), "Package archive successfully", true);
}
/**
* Generate project source and war archive
*
* @param packageId package id
*
* @return generation package info
*/
@GET
@Path("/package/generate/code/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<PackageVersion> generateWar(@PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.generateWar(packageId);
}
/**
* Generate upgrade xml
*
* @param packageId package id
* @param version other version
*
* @return generation package info
*/
@GET
@Path("/package/generate/upgrade/{packageId}/{version}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<PackageVersion> generateUpgradeXml(@PathParam("packageId") Long packageId, @PathParam("version") Integer version) {
return OPFEngine.RegistryService.generateUpgradeXml(packageId, version);
}
/**
* Get package version info
*
* @param packageId package id
*
* @return founded version info
*/
@GET
@Path("/package/versions/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<PackageVersionInfo> getPackageVersionsInfo(@PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.getPackageVersionsInfo(packageId);
}
/**
* Lock/Unlock package version
*
* @param packageId package id
* @param request package version data
*
* @return package data
*/
@PUT
@Path("/package/lock/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Package> lockPackageVersion(@PathParam("packageId") Long packageId, ServiceRequest<PackageVersionInfo> request) {
return OPFEngine.RegistryService.lockPackageVersion(packageId, request.getData());
}
/**
* This method exports the xml for all nodes and data beneath the package and associates it with the newly created version.
* It also updates the current version field once the new version is created.
* <p/>
* CREATE-VERSION-REQUEST: /rest/registry/package --> GET method
*
* @param packageId - Long
*
* @return - PackageVersionVO
*/
@GET
@Path("/package/archive/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<PackageVersion> archive(@PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.archive(packageId);
}
/**
* Delete package version
*
* @param packageId package id
* @param version removed version
*
* @return package data
*/
@DELETE
@Path("/package/version/{packageId}/{version}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Package> deletePackageVersion(@PathParam("packageId") Long packageId, @PathParam("version") Integer version) {
return OPFEngine.RegistryService.deletePackageVersion(packageId, version);
}
/**
* Activate old package version
*
* @param packageId package id
* @param version activate version
*
* @return complete result
*/
@GET
@Path("/package/activate/{packageId}/{version}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse activatePackageVersion(@PathParam("packageId") Long packageId, @PathParam("version") Integer version) {
return OPFEngine.RegistryService.activatePackageVersion(packageId, version);
}
/**
* Supported other version in current
*
* @param packageId package id
* @param version supported version
*
* @return complete result
*/
@GET
@Path("/package/support/{packageId}/{version}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse supportPackageVersion(@PathParam("packageId") Long packageId, @PathParam("version") Integer version) {
return OPFEngine.RegistryService.supportPackageVersion(packageId, version);
}
/**
* This takes one parameter, a file to add to the current version of the package.
* It places the code file on the file system and updates the version's code file location field accordingly.
* <p/>
* UPLOAD-VERSION-CODE-REQUEST: /rest/registry/package/version/[package-id]/[package-version-id]/[xml|war|zip] --> POST method
*
* @param fileType - String, one of values: xml|war|zip
* @param packageId - Long
* @param inputStream - uploaded file
*
* @return - Response with text/html type
*
* @throws java.io.IOException can't serialize response data
*/
@POST
@Path("/package/version/{packageId}/{fileType: (xml|war|zip)}")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
//todo: not valid in terms of OPF action abstraction
public Response uploadPackageVersionXML(
@PathParam("fileType") String fileType,
@PathParam("packageId") Long packageId,
@FormDataParam("file") InputStream inputStream) throws IOException {
ServiceResponse response = OPFEngine.RegistryService.uploadPackageVersionXML(packageId, fileType, inputStream);
ObjectMapper mapper = new ObjectMapper();
String responderData = mapper.writeValueAsString(response);
return Response.ok(responderData).type(MediaType.TEXT_HTML_TYPE).build();
}
public ServiceResponse<PackageVersion> uploadPackageVersionXML(String fileType, Long packageId, FileInfo info) {
return OPFEngine.RegistryService.uploadPackageVersionXML(packageId, fileType, info.getStream());
}
/**
* This should associate a database with the appropriate package in the registry.
*
* @param packageId package id
* @param databaseId database id
*
* @return complete result
*/
@POST
@Path("/package/associate-database/{packageId}/{databaseId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse associateDatabase(@PathParam("packageId") Long packageId, @PathParam("databaseId") Long databaseId) {
return OPFEngine.RegistryService.associateDatabase(packageId, databaseId);
}
/**
* @param registryNodeId - Long
*
* @return - PackageVO
*/
@GET
@Path("/reverse-engineering/{registryNodeId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Package> reverseEngineering(@PathParam("registryNodeId") Long registryNodeId) {
return OPFEngine.RegistryService.reverseEngineering(registryNodeId);
}
// READ-ONE-REQUEST:
// /rest/registry/relationship/[id] --> GET method
/**
* Read relationship by id
*
* @param id relationship id
*
* @return founded relationship
*/
@GET
@Path("/relationship/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Relationship> readRelationship(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readRelationship(id);
}
// READ-ALL-REQUEST:
// /rest/registry/relationship --> GET method
/**
* Read all relationships
*
* @return founded relationships
*/
@GET
@Path("/relationship")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Relationship> readAllRelationships() {
return OPFEngine.RegistryService.readAllRelationships();
}
// CREATE-REQUEST:
// /rest/registry/relationship --> POST method
/**
* Create new relationship
*
* @param request relationship data
*
* @return created relationship
*/
@POST
@Path("/relationship")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createRelationship(ServiceRequest<Relationship> request) {
return OPFEngine.RegistryService.createRelationship(request.getData());
}
// UPDATE-REQUEST:
// /rest/registry/relationship/[id] --> PUT method
/**
* Updated relationship by id
*
* @param id relationship id
* @param request relationship data
*
* @return updated relationship
*/
@PUT
@Path("/relationship/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateRelationship(
@PathParam("id") Long id, ServiceRequest<Relationship> request) {
return OPFEngine.RegistryService.updateRelationship(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/relationship/[id] --> DELETE method
/**
* Delete relationship by id
*
* @param id relationship id
*
* @return deleted relationship
*/
@DELETE
@Path("/relationship/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Relationship> deleteRelationship(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteRelationship(id);
}
/**
* Service retrieves the root_domain
*
* @param id - ID of the root_domain
*
* @return found root_domain
*/
@GET
@Path("/root_domain/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RootDomain> readRootDomain(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readRootDomain(id);
}
/**
* Read all root domains
*
* @return founded root domains
*/
@GET
@Path("/root_domain")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RootDomain> readAllRootDomains() {
return OPFEngine.RegistryService.readAllRootDomains();
}
// CREATE-REQUEST
// /rest/registry/domain --> POST method
/**
* Create new root domain
*
* @param request root domain data
*
* @return created root domain
*/
@POST
@Path("/root_domain")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createRootDomain(ServiceRequest<RootDomain> request) {
return OPFEngine.RegistryService.createRootDomain(request.getData());
}
// UPDATE-REQUEST
// /rest/registry/domain/[id] --> PUT method
/**
* Update root domain by id
*
* @param id domain id
* @param request root domain data
*
* @return updated root domain
*/
@PUT
@Path("/root_domain/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateRootDomain(
@PathParam("id") Long id, ServiceRequest<RootDomain> request) {
return OPFEngine.RegistryService.updateRootDomain(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/domain/[id] --> DELETE method
/**
* Delete root domain
*
* @param id root domain id
*
* @return deleted root domain
*/
@DELETE
@Path("/root_domain/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RootDomain> deleteRootDomain(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteRootDomain(id);
}
// READ-ONE-REQUEST:
// /rest/registry/system/[id] --> GET method
/**
* Restart self system
*
* @return restart status
*/
@GET
@Path("/system/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<System> readSystem(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readSystem(id);
}
@GET
@Path("/system/status/war/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<WebArchive> readWarStatus(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readWarStatus(id);
}
/**
* Restart self system
*
* @return restart status
*/
@GET
@Path("/system/restart")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse restart() {
return OPFEngine.RegistryService.restart();
}
/**
* Ping self system
*
* @return ping status
*/
@GET
@Path("/system/ping")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse ping() {
return OPFEngine.RegistryService.ping();
}
/**
* Read all system
*
* @return founded systems
*/
@GET
@Path("/system")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<System> readAllSystems(@QueryParam("aliases") Boolean aliases) {
return OPFEngine.RegistryService.readAllSystems(aliases);
}
// CREATE-REQUEST
// /rest/registry/system --> POST method
/**
* Create new system
*
* @param request system data
*
* @return created system
*/
@POST
@Path("/system")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createSystem(ServiceRequest<System> request) {
return OPFEngine.RegistryService.createSystem(request.getData());
}
// UPDATE-REQUEST
// /rest/registry/system/[id] --> PUT method
/**
* Update system by id
*
* @param id system id
* @param request system data
*
* @return updated system
*/
@PUT
@Path("/system/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateSystem(
@PathParam("id") Long id, ServiceRequest<System> request) {
return OPFEngine.RegistryService.updateSystem(id, request.getData());
}
// DELETE-REQUEST:
// /rest/registry/system/[id] --> DELETE method
/**
* Delete system by id
*
* @param id system id
*
* @return deleted system
*/
@DELETE
@Path("/system/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<System> deleteSystem(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteSystem(id);
}
// ASSOCIATE-PACKAGE
// /platform/registry/registry-node/system/[system-id]/package/[package-id] - POST Method
// This should associate a package with the appropriate system in the registry and set all package server names to the system server name.
/**
* Associate package on system
*
* @param systemId system id
* @param packageId package id
*
* @return complete result
*/
@POST
@Path("/system/installed-package/{systemId}/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse associatePackage(@PathParam("systemId") Long systemId, @PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.associatePackage(systemId, packageId);
}
// REMOVE-ASSOCIATION
// ASSOCIATE-PACKAGE
// /platform/registry/registry-node/system/[system-id]/package/[package-id] - DELETE Method
/**
* Remove associate package with system
*
* @param systemId system id
* @param packageId package id
*
* @return complete result
*/
@DELETE
// @Path("/registry-node/system/{systemId}/package/{packageId}")
@Path("/system/installed-package/{systemId}/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse removeAssociationPackage(@PathParam("systemId") Long systemId, @PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.removeAssociationPackage(systemId, packageId);
}
/**
* Export system environments
*
* @param rootDomainId root domain id
* @param filename download file name
*
* @return stream data
*/
@GET
@Path("/system/export/{name}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
//todo: not valid in terms of OPF action abstraction
public StreamingOutput exportXml(
@QueryParam("rootDomainId") final Long rootDomainId,
@PathParam("name") final String filename) {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
InputStream stream = OPFEngine.RegistryService.exportXml(rootDomainId, filename);
if (stream != null) {
IOUtils.copy(stream, output);
IOUtils.closeQuietly(stream);
}
}
};
}
public ServiceResponse<FileInfo> exportXmlWS(Long rootDomainId, String filename) {
InputStream stream = OPFEngine.RegistryService.exportXml(rootDomainId, filename);
return new ServiceResponse<FileInfo>(new FileInfo(filename, stream), "Export xml successfully", true);
}
/**
* Upload system environments
*
* @param rootDomainId root domain rootDomainId
* @param inputStream stream data
*
* @return complete result
*
* @throws java.io.IOException can't serialize response data
*/
@POST
@Path("/system/import")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
//todo: not valid in terms of OPF action abstraction
public Response importXml(@QueryParam("rootDomainId") Long rootDomainId, @FormDataParam("file") InputStream inputStream)
throws IOException {
ServiceResponse response = OPFEngine.RegistryService.importXml(rootDomainId, inputStream);
ObjectMapper mapper = new ObjectMapper();
String responderData = mapper.writeValueAsString(response);
return Response.ok(responderData).type(MediaType.TEXT_HTML_TYPE).build();
}
public ServiceResponse importXml(Long rootDomainId, FileInfo info) {
return OPFEngine.RegistryService.importXml(rootDomainId, info.getStream());
}
/**
* Service retrieves the database
*
* @param id - ID of the database
*
* @return found database
*/
@GET
@Path("/database/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Database> readDatabase(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readDatabase(id);
}
/**
* Service searches the databases by associated package
*
* @param packageId - ID of the package
*
* @return list of found databases
*/
@GET
@Path("/database/associated-system/package/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Database> readDatabasesBySystem(@PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.readDatabasesBySystem(packageId);
}
/**
* Service searches the databases by associated package
*
* @param packageId - ID of the package
*
* @return list of found databases
*/
@GET
@Path("/database/associated-package/{packageId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Database> readDatabasesByPackage(@PathParam("packageId") Long packageId) {
return OPFEngine.RegistryService.readDatabasesByPackage(packageId);
}
/**
* Service searches the not-associated databases
*
* @return list of found databases
*/
@GET
@Path("/database/not-associated")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Database> readNotAssociatedDatabases() {
return OPFEngine.RegistryService.readNotAssociatedDatabases();
}
/**
* Service inserts the database
*
* @param request - request containing the database to be inserted
*
* @return registry tree node with newly created database
*/
@POST
@Path("/database")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createDatabase(ServiceRequest<Database> request) {
return OPFEngine.RegistryService.createDatabase(request.getData());
}
/**
* Service modifies the database
*
* @param id - ID of the database
* @param request - request containing the database to be modified
*
* @return registry tree node with modified database
*/
@PUT
@Path("/database/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateDatabase(
@PathParam("id") Long id, ServiceRequest<Database> request) {
return OPFEngine.RegistryService.updateDatabase(id, request.getData());
}
/**
* Service removes the database
*
* @param id - ID of the database to be removed
*
* @return database value object
*/
@DELETE
@Path("/database/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Database> deleteDatabase(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteDatabase(id);
}
/**
* Service reads the filestore
*
* @param id - ID of the filestore
*
* @return read filestore
*/
@GET
@Path("/filestore/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Filestore> readFilestore(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readFilestore(id);
}
/**
* Service creates the filestore
*
* @param request - request containing the filestore to be created
*
* @return registry node tree for filestore
*/
@POST
@Path("/filestore")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createFilestore(ServiceRequest<Filestore> request) {
return OPFEngine.RegistryService.createFilestore(request.getData());
}
/**
* Service updates the filestore
*
* @param id - ID of the filestore
* @param request - request containing the filestore to be updated
*
* @return registry node tree for filestore
*/
@PUT
@Path("/filestore/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateFilestore(
@PathParam("id") Long id, ServiceRequest<Filestore> request) {
return OPFEngine.RegistryService.updateFilestore(id, request.getData());
}
/**
* Service deletes the filestore
*
* @param id - ID of the filestore to be deleted
*
* @return filestore value object
*/
@DELETE
@Path("/filestore/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Filestore> deleteFilestore(@PathParam(value = "id") Long id) {
return OPFEngine.RegistryService.deleteFilestore(id);
}
/**
* Read server by id
*
* @param id server id
*
* @return founded server
*/
@GET
@Path("/server/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Server> readServer(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readServer(id);
}
/**
* Create new Server
*
* @param request server data
*
* @return created server
*/
@POST
@Path("/server")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createServer(ServiceRequest<Server> request) {
return OPFEngine.RegistryService.createServer(request.getData());
}
/**
* Update server by id
*
* @param id server id
* @param request server data
*
* @return updated server
*/
@PUT
@Path("/server/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateServer(@PathParam("id") Long id, ServiceRequest<Server> request) {
return OPFEngine.RegistryService.updateServer(id, request.getData());
}
/**
* Delete server by id
*
* @param id server id
*
* @return deleted server
*/
@DELETE
@Path("/server/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Server> deleteServer(@PathParam("id") Long id) {
return OPFEngine.RegistryService.deleteServer(id);
}
@POST
@Path("/register-node")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse registerServerNode(ServiceRequest<ServerNodeConfig> request) {
return OPFEngine.RegistryService.registerServerNode(request.getData());
}
/**
* registration Slave Nodes
*
* @param config configuration slave node
* @return server environments
*/
@POST
@Path("/slave")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public StreamingOutput registerSlaveNode(final ServiceRequest<ServerNodeConfig> config) {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
InputStream env = OPFEngine.RegistryService.registerSlaveNode(config.getData());
if (env != null) {
IOUtils.copy(env, output);
IOUtils.closeQuietly(env);
}
}
};
}
@GET
@Path("/report/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Report> readReport(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readReport(id);
}
@POST
@Path("/report")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createReport(ServiceRequest<Report> request) {
return OPFEngine.RegistryService.createReport(request.getData());
}
@PUT
@Path("/report/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateReport(@PathParam("id") Long id, ServiceRequest<Report> request) {
return OPFEngine.RegistryService.updateReport(id, request.getData());
}
@DELETE
@Path("/report/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Report> deleteReport(@PathParam("id") Long id) {
return OPFEngine.RegistryService.deleteReport(id);
}
@GET
@Path("/wizard/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Wizard> readWizard(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readWizard(id);
}
@POST
@Path("/wizard")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createWizard(ServiceRequest<Wizard> request) {
return OPFEngine.RegistryService.createWizard(request.getData());
}
@PUT
@Path("/wizard/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> updateWizard(@PathParam("id") Long id, ServiceRequest<Wizard> request) {
return OPFEngine.RegistryService.updateWizard(id, request.getData());
}
@DELETE
@Path("/wizard/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Wizard> deleteWizard(@PathParam("id") Long id) {
return OPFEngine.RegistryService.deleteWizard(id);
}
@GET
@Path("/license")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<License> readLicense() {
return OPFEngine.RegistryService.readLicense();
}
@POST
@Path("/license")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response verifyLicense(@FormDataParam("file") InputStream inputStream) throws IOException {
ServiceResponse<License> response = OPFEngine.RegistryService.verify(inputStream);
ObjectMapper mapper = new ObjectMapper();
String responderData = mapper.writeValueAsString(response);
return Response.ok(responderData).type(MediaType.TEXT_HTML_TYPE).build();
}
public ServiceResponse verifyLicenseWS(FileInfo info) {
return OPFEngine.RegistryService.verify(info.getStream());
}
@GET
@Path("/social/{packageLookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<Social> socialEnabled(@PathParam("packageLookup") String packageLookup) {
return OPFEngine.RegistryService.socialEnabled(packageLookup);
}
@GET
@Path("/bi/report/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReport> readBIReport(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readBIReport(id);
}
@GET
@Path("/bi/report-user/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReportUser> readBIReportUser(@PathParam("id") Long id) {
return OPFEngine.RegistryService.readBIReportUser(id);
}
@DELETE
@Path("/bi/report-user/{id}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReportUser> deleteBIReportUser(@PathParam("id") Long id) {
return OPFEngine.RegistryService.deleteBIReportUser(id);
}
@GET
@Path("/bi/report-user/allow/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReportUser> readAllowBIReportUser(@PathParam("lookup") String packageLookup) {
return OPFEngine.RegistryService.readAllowBIReportUser(packageLookup);
}
@GET
@Path("/bi/report/lookup/{lookup}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReport> readBIReportByLookup(@PathParam("lookup") String lookup) {
return OPFEngine.RegistryService.readBIReportByLookup(lookup);
}
@POST
@Path("/bi/report")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<RegistryNodeTree> createBIReport(ServiceRequest<BIReport> request) {
return OPFEngine.RegistryService.createBIReport(request.getData());
}
@POST
@Path("/bi/report-user")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReportUser> createBIReportUser(ServiceRequest<BIReportUser> request) {
return OPFEngine.RegistryService.createBIReportUser(request.getData());
}
@PUT
@Path("/bi/report-user/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public ServiceResponse<BIReportUser> updateBIReportUser(@PathParam("id") Long id, ServiceRequest<BIReportUser> request) {
return OPFEngine.RegistryService.updateBIReportUser(id, request.getData());
}
} | true |
27a41ad1393485b0cb0aebf4a6e8931502bab743 | Java | Svetus927/javahomework | /rest-sample/src/test/java/tests/TestBase.java | UTF-8 | 1,918 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | package tests;
import application.ApplicationManager;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
/**
* Created on 11/12/2017.
*/
public class TestBase {
protected static final ApplicationManager app = new ApplicationManager(System.getProperty("browser")); // в Edit Configurations указ пар р VM machine: -ea -dBrowser=firefox
// второе значение задает значение браузера по умолчанию
@BeforeClass
public void setUp() throws Exception {
app.init();
}
@AfterClass
public void tearDown() throws IOException {
app.stop();
}
// ** Функция которая проверяет в начале теста, исправлен ли баг по этому тесту в багтрекере мантис ** //
public void skipIfNotFixed(int issueId) throws IOException {
if (issueOpen(issueId)) {
throw new SkipException("Test ignored because of issue " + issueId);
}
}
/*
В классе TestBase, от которого наследуются все тесты, необходимо реализовать функцию boolean isIssueOpen(int issueId) ,
которая должна через Remote API получать из баг-трекера информацию о баг-репорте с заданным идентификатором,
и возвращать значение false или true в зависимости от того, помечен он как исправленный или нет.
*/
private boolean issueOpen (int issueId) throws IOException {
return (app.restHelper().isIssueOpen(issueId));
}
}
| true |
6f4752d674a1f1a94d5e8ad8989749acab345c41 | Java | UncileMovieBrick/saas-boot | /src/main/java/com/gs/service/impl/MenuServiceImpl.java | UTF-8 | 443 | 1.53125 | 2 | [] | no_license | package com.gs.service.impl;
import com.gs.entity.Menu;
import com.gs.mapper.MenuMapper;
import com.gs.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 菜单表 服务实现类
* </p>
*
* @author gongsong
* @since 2020-11-10
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
}
| true |
7d4ef6a2d33cc097bb51260f73878a67ee9cd058 | Java | jimolonely/MyCost | /android-app/app/src/main/java/com/jimo/mycost/func/life/LifeItemSearchResult.java | UTF-8 | 1,734 | 2.46875 | 2 | [] | no_license | package com.jimo.mycost.func.life;
public class LifeItemSearchResult {
private String imgUrl;
private String title;
private String type;//对应主题的类型,比如电影有科幻,爱情等,书籍有文学,科学等
private String creators;//书的作者或电影导演
private String pubdate;//上映时间
private String rating;//豆瓣评分 7.5/10
private String remark;//其他备注,书籍的页数,出版社,梗概,电影的演员
public LifeItemSearchResult(String imgUrl, String title, String type, String creators,
String pubdate, String remark, String rating) {
this.imgUrl = imgUrl;
this.title = title;
this.type = type;
this.creators = creators;
this.pubdate = pubdate;
this.remark = remark;
this.rating = rating;
}
public String getType() {
return type;
}
public String getCreators() {
return creators;
}
public String getPubdate() {
return pubdate;
}
public String getRemark() {
return remark;
}
public String getRating() {
return rating;
}
public String getImgUrl() {
return imgUrl;
}
public String getTitle() {
return title;
}
@Override
public String toString() {
return "LifeItemSearchResult{" +
"imgUrl='" + imgUrl + '\'' +
", title='" + title + '\'' +
", type='" + type + '\'' +
", creators='" + creators + '\'' +
", pubdate='" + pubdate + '\'' +
", rating='" + rating + '\'' +
", remark='" + remark + '\'' +
'}';
}
}
| true |
6a42dd1f885ed7775447108d7c4b7dc80136800a | Java | laurentkeil/lil-g3r | /src/com/mdl/parserSS/PickupType.java | UTF-8 | 14,021 | 1.5 | 2 | [] | no_license | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.14 at 04:24:38 PM CET
//
package com.mdl.parserSS;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>
* Java class for pickupType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="pickupType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="pickupaddress" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}addressType"/>
* <element name="billingaddress" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}addressType" minOccurs="0"/>
* <element name="deliveryaddress" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}addressType"/>
* <element name="pickupcenter">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Li�ge"/>
* <enumeration value="Hasselt"/>
* <enumeration value="Arlon"/>
* <enumeration value="Namur"/>
* <enumeration value="Mons"/>
* <enumeration value="Wavre"/>
* <enumeration value="Louvain"/>
* <enumeration value="Gand"/>
* <enumeration value="Anvers"/>
* <enumeration value="Bruges"/>
* <enumeration value="A�roport-Bruxelles"/>
* <enumeration value="A�roport-Li�ge"/>
* </restriction>
* </simpleType>
* </element>
* <element name="deliverycenter">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Li�ge"/>
* <enumeration value="Hasselt"/>
* <enumeration value="Arlon"/>
* <enumeration value="Namur"/>
* <enumeration value="Mons"/>
* <enumeration value="Wavre"/>
* <enumeration value="Louvain"/>
* <enumeration value="Gand"/>
* <enumeration value="Anvers"/>
* <enumeration value="Bruges"/>
* <enumeration value="A�roport-Bruxelles"/>
* <enumeration value="A�roport-Li�ge"/>
* </restriction>
* </simpleType>
* </element>
* <element name="receiver" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}receiverType"/>
* <element name="insurance" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}insuranceType"/>
* <element name="receipt" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="declareddimension" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}dimension"/>
* <element name="reviseddimension" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}dimension"/>
* <element name="chargedamount" type="{http://www.w3.org/2001/XMLSchema}float"/>
* <element name="extraamount" type="{http://www.w3.org/2001/XMLSchema}float" minOccurs="0"/>
* <element name="extranotification" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="litige" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}litigeType" minOccurs="0"/>
* <element name="deliveryproblem" type="{http://www.hlbexpress.com/namespaces/HLB-head-office}deliveryproblemType" minOccurs="0"/>
* </sequence>
* <attribute name="requestdate" use="required" type="{http://www.w3.org/2001/XMLSchema}dateTime" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType( XmlAccessType.FIELD )
@XmlType( name = "pickupType", propOrder = {
"pickupaddress",
"billingaddress",
"deliveryaddress",
"pickupcenter",
"deliverycenter",
"receiver",
"insurance",
"receipt",
"declareddimension",
"reviseddimension",
"chargedamount",
"extraamount",
"extranotification",
"litige",
"deliveryproblem"
} )
public class PickupType {
@XmlElement( required = true )
protected AddressType pickupaddress;
protected AddressType billingaddress;
@XmlElement( required = true )
protected AddressType deliveryaddress;
@XmlElement( required = true )
protected String pickupcenter;
@XmlElement( required = true )
protected String deliverycenter;
@XmlElement( required = true )
protected ReceiverType receiver;
@XmlElement( required = true )
protected InsuranceType insurance;
protected boolean receipt;
@XmlElement( required = true )
protected Dimension declareddimension;
@XmlElement( required = true )
protected Dimension reviseddimension;
protected float chargedamount;
protected Float extraamount;
@XmlSchemaType( name = "dateTime" )
protected XMLGregorianCalendar extranotification;
protected LitigeType litige;
protected DeliveryproblemType deliveryproblem;
@XmlAttribute( name = "requestdate", required = true )
@XmlSchemaType( name = "dateTime" )
protected XMLGregorianCalendar requestdate;
/**
* Gets the value of the pickupaddress property.
*
* @return possible object is {@link AddressType }
*
*/
public AddressType getPickupaddress() {
return pickupaddress;
}
/**
* Sets the value of the pickupaddress property.
*
* @param value
* allowed object is {@link AddressType }
*
*/
public void setPickupaddress( AddressType value ) {
this.pickupaddress = value;
}
/**
* Gets the value of the billingaddress property.
*
* @return possible object is {@link AddressType }
*
*/
public AddressType getBillingaddress() {
return billingaddress;
}
/**
* Sets the value of the billingaddress property.
*
* @param value
* allowed object is {@link AddressType }
*
*/
public void setBillingaddress( AddressType value ) {
this.billingaddress = value;
}
/**
* Gets the value of the deliveryaddress property.
*
* @return possible object is {@link AddressType }
*
*/
public AddressType getDeliveryaddress() {
return deliveryaddress;
}
/**
* Sets the value of the deliveryaddress property.
*
* @param value
* allowed object is {@link AddressType }
*
*/
public void setDeliveryaddress( AddressType value ) {
this.deliveryaddress = value;
}
/**
* Gets the value of the pickupcenter property.
*
* @return possible object is {@link String }
*
*/
public String getPickupcenter() {
return pickupcenter;
}
/**
* Sets the value of the pickupcenter property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setPickupcenter( String value ) {
this.pickupcenter = value;
}
/**
* Gets the value of the deliverycenter property.
*
* @return possible object is {@link String }
*
*/
public String getDeliverycenter() {
return deliverycenter;
}
/**
* Sets the value of the deliverycenter property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setDeliverycenter( String value ) {
this.deliverycenter = value;
}
/**
* Gets the value of the receiver property.
*
* @return possible object is {@link ReceiverType }
*
*/
public ReceiverType getReceiver() {
return receiver;
}
/**
* Sets the value of the receiver property.
*
* @param value
* allowed object is {@link ReceiverType }
*
*/
public void setReceiver( ReceiverType value ) {
this.receiver = value;
}
/**
* Gets the value of the insurance property.
*
* @return possible object is {@link InsuranceType }
*
*/
public InsuranceType getInsurance() {
return insurance;
}
/**
* Sets the value of the insurance property.
*
* @param value
* allowed object is {@link InsuranceType }
*
*/
public void setInsurance( InsuranceType value ) {
this.insurance = value;
}
/**
* Gets the value of the receipt property.
*
*/
public boolean isReceipt() {
return receipt;
}
/**
* Sets the value of the receipt property.
*
*/
public void setReceipt( boolean value ) {
this.receipt = value;
}
/**
* Gets the value of the declareddimension property.
*
* @return possible object is {@link Dimension }
*
*/
public Dimension getDeclareddimension() {
return declareddimension;
}
/**
* Sets the value of the declareddimension property.
*
* @param value
* allowed object is {@link Dimension }
*
*/
public void setDeclareddimension( Dimension value ) {
this.declareddimension = value;
}
/**
* Gets the value of the reviseddimension property.
*
* @return possible object is {@link Dimension }
*
*/
public Dimension getReviseddimension() {
return reviseddimension;
}
/**
* Sets the value of the reviseddimension property.
*
* @param value
* allowed object is {@link Dimension }
*
*/
public void setReviseddimension( Dimension value ) {
this.reviseddimension = value;
}
/**
* Gets the value of the chargedamount property.
*
*/
public float getChargedamount() {
return chargedamount;
}
/**
* Sets the value of the chargedamount property.
*
*/
public void setChargedamount( float value ) {
this.chargedamount = value;
}
/**
* Gets the value of the extraamount property.
*
* @return possible object is {@link Float }
*
*/
public Float getExtraamount() {
return extraamount;
}
/**
* Sets the value of the extraamount property.
*
* @param value
* allowed object is {@link Float }
*
*/
public void setExtraamount( Float value ) {
this.extraamount = value;
}
/**
* Gets the value of the extranotification property.
*
* @return possible object is {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getExtranotification() {
return extranotification;
}
/**
* Sets the value of the extranotification property.
*
* @param value
* allowed object is {@link XMLGregorianCalendar }
*
*/
public void setExtranotification( XMLGregorianCalendar value ) {
this.extranotification = value;
}
/**
* Gets the value of the litige property.
*
* @return possible object is {@link LitigeType }
*
*/
public LitigeType getLitige() {
return litige;
}
/**
* Sets the value of the litige property.
*
* @param value
* allowed object is {@link LitigeType }
*
*/
public void setLitige( LitigeType value ) {
this.litige = value;
}
/**
* Gets the value of the deliveryproblem property.
*
* @return possible object is {@link DeliveryproblemType }
*
*/
public DeliveryproblemType getDeliveryproblem() {
return deliveryproblem;
}
/**
* Sets the value of the deliveryproblem property.
*
* @param value
* allowed object is {@link DeliveryproblemType }
*
*/
public void setDeliveryproblem( DeliveryproblemType value ) {
this.deliveryproblem = value;
}
/**
* Gets the value of the requestdate property.
*
* @return possible object is {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getRequestdate() {
return requestdate;
}
/**
* Sets the value of the requestdate property.
*
* @param value
* allowed object is {@link XMLGregorianCalendar }
*
*/
public void setRequestdate( XMLGregorianCalendar value ) {
this.requestdate = value;
}
}
| true |
9c1a570f7a0f1ed097d0134ed5513193fc7662cd | Java | thanhhungchu95/EncryptApp | /gos/app/encrypt/EncryptApp.java | UTF-8 | 3,298 | 2.90625 | 3 | [] | no_license | package gos.app.encrypt;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.DefaultComboBoxModel;
import java.awt.FlowLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class EncryptApp extends JFrame {
private DefaultComboBoxModel<String> model;
private JComboBox<String> boxAlgorithm;
private JPanel pnlText;
private JPanel pnlButton;
private JTextField fldOriginalMessage;
private JTextField fldGenerateMessage;
private JButton btnExit;
private JButton btnGenerate;
private String algorithm;
private final String name[] = {"MD5", "SHA-1", "SHA-256", "SHA-512"};
public EncryptApp() {
initialize();
addListener();
}
public static void main(String[] args) {
EncryptApp app = new EncryptApp();
app.showWindow();
}
private void initialize() {
model = new DefaultComboBoxModel<String>();
algorithm = "MD5";
for (String n : name) model.addElement(n);
boxAlgorithm = new JComboBox<String>();
boxAlgorithm.setModel(model);
boxAlgorithm.setToolTipText("Choose algorithm");
boxAlgorithm.setBounds(100, 50, 100, 25);
fldOriginalMessage = new JTextField();
fldOriginalMessage.setToolTipText("Type your message ...");
fldOriginalMessage.setBounds(10, 10, 280, 30);
fldGenerateMessage = new JTextField();
fldGenerateMessage.setToolTipText("Crypt message");
fldGenerateMessage.setBounds(10, 85, 280, 30);
fldGenerateMessage.setEditable(false);
btnGenerate = new JButton("Generate");
btnExit = new JButton("Exit");
pnlText = new JPanel(null);
pnlText.add(fldOriginalMessage);
pnlText.add(boxAlgorithm);
pnlText.add(fldGenerateMessage);
pnlButton = new JPanel(new FlowLayout(FlowLayout.CENTER));
pnlButton.add(btnGenerate);
pnlButton.add(btnExit);
setTitle("Demo Encrypt Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(400, 100, 300, 200);
getContentPane().add(pnlText, "Center");
getContentPane().add(pnlButton, "South");
}
private void addListener() {
boxAlgorithm.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == evt.SELECTED) {
algorithm = (String)evt.getItem();
}
}
});
btnGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
String gen = Encrypt.crypt(algorithm, fldOriginalMessage.getText());
fldGenerateMessage.setText(gen);
}
});
btnExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
}
public void showWindow() {
setVisible(true);
}
}
| true |
8a32bcfbaf7ae722a46374cf5944233b0c1fd848 | Java | Joncarre/Java-language | /Tecnología de la Programación/Juegos usando MVC/2. Versión con interfaz gráfica/main/java/es/ucm/fdi/tp/view/MessageViewer.java | UTF-8 | 888 | 2.546875 | 3 | [] | no_license | package main.java.es.ucm.fdi.tp.view;
import main.java.es.ucm.fdi.tp.base.model.GameAction;
import main.java.es.ucm.fdi.tp.base.model.GameState;
public abstract class MessageViewer<S extends GameState<S, A>, A extends GameAction<S, A>> extends GUIView<S, A> {
private static final long serialVersionUID = 1L;
/**
* Modifica el contenido de MessageViewerComp
*/
public void setMessageViewer(MessageViewer<S, A> messageInfoViewer){
// Es vacío por defecto. Puede sobreescribirse en las subclases. //
}
/**
* Limpia el MessagesView
*/
abstract public void clearMessagesViewer();
/**
* Añade mensajes
* @param msg
*/
abstract public void addContent(String msg);
/**
* Modifica el texto
* @param msg
*/
abstract public void setContent(String msg);
/**
* Devuelve el texto del JTextArea
* @return
*/
abstract public String getContent();
}
| true |
dc4fa25016b92e4ddb1e914f0688317e872142c8 | Java | haodongLing/MyTalk | /common/src/main/java/com/hoadong/common/ui/recycler/RecyclerAdapter.java | UTF-8 | 7,613 | 2.484375 | 2 | [] | no_license | package com.hoadong.common.ui.recycler;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.util.AsyncListUtil;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hoadong.common.R;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* Created by linghaoDo on 2018/8/29
*/
public abstract class RecyclerAdapter<Data>
extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder<Data>>
implements View.OnClickListener,
View.OnLongClickListener,
IAdapterCallback<Data> {
private final List<Data> mDataList ;
private AdapterListener mListener = null;
/**
* 构造函数模块
*/
public RecyclerAdapter() {
this(null);
}
public RecyclerAdapter( AdapterListener<Data> listener) {
this(new ArrayList<Data>(),listener);
}
public RecyclerAdapter(List<Data> dataList, AdapterListener<Data> listener) {
this.mListener = listener;
this.mDataList = dataList;
}
/**
* 复写默认布局类型返回
*
* @param position 坐标
* @return ResId
*/
@Override
public int getItemViewType(int position) {
return getItemViewType(position, mDataList.get(position));
}
/**
* @param position
* @param data
* @return ResId, 用于创建ViewHolder
*/
@LayoutRes
protected abstract int getItemViewType(int position, Data data);
/**
* 创建viewholder
*
* @param parent recyclerview
* @param viewType 界面的类型 约定为xml的id
* @return 返回viewholder
*/
@NonNull
@Override
public ViewHolder<Data> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 把xml的布局变成view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
// 把xml id 为viewtype的文件初始化为一个root view
View root = inflater.inflate(viewType, parent, false);
// 通过子类必须实现的方法得到viewholder
ViewHolder<Data> holder = onCreatedViewHolder(root, viewType);
// 使用设置id的方法,避免冲突
root.setTag(R.id.tag_recycler_holder, holder);
// 设置事件点击
root.setOnClickListener(this);
root.setOnLongClickListener(this);
// 界面数据绑定
holder.unbinder = ButterKnife.bind(holder, root);
//绑定callback
holder.mCallback = this;
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder<Data> holder, int position) {
// 得到需要的数据
Data data = mDataList.get(position);
// 绑定数据
holder.bind(data);
}
/**
* 得到一个新的viewholder
*
* @param root 根布局
* @param viewType 布局的类型
* @return
*/
protected abstract ViewHolder<Data> onCreatedViewHolder(View root, int viewType);
/**
* @return
*/
@Override
public int getItemCount() {
return mDataList.size();
}
/**
* 插入一条数据
*
* @param data
*/
public void add(Data data) {
mDataList.add(data);
// 只跟新当前
notifyItemInserted(mDataList.size() - 1);
}
/**
* 插入多条数据
*
* @param dataList
*/
public void add(Data... dataList) {
if (dataList != null && dataList.length > 0) {
int startPos = mDataList.size();
Collections.addAll(mDataList, dataList);
notifyItemRangeChanged(startPos, dataList.length);
}
}
/**
* 插入数据
*
* @param dataList
*/
public void add(Collection<Data> dataList) {
if (dataList != null && dataList.size() > 0) {
int startPos = mDataList.size();
mDataList.addAll(dataList);
notifyItemRangeChanged(startPos, dataList.size());
}
}
/**
* 删除 全部更新
*/
public void clear() {
mDataList.clear();
notifyDataSetChanged();
}
/**
* 将数据进行更替,其中包括清空
*
* @param dataList
*/
public void replace(Collection<Data> dataList) {
mDataList.clear();
if (mDataList == null || mDataList.size() == 0) {
mDataList.addAll(dataList);
notifyDataSetChanged();
}
}
@Override
public void onClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag(R.id.tag_recycler_holder);
if (this.mListener != null) {
int pos = viewHolder.getAdapterPosition();
this.mListener.onItemClick(viewHolder, mDataList.get(pos));
}
}
@Override
public boolean onLongClick(View v) {
ViewHolder viewHolder = (ViewHolder) v.getTag(R.id.tag_recycler_holder);
if (this.mListener != null) {
int pos = viewHolder.getAdapterPosition();
this.mListener.onItemLongClick(viewHolder, mDataList.get(pos));
return true;
}
return false;
}
/**
* 设置适配器的监听
*
* @param adapterListener
*/
public void setListener(AdapterListener<Data> adapterListener) {
this.mListener = adapterListener;
}
/**
* 自定义监听器
*
* @param <Data>
*/
public interface AdapterListener<Data> {
void onItemClick(RecyclerAdapter.ViewHolder holder, Data data);
void onItemLongClick(RecyclerAdapter.ViewHolder holder, Data data);
}
@Override
public void update(Data data, ViewHolder<Data> holder) {
int pos=holder.getAdapterPosition();
if (pos>=0){
// 进行数据的移除与更新
//并通知刷新
mDataList.remove(pos);
mDataList.add(pos,data);
notifyItemChanged(pos);
}
}
/**
* 自定义的viewholder
*
* @param <Data>泛型数据类型
*/
public static abstract class ViewHolder<Data> extends RecyclerView.ViewHolder {
protected Data mData;
private IAdapterCallback<Data> mCallback = null;
private Unbinder unbinder = null;
public ViewHolder(View itemView) {
super(itemView);
}
/**
* 用于绑定数据的触发
*
* @param data 绑定的数据
*/
void bind(Data data) {
this.mData = data;
onBind(data);
}
/**
* 当触发绑定数据的时候的回调;必须复写
*
* @param data 绑定的数据
*/
protected abstract void onBind(Data data);
/**
* holder自己对自己对应的data进行更新
*
* @param data
*/
public void updateData(Data data) {
if (this.mCallback != null) {
this.mCallback.update(data, this);
}
}
}
/**
* 对回调接口作实现
* @param <Data>
*/
public static abstract class AdapterListenerImpl<Data> implements AdapterListener<Data>{
@Override
public void onItemClick(ViewHolder holder, Data data) {
}
@Override
public void onItemLongClick(ViewHolder holder, Data data) {
}
}
}
| true |
f3c99517a3e91fe1a6e3d4098040d13bd2150e6e | Java | dhanusathya/springhibernate | /Student/src/main/java/com/sample/dao/StudentDAOImpl.java | UTF-8 | 1,983 | 2.671875 | 3 | [] | no_license | package com.sample.dao;
import java.util.List;
import com.sample.model.Employee;
import com.sample.model.Student;
public class StudentDAOImpl extends BaseDaoImpl implements StudentDAO {
public String addNewEmployee(Employee employee) {
String returnVal="failed";
if(null == employee.getEmp_name() || employee.getEmp_name().isEmpty()){
return returnVal;
}
String SQL ="INSERT INTO employee(emp_name,emp_salary,dept_id,address) VALUES(?,?,?,?)";
int update = getJdbcTemplate().update(SQL, new Object[]{employee});
if(update >= 1){
returnVal="success";
}
logger.info("Logs :",StudentDAOImpl.class);
System.out.println("MSG : "+returnVal);
return returnVal;
}
public String update_student(String student_name, String father_name,
String section, String type_of_student, int studentId) {
String returnVal="failed";
if(null == student_name || student_name.isEmpty() || null == father_name || father_name.isEmpty()){
return returnVal;
}
String SQL = "UPDATE Student SET student_name=?, father_name=?, section=?, type_of_student=? WHERE id=?" ;
int update = getJdbcTemplate().update(SQL, new Object[]{student_name, father_name, section, type_of_student, studentId});
if(update >= 1){
returnVal="success";
}
System.out.println("MSG : "+returnVal);
return returnVal;
}
public List<Student> view_student(String student_name, String father_name,
String section, String type_of_student) {
String SQL="SELECT * FROM student";
return getJdbcTemplate().query(SQL, new StudentRowMapper());
}
public String delete_student(int studentId) {
String returnVal="failed";
String SQL = "Delete from student where id=?";
int update = getJdbcTemplate().update(SQL, new Object[] {studentId});
if(update>=1){
returnVal = "Success";
}
System.out.println("MSG :" +returnVal);
return returnVal;
}
} | true |
5b99b0f13341747561ea9bbe4c557622678e30a6 | Java | codehaus-plexus/plexus-classworlds | /src/test/java/org/codehaus/plexus/classworlds/TestUtil.java | UTF-8 | 1,528 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package org.codehaus.plexus.classworlds;
/*
* Copyright 2001-2006 Codehaus Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @author <a href="bwalding@jakarta.org">Ben Walding</a>
*/
public class TestUtil {
public static URL getTestResourceUrl(String resourceName) {
File baseDir = new File(getBasedir());
File testDir = new File(baseDir, "src/test/test-data");
File resourceFile = new File(testDir, resourceName);
try {
return resourceFile.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static String getBasedir() {
String basedir = System.getProperty("basedir");
/* do our best if we are not running from surefire */
if (basedir == null || basedir.length() <= 0) {
basedir = (new File("")).getAbsolutePath();
}
return basedir;
}
}
| true |
81f29f9d0327835672d391ee64115129346ad453 | Java | pschmucker/Flexmanager | /src/test/java/flexcom/casehistory/ticket/dao/test/NoteDAOImplTest.java | UTF-8 | 5,613 | 2.578125 | 3 | [] | no_license | package flexcom.casehistory.ticket.dao.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import flexcom.casehistory.data.Data;
import flexcom.casehistory.data.TicketDataSet;
import flexcom.casehistory.data.UserDataSet;
import flexcom.casehistory.ticket.dao.NoteDAO;
import flexcom.casehistory.ticket.dao.TicketDAOImpl;
import flexcom.casehistory.ticket.entity.Note;
import flexcom.casehistory.ticket.search.Query;
/**
* Test class for {@link TicketDAOImpl}
*
* @author philippe
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class NoteDAOImplTest {
/**
* A {@link Note}
*/
private Note note;
/**
* Another {@link Note}
*/
private Note tmp;
/**
* ID for the {@link Note}
*/
private long noteId;
/**
* Note DAO
*/
@Autowired
private NoteDAO noteDAO;
@Autowired
private TicketDataSet ticketDataSet;
@Autowired
private UserDataSet userDataSet;
/**
* Set up the context
*
* @throws Exception
*/
@Before
public void setUp() throws Exception {
ticketDataSet.setup();
userDataSet.setup();
note = new Note();
note.setNote("test");
note.setTicket(Data.TICKET_1);
note.setAuthor(Data.USER_1);
noteDAO.createNote(note);
noteId = note.getId();
tmp = new Note();
tmp.setNote("tmp");
tmp.setTicket(Data.TICKET_1);
tmp.setAuthor(Data.USER_1);
noteDAO.createNote(tmp);
}
/**
* Clear the context
*
* @throws Exception
*/
@After
public void tearDown() throws Exception {
noteDAO.deleteAll();
note = null;
tmp = null;
userDataSet.clear();
ticketDataSet.clear();
}
/**
* Test the createNote(Note) method : the DAO must have an additionnal
* entity after the creation
*/
@Test
public void testCreateNote() {
int count = (int) noteDAO.count();
Note n = new Note();
n.setNote("test");
n.setTicket(Data.TICKET_1);
n.setAuthor(Data.USER_1);
noteDAO.createNote(n);
assertEquals(count + 1, noteDAO.count());
}
/**
* Test if the createNote(Note) method throws a
* {@link InvalidDataAccessApiUsageException} by passing a <code>null</code>
* {@link Note}
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void testCreateNullNote() {
noteDAO.createNote(null);
}
/**
* Test if the findAll() method return a correct and complete list of all
* notes. The following conditions are checked :<br/>
* <ul>
* <li>2 notes are in the list</li>
* <li>The list contains the note "test"</li>
* <li>The list contains the note "tmp"</li>
* </ul>
*/
@Test
public void testFindAll() {
List<Note> notes = noteDAO.findAll();
assertEquals(2, notes.size());
assertTrue(notes.contains(note));
assertTrue(notes.contains(tmp));
}
/**
* Test if the modification of an entity has been correctly done
*/
@Test
public void testUpdateNote() {
note.setNote("new test");
noteDAO.updateNote(note);
assertEquals("new test", noteDAO.findById(noteId).getNote());
}
/**
* Test if the updateNote(Note) method throws an
* {@link InvalidDataAccessApiUsageException} if the given argument is
* <code>null</code>
*/
@Test(expected = NullPointerException.class)
public void testUpdateNullNote() {
noteDAO.updateNote(null);
}
/**
* Test if all notes with the specified text are found. The following
* conditions are checked : <br/>
* <ul>
* <li>The list contains 1 note</li>
* <li>The list contains the ticket "test"</li>
* </ul>
*/
@Test
public void testFindByNote() {
List<Note> notes = noteDAO.findByNote("test");
assertEquals(1, notes.size());
assertEquals(note, notes.get(0));
}
/**
* Test the deletion of an {@link Note}. We check that the deleted
* {@link Note} can't be found.
*/
@Test
public void testDeleteNote() {
noteDAO.deleteNote(note);
assertNull(noteDAO.findById(noteId));
}
/**
* Test if a {@link NullPointerException} is thrown by trying to delete a
* <code>null</code> {@link Note}
*/
@Test(expected = NullPointerException.class)
public void testDeleteNullNote() {
noteDAO.deleteNote(null);
}
/**
* Test if the DAO have no more {@link Note} entities after the call of
* deleteAll() method
*/
@Test
public void testDeleteAll() {
noteDAO.deleteAll();
assertEquals(0, noteDAO.count());
}
/**
* Test if an {@link Note} can be found by his ID
*/
@Test
public void testFindById() {
assertEquals(note, noteDAO.findById(noteId));
}
/**
* Test some {@link Note} {@link Query}. First, we create a {@link Query}
* without filters. Then, after each execution of this query, we add a
* filter. The following scenario is executed :<br/>
* <ul>
* <li>0 filters : 2 notes found</li>
* <li>Filter () added : 1 note found</li>
* <li>Filter () added : no note found</li>
* </ul>
*/
@Test
public void testFilter() {
List<Note> notes;
Query<Note> query = new Query<Note>(Note.class);
notes = noteDAO.filter(query);
assertEquals(2, notes.size());
// TODO test some filters
}
/**
* Test the count() method
*/
@Test
public void testCount() {
assertEquals(2, noteDAO.count());
}
}
| true |
fe4da07379c6bce8361c04100b9d31da17516eaf | Java | pro-nsk/testRepo | /src/test/java/SendMailTest.java | UTF-8 | 1,006 | 2.078125 | 2 | [] | no_license | import org.junit.Test;
public class SendMailTest {
@Test
public void sendMail() throws InterruptedException {
YandexMailPage yandexMailPage = new YandexMailPage();
YandexLoginPage yandexLoginPage = yandexMailPage.login();
yandexMailPage = yandexLoginPage.login("alexanderk@adjuggler.ru", System.getProperty("yandexPass"));
yandexMailPage.writeMail("alexanderk@adjuggler.ru", "theme");
yandexMailPage.refreshCheck();
yandexMailPage.deleteLastMail();
// yandexMailPage.other();
System.out.println(666);
System.out.println(555);
System.out.println(333);
System.out.println(222);
yandexMailPage.close();
}
@Test
public void htmlTable() {
HtmlTableExample htmlTableExample = new HtmlTableExample();
// Class<? extends HtmlTableExample> aClass = htmlTableExample.getClass();
htmlTableExample.close();
}
@Test
public void testTest () {
System.out.println("testTest");
}
}
| true |
dd623ce71d9fc0178c2cb7c145364e240e37d5ec | Java | prateekmathur1991/CodeBackup | /src/com/koldbyte/codebackup/plugins/codechef/CodechefPluginImpl.java | UTF-8 | 2,761 | 2.359375 | 2 | [] | no_license | package com.koldbyte.codebackup.plugins.codechef;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.koldbyte.codebackup.core.entities.LanguagesEnum;
import com.koldbyte.codebackup.core.entities.Problem;
import com.koldbyte.codebackup.core.entities.Submission;
import com.koldbyte.codebackup.core.entities.User;
import com.koldbyte.codebackup.plugins.PluginInterface;
import com.koldbyte.codebackup.plugins.codechef.core.entities.CodechefProblem;
import com.koldbyte.codebackup.plugins.codechef.core.entities.CodechefSubmission;
public class CodechefPluginImpl implements PluginInterface {
private final String LISTPAGE = "http://www.codechef.com/users/";
public List<Submission> getSolvedList(User user) {
String url = LISTPAGE + user.getHandle();
ArrayList<Submission> submissions = new ArrayList<Submission>();
try {
// fetch the main page
Document doc = Jsoup.connect(url).get();
// fetch the div which contains the list of solved
Elements elems = doc.getElementsByClass("profile");
Elements links = elems.select("a[href]");
for (Element link : links) {
String linkurl = link.attr("abs:href");
if (linkurl.contains("status")) {
String problemId = link.text();
Problem problem = new CodechefProblem(problemId, "");
// if it is a proper "status" page
// fetch this page
Document page = Jsoup.connect(linkurl).get();
// TODO: extend app to process more than one submission
// Currently let us fetch only the first submission
Element tr = page.select(".kol").get(0);
Elements tds = tr.getElementsByTag("td");
String id = tds.get(0).text();
String time = tds.get(1).text();
String lang = tds.get(6).text();
String solUrl = tds.get(7).select("a[href]")
.attr("abs:href");
// TODO: the solUrl is of pattern
// http://www.codechef.com/viewsolution/2078521
// It should be
// http://www.codechef.com/viewplaintext/2078521
solUrl = solUrl.replace("viewsolution", "viewplaintext");
Submission sub = new CodechefSubmission(id, solUrl,
problem, user);
// TODO: Fix the code language
sub.setLanguage(LanguagesEnum.findExtension(lang));
sub.setTimestamp(time);
submissions.add(sub);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("codechef: Error fetching list.");
// e.printStackTrace();
}
System.out.println("codechef: Found " + submissions.size()
+ " Submissions");
return submissions;
}
}
| true |
5e6b0352b5016574bd45d980f73eb8bdb694b38e | Java | seymourzhang/Layer | /.svn/pristine/fd/fdbe739f6447018c2b91d474165da4481485157c.svn-base | UTF-8 | 2,423 | 1.820313 | 2 | [] | no_license | /**
*
* MTC-上海农汇信息科技有限公司
* Copyright © 2015 农汇 版权所有
*/
package com.mtc.common.util.constants;
/**
* @ClassName: Constants
* @Description:
* @Date 2015年9月10日 上午10:49:39
* @Author Yin Guo Xiang
*
*/
public class Constants {
public static final String APPLICATION_NAME = "惠购-惠购网-www.huiget.com";
public static final String DOMAIN = "http://www.huiget.com";
public static final String STATIC_RESOURCE_DOMAIN = "http://www.huiget.com";
public static final String BACKEND_DOMAIN = "http://backend.huiget.com";
public static final String BACKEND_STATIC_RESOURCE_DOMAIN = "http://backend.huiget.com";
public static final String COOKIE_CONTEXT_ID = "c_id";
public static final String COOKIE_USER_NAME = "un";
public static final String COOKIE_SESSION_ID = "s_id";
public static final String ENCODING_UTF_8 = "UTF-8";
public static final String DEFAULT_MAIL_ENCODING = ENCODING_UTF_8;
public static final boolean DEFAULT_MAIL_HTML = true;
public static final int MAIL_SEND_SUCC = 1;
public static final int MAIL_SEND_FAIL = 0;
public static final String STATUS_VALID = "1";
public static final String STATUS_INVALID = "0";
public static final String RESULT_KEY_STATUS = "status";
public static final String RESULT_VAL_STATUS_200 = "200";
public static final String RESULT_VAL_STATUS_403 = "403";
public static final String RESULT_VAL_STATUS_500 = "500";
public static final String RESULT_KEY_DATA = "data";
public static final String SEGMENTATION = ";";
public static final String LOGIN_TYPE_EMAIL = "E";
public static final String LOGIN_TYPE_MOBILE_PHONE = "M";
public static final String TYPE_PRODUCT = "product";
public static final String TYPE_BRAND = "brand";
public static final String TYPE_AVATAR = "avatar";
public static final String RESULT_SUCCESS = "SUCCESS";
public static final String RESULT_FAIL = "FAIL";
}
| true |
31762b6fd148c08a668ff17253d0f14d922e154e | Java | CodingPlatelets/Spring | /springMvc/src/main/java/cn/edu/wut/edward/Dao/Impl/UserDaoImpl.java | UTF-8 | 335 | 1.921875 | 2 | [] | no_license | package cn.edu.wut.edward.Dao.Impl;
import cn.edu.wut.edward.Dao.UserDao;
import org.springframework.stereotype.Repository;
/**
* @author wenka
* @date 1/31/202118:23
*/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("Hello world");
}
}
| true |
897163715c5ceea698898855c71aa1d35cb2f433 | Java | lixw1992/tomcat5 | /src/org/apache/catalina/authenticator/NonLoginAuthenticator.java | UTF-8 | 2,061 | 2.65625 | 3 | [] | no_license | package org.apache.catalina.authenticator;
import java.io.IOException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.LoginConfig;
/**
* <b>Authenticator</b>和<b>Valve</b>实现类, 只检查不涉及用户身份验证的安全约束
*/
public final class NonLoginAuthenticator extends AuthenticatorBase {
// ----------------------------------------------------- Instance Variables
/**
* 实现类的描述信息
*/
private static final String info =
"org.apache.catalina.authenticator.NonLoginAuthenticator/1.0";
// ------------------------------------------------------------- Properties
/**
* 返回Valve实现类的描述信息
*/
public String getInfo() {
return (info);
}
// --------------------------------------------------------- Public Methods
/**
* 根据指定的登录配置,对作出此请求的用户进行身份验证.
* 如果满足指定的约束,返回<code>true</code>;
* 如果已经创建了一个响应,返回 or <code>false</code>
*
* @param request Request we are processing
* @param response Response we are creating
* @param config 描述如何进行身份验证的登录配置
*
* @exception IOException if an input/output error occurs
*/
public boolean authenticate(Request request,
Response response,
LoginConfig config)
throws IOException {
/* 将请求的会话和一个 SSO关联允许协调会话失效, 当另一个会话登出时, 用户没有登录的web应用的会话应该失效吗?
String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
if (ssoId != null)
associate(ssoId, getSession(request, true));
*/
if (containerLog.isDebugEnabled())
containerLog.debug("User authentication is not required");
return (true);
}
}
| true |
ff1a50734d83cd4957876125f797320b8a65bd25 | Java | ohmylawer/jmrhz | /src/main/java/com/jmrhz/dictionary/controller/DictionaryController.java | UTF-8 | 1,831 | 1.984375 | 2 | [] | no_license | package com.jmrhz.dictionary.controller;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.utils.CommonUtil;
import com.common.utils.IntegerValueFilter;
import com.jmrhz.dictionary.service.IDictionaryService;
@RestController
@RequestMapping(value = "/dictionary")
@CrossOrigin
public class DictionaryController {
@Autowired
private IDictionaryService dictionaryService;
private Logger logger = LoggerFactory.getLogger(getClass());
@GetMapping(value = "/list")
public void listSysdictionary() {
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("dictionaryId", CommonUtil.getRequest().getParameter("dictionaryId"));
map.put("dictionaryValue", CommonUtil.getRequest().getParameter("dictionaryValue"));
map.put("dictionaryType", CommonUtil.getRequest().getParameter("dictionaryType"));
JSONObject obj = new JSONObject();
obj.put("data", JSONArray
.parseArray(JSON.toJSONString(dictionaryService.listDictionarys(map), new IntegerValueFilter())));
CommonUtil.sendJsonData(CommonUtil.getResponse(), obj.toJSONString());
} catch (Exception e) {
try {
CommonUtil.error(CommonUtil.getResponse(), e.toString());
} catch (Exception e1) {
logger.error(e1.getMessage());
e1.printStackTrace();
}
logger.error(e.getMessage());
e.printStackTrace();
}
}
}
| true |
ff5637952c1274678010833a0d906a5dbf66882b | Java | hutamaki/cg | /java/bfs/src/tree/BFS.java | UTF-8 | 323 | 2.75 | 3 | [] | no_license | package tree;
import java.util.Vector;
import tree.Node;
/**
* Created by pierre on 20/01/2017.
*/
public class BFS {
public <T> void sTrace(Tree<T> tree) {
int levels = tree.getMaze().size();
for (Vector<Node<T>> level : tree.getMaze()) {
for (Node<T> node : level) {
}
}
}
}
| true |
4eed0b10595e98f410942de14de4f2649e459e3b | Java | ebourg/jsign | /jsign-core/src/main/java/net/jsign/PESigner.java | UTF-8 | 9,788 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2012 Emmanuel Bourg
*
* 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 net.jsign;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import net.jsign.pe.PEFile;
import net.jsign.timestamp.Timestamper;
import net.jsign.timestamp.TimestampingMode;
/**
* Sign a portable executable file. Timestamping is enabled by default
* and relies on the Sectigo server (http://timestamp.sectigo.com).
*
* @see <a href="https://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/Authenticode_PE.docx">Windows Authenticode Portable Executable Signature Format</a>
* @see <a href="https://docs.microsoft.com/en-us/windows/win32/seccrypto/time-stamping-authenticode-signatures">Time Stamping Authenticode Signatures</a>
*
* @author Emmanuel Bourg
* @since 1.0
* @deprecated Use {@link AuthenticodeSigner} instead
*/
@Deprecated
public class PESigner extends AuthenticodeSigner {
/**
* Create a PESigner with the specified certificate chain and private key.
*
* @param chain the certificate chain. The first certificate is the signing certificate
* @param privateKey the private key
* @throws IllegalArgumentException if the chain is empty
*/
public PESigner(Certificate[] chain, PrivateKey privateKey) {
super(chain, privateKey);
}
/**
* Create a PESigner with a certificate chain and private key from the specified keystore.
*
* @param keystore the keystore holding the certificate and the private key
* @param alias the alias of the certificate in the keystore
* @param password the password to get the private key
* @throws KeyStoreException if the keystore has not been initialized (loaded).
* @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
* @throws UnrecoverableKeyException if the key cannot be recovered (e.g., the given password is wrong).
*/
public PESigner(KeyStore keystore, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
super(keystore, alias, password);
}
/**
* Set the program name embedded in the signature.
*
* @param programName the program name
* @return the current signer
*/
public PESigner withProgramName(String programName) {
return (PESigner) super.withProgramName(programName);
}
/**
* Set the program URL embedded in the signature.
*
* @param programURL the program URL
* @return the current signer
*/
public PESigner withProgramURL(String programURL) {
return (PESigner) super.withProgramURL(programURL);
}
/**
* Enable or disable the replacement of the previous signatures (disabled by default).
*
* @param replace <code>true</code> if the new signature should replace the existing ones, <code>false</code> to append it
* @return the current signer
* @since 2.0
*/
public PESigner withSignaturesReplaced(boolean replace) {
return (PESigner) super.withSignaturesReplaced(replace);
}
/**
* Enable or disable the timestamping (enabled by default).
*
* @param timestamping <code>true</code> to enable timestamping, <code>false</code> to disable it
* @return the current signer
*/
public PESigner withTimestamping(boolean timestamping) {
return (PESigner) super.withTimestamping(timestamping);
}
/**
* RFC3161 or Authenticode (Authenticode by default).
*
* @param tsmode the timestamping mode
* @return the current signer
* @since 1.3
*/
public PESigner withTimestampingMode(TimestampingMode tsmode) {
return (PESigner) super.withTimestampingMode(tsmode);
}
/**
* Set the URL of the timestamping authority. Both RFC 3161 (as used for jar signing)
* and Authenticode timestamping services are supported.
*
* @param url the URL of the timestamping authority
* @return the current signer
* @deprecated Use {@link #withTimestampingAuthority(String)} instead
*/
public PESigner withTimestampingAutority(String url) {
return withTimestampingAuthority(url);
}
/**
* Set the URLs of the timestamping authorities. Both RFC 3161 (as used for jar signing)
* and Authenticode timestamping services are supported.
*
* @param urls the URLs of the timestamping authorities
* @return the current signer
* @since 2.0
* @deprecated Use {@link #withTimestampingAuthority(String...)} instead
*/
public PESigner withTimestampingAutority(String... urls) {
return withTimestampingAuthority(urls);
}
/**
* Set the URL of the timestamping authority. Both RFC 3161 (as used for jar signing)
* and Authenticode timestamping services are supported.
*
* @param url the URL of the timestamping authority
* @return the current signer
* @since 2.1
*/
public PESigner withTimestampingAuthority(String url) {
return (PESigner) super.withTimestampingAuthority(url);
}
/**
* Set the URLs of the timestamping authorities. Both RFC 3161 (as used for jar signing)
* and Authenticode timestamping services are supported.
*
* @param urls the URLs of the timestamping authorities
* @return the current signer
* @since 2.1
*/
public PESigner withTimestampingAuthority(String... urls) {
return (PESigner) super.withTimestampingAuthority(urls);
}
/**
* Set the Timestamper implementation.
*
* @param timestamper the timestamper implementation to use
* @return the current signer
*/
public PESigner withTimestamper(Timestamper timestamper) {
return (PESigner) super.withTimestamper(timestamper);
}
/**
* Set the number of retries for timestamping.
*
* @param timestampingRetries the number of retries
* @return the current signer
*/
public PESigner withTimestampingRetries(int timestampingRetries) {
return (PESigner) super.withTimestampingRetries(timestampingRetries);
}
/**
* Set the number of seconds to wait between timestamping retries.
*
* @param timestampingRetryWait the wait time between retries (in seconds)
* @return the current signer
*/
public PESigner withTimestampingRetryWait(int timestampingRetryWait) {
return (PESigner) super.withTimestampingRetryWait(timestampingRetryWait);
}
/**
* Set the digest algorithm to use (SHA-256 by default)
*
* @param algorithm the digest algorithm
* @return the current signer
*/
public PESigner withDigestAlgorithm(DigestAlgorithm algorithm) {
return (PESigner) super.withDigestAlgorithm(algorithm);
}
/**
* Explicitly sets the signature algorithm to use.
*
* @param signatureAlgorithm the signature algorithm
* @return the current signer
* @since 2.0
*/
public PESigner withSignatureAlgorithm(String signatureAlgorithm) {
return (PESigner) super.withSignatureAlgorithm(signatureAlgorithm);
}
/**
* Explicitly sets the signature algorithm and provider to use.
*
* @param signatureAlgorithm the signature algorithm
* @param signatureProvider the security provider for the specified algorithm
* @return the current signer
* @since 2.0
*/
public PESigner withSignatureAlgorithm(String signatureAlgorithm, String signatureProvider) {
return withSignatureAlgorithm(signatureAlgorithm, Security.getProvider(signatureProvider));
}
/**
* Explicitly sets the signature algorithm and provider to use.
*
* @param signatureAlgorithm the signature algorithm
* @param signatureProvider the security provider for the specified algorithm
* @return the current signer
* @since 2.0
*/
public PESigner withSignatureAlgorithm(String signatureAlgorithm, Provider signatureProvider) {
return (PESigner) super.withSignatureAlgorithm(signatureAlgorithm, signatureProvider);
}
/**
* Set the signature provider to use.
*
* @param signatureProvider the security provider for the signature algorithm
* @return the current signer
* @since 2.0
*/
public PESigner withSignatureProvider(Provider signatureProvider) {
return (PESigner) super.withSignatureProvider(signatureProvider);
}
/**
* Sign the specified executable file.
*
* @param file the file to sign
* @throws Exception if signing fails
*/
public void sign(PEFile file) throws Exception {
super.sign(file);
}
}
| true |
109ac4f96c9887477867c462a0cbfe4257531c51 | Java | Vilkos/SANTEX | /src/main/java/com/santex/entity/Order.java | UTF-8 | 4,024 | 2.65625 | 3 | [] | no_license | package com.santex.entity;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.validation.constraints.Size;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@Entity(name = "orders")
public class Order {
private int id;
private String street;
private String city;
private String postcode;
private String message;
private Status status;
private LocalDateTime timeOfOrder;
private Customer customer;
private List<OrderEntry> entryList = new ArrayList<>();
public Order() {
timeOfOrder = LocalDateTime.now(ZoneId.of("Europe/Kiev"));
status = Status.Нове;
message = "";
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Size(min = 3, max = 50, message = "Назва вулиці має містити від 3 до 50 символів.")
@Column(nullable = false, length = 50)
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Size(min = 3, max = 50, message = "Назва міста має містити від 3 до 50 символів.")
@Column(nullable = false, length = 50)
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Size(min = 3, max = 10, message = "Поштовий індекс має містити від 3 до 10 символів.")
@Column(nullable = false, length = 10)
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
@Size(max = 255, message = "Повідомлення не має перевищувати 255 символів.")
@Column(nullable = false)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Basic
@Convert(converter = StatusConverter.class)
@Column
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Column
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
public LocalDateTime getTimeOfOrder() {
return timeOfOrder;
}
public void setTimeOfOrder(LocalDateTime timeOfOrder) {
this.timeOfOrder = timeOfOrder;
}
@Transient
public String showTimeOfOrder() {
return timeOfOrder.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT).withLocale(Locale.forLanguageTag("uk-UA")).withZone(ZoneId.of("Europe/Kiev")));
}
@Transient
public boolean isCurrentDate() {
return timeOfOrder.toLocalDate().isEqual(LocalDate.now());
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer user) {
this.customer = user;
}
@OneToMany(mappedBy = "orders", fetch = FetchType.LAZY)
public List<OrderEntry> getEntryList() {
return entryList;
}
public void setEntryList(List<OrderEntry> entryList) {
this.entryList = entryList;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", street='" + street + '\'' +
", city='" + city + '\'' +
", postcode='" + postcode + '\'' +
", message='" + message + '\'' +
", timeOfOrder=" + timeOfOrder +
'}';
}
}
| true |
253feff4c3c9fc93d48e2eb38f8cfab2a361d732 | Java | Woojungmin/study | /study/src/study/chap09/instance_member_class/MainExample.java | UTF-8 | 523 | 3.03125 | 3 | [] | no_license | package study.chap09.instance_member_class;
public class MainExample {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
//InnerClass: 인스턴스 멤버 클래스
OuterClass.InnerClass instanceClass = new OuterClass.InnerClass();
instanceClass = outer.new InnerClass();
}
//정적 클래스
OuterClass.StaticInnerClass staticClass = new OuterClass.StaticInnerClass();
staticClass.num = 20;
staticClass.snum = 3;
OuterClass.StaticInnerClass.method2();
}
| true |
8290881fc90994c230bd97da08bba51ba0ba3c77 | Java | DeuceSTM/DeuceSTM | /src/java/org/deuce/transaction/tl2/LockTable.java | UTF-8 | 3,371 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | package org.deuce.transaction.tl2;
import java.util.concurrent.atomic.AtomicIntegerArray;
import org.deuce.transaction.TransactionException;
import org.deuce.transform.Exclude;
@Exclude
public class LockTable {
// Failure transaction
final private static TransactionException FAILURE_EXCEPTION = new TransactionException( "Faild on lock.");
final public static int LOCKS_SIZE = 1<<20; // amount of locks - TODO add system property
final public static int MASK = 0xFFFFF;
final private static int LOCK = 1 << 31;
final private static int UNLOCK = ~LOCK;
final static private int MODULE_8 = 7; //Used for %8
final static private int DIVIDE_8 = 3; //Used for /8
final private static AtomicIntegerArray locks = new AtomicIntegerArray(LOCKS_SIZE); // array of 2^20 entries of 32-bit lock words
/**
*
* @return <code>true</code> if lock otherwise false.
* @throws TransactionException incase the lock is hold by other thread.
*/
public static boolean lock( int lockIndex, byte[] contextLocks) throws TransactionException{
final int lock = locks.get(lockIndex);
final int selfLockIndex = lockIndex>>>DIVIDE_8;
final byte selfLockByte = contextLocks[selfLockIndex];
final byte selfLockBit = (byte)(1 << (lockIndex & MODULE_8));
if( (lock & LOCK) != 0){ //is already locked?
if( (selfLockByte & selfLockBit) != 0) // check for self locking
return false;
throw FAILURE_EXCEPTION;
}
boolean isLocked = locks.compareAndSet(lockIndex, lock, lock | LOCK);
if( !isLocked)
throw FAILURE_EXCEPTION;
contextLocks[selfLockIndex] |= selfLockBit; //mark in self locks
return true;
}
public static int checkLock(int lockIndex, int clock) {
int lock = locks.get(lockIndex);
if( clock < (lock & UNLOCK)|| (lock & LOCK) != 0)
throw FAILURE_EXCEPTION;
return lock;
}
public static int checkLock(int lockIndex, int clock, byte[] contextLocks) {
int lock = locks.get(lockIndex);
if( clock < (lock & UNLOCK))
throw FAILURE_EXCEPTION;
if( (lock & LOCK) != 0){ //is already locked?
int selfLockIndex = lockIndex>>>DIVIDE_8;
byte selfLockByte = contextLocks[selfLockIndex];
byte selfLockBit = (byte)(1 << (lockIndex & MODULE_8));
if( (selfLockByte & selfLockBit) == 0) // check for self locking
throw FAILURE_EXCEPTION; // not self locked
}
return lock;
}
public static void checkLock(int lockIndex, int clock, int expected) {
int lock = locks.get(lockIndex);
if( lock != expected || clock < (lock & UNLOCK) || (lock & LOCK) != 0)
throw FAILURE_EXCEPTION;
}
public static void unLock( int lockIndex, byte[] contextLocks){
int lockedValue = locks.get( lockIndex);
int unlockedValue = lockedValue & UNLOCK;
locks.set(lockIndex, unlockedValue);
clearSelfLock(lockIndex, contextLocks);
}
public static void setAndReleaseLock( int hash, int newClock, byte[] contextLocks){
int lockIndex = hash & MASK;
locks.set(lockIndex, newClock);
clearSelfLock( lockIndex, contextLocks);
}
/**
* Clears lock marker from self locking array
*/
private static void clearSelfLock( int lockIndex, byte[] contextLocks){
// clear marker TODO might clear all bits
contextLocks[lockIndex>>>DIVIDE_8] &= ~(1 << (lockIndex & MODULE_8));
}
}
| true |
a83917e22c8b27a4ec6030ac5892f32bd4989376 | Java | dbeaver/dbeaver | /plugins/org.jkiss.dbeaver.ext.exasol.ui/src/org/jkiss/dbeaver/ext/exasol/ui/editors/ExasolLockEditor.java | UTF-8 | 2,901 | 1.875 | 2 | [
"Apache-2.0",
"EPL-1.0",
"LGPL-2.0-or-later"
] | permissive | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2017 Andrew Khitrin (ahitrin@gmail.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 org.jkiss.dbeaver.ext.exasol.ui.editors;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.widgets.Composite;
import org.jkiss.dbeaver.ext.exasol.model.ExasolDataSource;
import org.jkiss.dbeaver.ext.exasol.model.lock.ExasolLock;
import org.jkiss.dbeaver.ext.exasol.model.lock.ExasolLockManager;
import org.jkiss.dbeaver.ext.ui.locks.edit.AbstractLockEditor;
import org.jkiss.dbeaver.ext.ui.locks.manage.LockManagerViewer;
import org.jkiss.dbeaver.model.admin.locks.DBAServerLock;
import org.jkiss.dbeaver.model.admin.locks.DBAServerLockItem;
import org.jkiss.dbeaver.model.admin.locks.DBAServerLockManager;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import java.math.BigInteger;
import java.util.HashMap;
public class ExasolLockEditor extends AbstractLockEditor {
public static final String sidHold = "hsid";
public static final String sidWait = "wsid";
@SuppressWarnings("unchecked")
@Override
protected LockManagerViewer createLockViewer(
DBCExecutionContext executionContext, Composite parent) {
@SuppressWarnings("rawtypes")
DBAServerLockManager<DBAServerLock, DBAServerLockItem> lockManager = (DBAServerLockManager) new ExasolLockManager((ExasolDataSource) executionContext.getDataSource());
return new LockManagerViewer(this, parent, lockManager) {
@Override
protected void contributeToToolbar(DBAServerLockManager<DBAServerLock, DBAServerLockItem> sessionManager, IContributionManager contributionManager) {
contributionManager.add(new Separator());
}
@SuppressWarnings("serial")
@Override
protected void onLockSelect(final DBAServerLock lock) {
super.onLockSelect(lock);
if (lock != null) {
final ExasolLock pLock = (ExasolLock) lock;
super.refreshDetail(new HashMap<String, Object>() {{
put(sidHold, BigInteger.valueOf(pLock.getHold_sid()));
put(sidWait, BigInteger.valueOf(pLock.getWait_sid().longValue()));
}});
}
}
};
}
}
| true |
ebd216796a0bfa5dcc32ab60f818fffb07062025 | Java | artiomstasiukevich/FridayIsComing | /src/main/java/com/alcoproj/model/UserCredentials.java | UTF-8 | 1,250 | 2.4375 | 2 | [] | no_license | package com.alcoproj.model;
import javax.persistence.*;
import org.hibernate.annotations.NaturalId;
@Entity
@Table(name = "usercredentials")
public class UserCredentials {
@Id
@Column(name = "credentials_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "password")
private String password;
@NaturalId
@Column(name = "email", nullable = false, unique = true)
private String email;
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
User user;
public void updateUser(User user) {
this.user.setName(user.getName());
this.user.setAge(user.getAge());
this.user.setEmail(user.getEmail());
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| true |
c987fe8ecd6cd93bf625fe83f88227454045473b | Java | wgarcia1309/Liga-de-la-justicia | /LigaJusticia/src/ligajusticia/models/Personaje.java | UTF-8 | 1,791 | 3.234375 | 3 | [] | no_license |
package ligajusticia.models;
import java.util.ArrayList;
public abstract class Personaje {
private String nombre;
private ArrayList<Vehiculo> vehiculos;
private ArrayList<Encuentro> encuentros;
public Personaje(String nombre) {
this.nombre = nombre;
vehiculos=new ArrayList<Vehiculo>();
encuentros=new ArrayList<Encuentro>();
}
public void adde(Encuentro e){
encuentros.add(e);
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Vehiculo getsv(String s) {
int i=vehiculos.indexOf(new Vehiculo(s));
if(i==-1)return null;
else return vehiculos.get(i);
}
public void addv(String nombre) {
vehiculos.add(new Vehiculo(nombre));
}
public String getsvmas(){
if(vehiculos.size()>0){
int index=0;
for (int i = 1; i < vehiculos.size(); i++) {
if(vehiculos.get(i).getEncuentros()>vehiculos.get(index).getEncuentros())index=i;
}
if(vehiculos.get(index).getNombre()==null)return "no se ha usado ningun vehiculo hasta el momento en la liga de este heroe";
else return "El vehiculo con mas encuentros en la liga de "+this.getNombre()+" es:\n"+vehiculos.get(index).getNombre()+" con "+vehiculos.get(index).getEncuentros()+" encuentros.";
}
return this.getNombre()+" no tiene ni un vehiculo";
}
@Override
public boolean equals(Object o){
if(o==null)return false;
else if(o instanceof Personaje){
Personaje p=(Personaje)o;
if(p.getNombre().equalsIgnoreCase(this.getNombre()))return true;
}
return false;
}
}
| true |
fda75a7d226f97f3d576e55d5b96eb57870d40a6 | Java | maliamjad17/WSO2_IS_Deployment | /wso2/wso2/WEB-INF/classes/org/wso2/carbon/identity/scim/provider/resources/BulkResource.java | UTF-8 | 3,571 | 1.84375 | 2 | [] | no_license | /* */ package org.wso2.carbon.identity.scim.provider.resources;
/* */
/* */ import javax.ws.rs.HeaderParam;
/* */ import javax.ws.rs.POST;
/* */ import javax.ws.rs.Path;
/* */ import javax.ws.rs.core.Response;
/* */ import org.wso2.carbon.identity.scim.provider.impl.IdentitySCIMManager;
/* */ import org.wso2.carbon.identity.scim.provider.util.JAXRSResponseBuilder;
/* */ import org.wso2.charon.core.encoder.Encoder;
/* */ import org.wso2.charon.core.exceptions.CharonException;
/* */ import org.wso2.charon.core.exceptions.FormatNotSupportedException;
/* */ import org.wso2.charon.core.extensions.UserManager;
/* */ import org.wso2.charon.core.protocol.SCIMResponse;
/* */ import org.wso2.charon.core.protocol.endpoints.AbstractResourceEndpoint;
/* */ import org.wso2.charon.core.protocol.endpoints.BulkResourceEndpoint;
/* */ import org.wso2.charon.core.schema.SCIMConstants;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Path("/")
/* */ public class BulkResource
/* */ {
/* */ @POST
/* */ public Response createUser(@HeaderParam("Content-Type") String inputFormat, @HeaderParam("Accept") String outputFormat, @HeaderParam("Authorization") String authorization, String resourceString)
/* */ {
/* 44 */ Encoder encoder = null;
/* */ try
/* */ {
/* 47 */ IdentitySCIMManager identitySCIMManager = IdentitySCIMManager.getInstance();
/* */
/* */
/* 50 */ if (inputFormat == null) {
/* 51 */ String error = "Content-Type not present in the request header.";
/* 52 */ throw new FormatNotSupportedException(error);
/* */ }
/* */
/* */
/* 56 */ if (!outputFormat.equals("application/json")) {
/* 57 */ outputFormat = "application/json";
/* */ }
/* */
/* 60 */ encoder = identitySCIMManager.getEncoder(SCIMConstants.identifyFormat(outputFormat));
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 68 */ UserManager userManager = IdentitySCIMManager.getInstance().getUserManager(authorization);
/* */
/* */
/* 71 */ BulkResourceEndpoint bulkResourceEndpoint = new BulkResourceEndpoint();
/* 72 */ SCIMResponse responseString = bulkResourceEndpoint.processBulkData(resourceString, inputFormat, outputFormat, userManager);
/* */
/* */
/* */
/* */
/* */
/* 78 */ return new JAXRSResponseBuilder().buildResponse(responseString);
/* */ }
/* */ catch (CharonException e)
/* */ {
/* 82 */ if (e.getCode() == -1) {
/* 83 */ e.setCode(500);
/* */ }
/* 85 */ return new JAXRSResponseBuilder().buildResponse(AbstractResourceEndpoint.encodeSCIMException(encoder, e));
/* */ }
/* */ catch (FormatNotSupportedException e) {
/* 88 */ return new JAXRSResponseBuilder().buildResponse(AbstractResourceEndpoint.encodeSCIMException(encoder, e));
/* */ }
/* */ }
/* */ }
/* Location: C:\Users\MuhammadAli\Desktop\MC\ISCODECOMPARE\wso2is-5.0.0\repository\deployment\server\webapps\wso2.war!\WEB-INF\classes\org\wso2\carbon\identity\scim\provider\resources\BulkResource.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ | true |
28cdd3df78c2696c2bd12f8b504e648ccbfd2767 | Java | jj-a/basicJava | /src/oop1122/SortTest.java | UTF-8 | 1,459 | 3.734375 | 4 | [] | no_license | package oop1122;
public class SortTest {
public static void main(String[] args) {
System.out.println("[ JJA - SortTest ]"+"\n");
// ASC 오름차순 (ascending sort) / DESC 내림차순 (descending sort)
// 정렬 유형: Insertion Sort (삽입정렬) / Selection Sort (선택정렬) / Bubble Sort (버블정렬) / Quick Sort (퀵정렬) / Shell Sort (쉘정렬)
int sort[]= {9,7,3,5,1};
// 선택정렬
System.out.println("[ Selection Sort ]");
System.out.print("정렬전: ");
for(int i=0;i<sort.length;i++) System.out.print(sort[i]+" ");
for(int i=0;i<sort.length;i++) {
for(int j=i+1;j<sort.length;j++) {
if(sort[i]>sort[j]) {
int tmp=sort[i];
sort[i]=sort[j];
sort[j]=tmp;
}
}
}
System.out.print("\n정렬후: ");
for(int i=0;i<sort.length;i++) System.out.print(sort[i]+" ");
// lab. Bubble Sort 방식으로 내림차순 정렬
System.out.println("\n\n[ Bubble Sort (DESC) ]");
System.out.print("정렬전: ");
for(int i=0;i<sort.length;i++) System.out.print(sort[i]+" ");
for(int i=0;i<sort.length;i++) {
for(int j=i;j<=i;j++) {
if(sort[j]<sort[j+1]) {
int tmp=sort[j];
sort[j]=sort[j+1];
sort[j+1]=tmp;
System.out.println(sort[j]+""+sort[j+1]);
}
}
}
System.out.print("\n정렬후: ");
for(int i=0;i<sort.length;i++) System.out.print(sort[i]+" ");
}
}
| true |
0c41236702b24158f3a9e9dd869632f004a3d5bf | Java | madsharm/search-target-case-study | /src/perfTest/java/edu/search/perf/SearchPerformanceTest.java | UTF-8 | 3,573 | 2.8125 | 3 | [] | no_license | package edu.search.perf;
import edu.search.app.search.Search;
import edu.search.engine.SearcherFactory;
import edu.search.vo.TimedSearchResult;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class SearchPerformanceTest {
public static void main(String[] args) throws IOException, URISyntaxException {
Search search = new Search(SearcherFactory.getInstance());
search.initSearchEngine(args);
List<String> testData = loadTestData(search, args);
int numSearches = 500;
compareSearchPerformance(search, testData, numSearches,"regex");
compareSearchPerformance(search, testData, numSearches,"exact string");
}
public static void compareSearchPerformance(Search search, List<String> testData, int numSearches, String type) {
double totalTimeWithIndexedSearch = 0;
double totalTimeWithSimpleSearch = 0;
//simple and indexed search with regex match comparison
for(int i =0 ; i< numSearches ; i++ ) {
String term = generateRandomData(testData, type);
TimedSearchResult indexedSearch = search.search(term, SearcherFactory.MODE.INDEXED);
TimedSearchResult simpleSearch = search.search(term, SearcherFactory.MODE.SIMPLE);
Assert.assertEquals(indexedSearch.getResult().size() , simpleSearch.getResult().size());
totalTimeWithIndexedSearch += indexedSearch.getTimeElapsedInSearch();
totalTimeWithSimpleSearch += simpleSearch.getTimeElapsedInSearch();
}
System.out.println("Average Time for "+ type +" search using Simple Search (ns) = " + (totalTimeWithSimpleSearch/numSearches));
System.out.println("Average Time for "+ type +" search using Indexed Search (ns) = " + (totalTimeWithIndexedSearch/numSearches));
}
static String generateRandomData(List<String> keys , String type) {
if (type.equals("regex")) {
Random random = new Random();
String randomKey = null;
do {
int randomKeyPos = random.nextInt(keys.size());
randomKey = keys.get(randomKeyPos);
} while (randomKey== null || randomKey.length() < 3);
// Do we want prefix/suffix/substring match?
int randomMatchType = random.nextInt(3);
if(randomMatchType == 0) {
//prefix
return randomKey.substring(0, random.nextInt(randomKey.length()-2)+1) + "*";
} else if(randomMatchType == 1) {
//suffix
return "*" + randomKey.substring(random.nextInt(randomKey.length()-2)+1 , randomKey.length());
} else {
return "*" + RandomStringUtils.randomAlphabetic(random.nextInt(5)+1).toLowerCase() + "*";
}
} else {
//exact
Random random = new Random();
String randomKey = null;
do {
int randomKeyPos = random.nextInt(keys.size());
randomKey = keys.get(randomKeyPos);
} while (randomKey== null || randomKey.length() < 2);
return randomKey;
}
}
static List<String> loadTestData(Search search, String[] args) throws IOException, URISyntaxException {
Set<String> keys = search.loadStatisticsData(args).keySet();
return new ArrayList<>(keys);
}
}
| true |
9999ffe4a483b1beb0de60843e52106be1b4dcee | Java | nullbull/Study | /thinkinjava/src/main/java/IO/IOTest.java | UTF-8 | 2,086 | 3.40625 | 3 | [] | no_license | package main.java.IO;
import java.io.*;
public class IOTest {
public static void printStream() throws FileNotFoundException, IOException{
try (
FileOutputStream fileOutputStream = new FileOutputStream("tmp2.txt");
PrintStream printStream = new PrintStream(fileOutputStream);
){
printStream.println("TeXtText\n");
printStream.println(new IOTest());
}catch (IOException e){
e.printStackTrace();
}
System.out.println("Finnsh");
}
public static void stringNode() throws IOException{
String string = "1";
char[] buf = new char[32];
int hasRead = 0;
try (StringReader stringReader = new StringReader("112")){
while ((hasRead = stringReader.read(buf)) > 0){
System.out.print(new String(buf, 0, hasRead));
}
}catch (IOException e){
e.printStackTrace();
}
try (StringWriter stringWriter = new StringWriter()){
stringWriter.write("我想我妈了\n");
stringWriter.write("今天给她打个电话\n");
System.out.println(stringWriter);
}catch (IOException e){
e.printStackTrace();
}
}
public static void keyIn() throws IOException{
try (
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(reader);
){
String line = null;
while((line = bufferedReader.readLine()) != null){
if(line.equals("exit"))
break;
System.out.println(line);
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
//printStream();
// stringNode();
keyIn();
//InputStream 一次读取一个字节
//InputStreamReader 一次读取一个字符
//BufferedReader 一次读取一行
}
}
| true |
2972a29f37f4523574e61d75e0f11a8ac8dbb82b | Java | MatfOOP/OOP | /kolokvijumi/resenja/kol201516_Torta/src/torta/Recept.java | UTF-8 | 499 | 2.84375 | 3 | [
"MIT"
] | permissive | package torta;
public class Recept {
private Sastojak[] sastojci;
public Recept(Sastojak[] sastojci) {
this.sastojci = new Sastojak[sastojci.length];
for(int i = 0; i < sastojci.length; i++)
this.sastojci[i] = new Sastojak(sastojci[i]);
}
public Sastojak[] getSastojci() {
return sastojci;
}
@Override
public String toString() {
String pom = "Lista sastojaka:\n";
for(int i = 0; i < sastojci.length; i++)
pom += ((i+1) + ". " + sastojci[i] + "\n");
return pom;
}
}
| true |
1364d4344b2a15774002cf22bcb2f7c198d5eb85 | Java | WiseHollow/LWJGL_FirstProject | /src/net/johnbrooks/fjg/drawables/effects/EffectType.java | UTF-8 | 1,097 | 2.515625 | 3 | [] | no_license | package net.johnbrooks.fjg.drawables.effects;
import net.johnbrooks.fjg.drawables.Draw;
import org.newdawn.slick.opengl.Texture;
/**
* Created by ieatl on 7/9/2017.
*/
public enum EffectType
{
EXPLOSION(
Draw.loadTexture("res/effects/explosion-large-01.png"),
Draw.loadTexture("res/effects/explosion-large-02.png"),
Draw.loadTexture("res/effects/explosion-large-03.png"),
Draw.loadTexture("res/effects/explosion-large-04.png"),
Draw.loadTexture("res/effects/explosion-large-05.png"),
Draw.loadTexture("res/effects/explosion-large-06.png"),
Draw.loadTexture("res/effects/explosion-large-07.png"),
Draw.loadTexture("res/effects/explosion-large-08.png"),
Draw.loadTexture("res/effects/explosion-large-09.png"),
Draw.loadTexture("res/effects/explosion-large-10.png")
);
private Texture[] textures;
EffectType(Texture... textures)
{
this.textures = textures;
}
public Texture[] getTextures()
{
return textures;
}
}
| true |
8f8b153ccb4cd30017e5ceccfcdc937fc5373b0c | Java | Rb518113/Zoopla_Framework | /src/main/java/com/amazon/utilitty/ExplicitWaitZoopla.java | UTF-8 | 485 | 2.015625 | 2 | [] | no_license | package com.amazon.utilitty;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.amazon.basePage.Basepage;
public class ExplicitWaitZoopla extends Basepage {
public static void explicitWait(WebElement element , long time) {
WebDriverWait wait = new WebDriverWait(driver,time);
wait.until(ExpectedConditions.elementToBeClickable(element));
}
}
| true |
b7e76fb2e8a9970d9d920f1dad36db007b90074c | Java | venio-lusidity/soterium | /framework/src/main/java/com/lusidity/framework/security/RsaX.java | UTF-8 | 3,741 | 2.40625 | 2 | [] | no_license | /*
* Copyright 2018 lusidity inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.lusidity.framework.security;
import com.lusidity.framework.reports.ReportHandler;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RsaX
{
/**
*
* @param file The der public certificate.
* @return A PublicKey
*/
public static PublicKey getPublicKey(File file){
PublicKey result = null;
try(FileInputStream fis = new FileInputStream(file)){
byte[] keyBytes = null;
try(DataInputStream dis = new DataInputStream(fis)){
keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
}
catch (Exception ex){
if(null!=ReportHandler.getInstance()){
ReportHandler.getInstance().warning(ex);
}
}
if(null!=keyBytes)
{
X509EncodedKeySpec spec=new X509EncodedKeySpec(keyBytes);
KeyFactory kf=KeyFactory.getInstance("RSA");
result=kf.generatePublic(spec);
}
}
catch (Exception ex){
if(null!=ReportHandler.getInstance()){
ReportHandler.getInstance().warning(ex);
}
}
return result;
}
/**
*
* @param file The der private key.
* @return A PrivateKey
*/
public static PrivateKey getPrivateKey(File file){
PrivateKey result = null;
try(FileInputStream fis = new FileInputStream(file))
{
try(DataInputStream dis=new DataInputStream(fis))
{
byte[] keyBytes=new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec=new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf=KeyFactory.getInstance("RSA");
result = kf.generatePrivate(spec);
}
catch (Exception ignored){}
}
catch (Exception ignored){}
return result;
}
public static String sign(PrivateKey privateKey, String message) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initSign(privateKey);
sign.update(message.getBytes("UTF-8"));
return new String(Base64.encodeBase64(sign.sign()), "UTF-8");
}
public static boolean verify(PublicKey publicKey, String message, String signature) throws SignatureException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initVerify(publicKey);
sign.update(message.getBytes("UTF-8"));
return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8")));
}
public static String encrypt(String rawText, PublicKey publicKey) throws IOException, GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64String(cipher.doFinal(rawText.getBytes("UTF-8")));
}
public static String decrypt(String cipherText, PrivateKey privateKey) throws IOException, GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.decodeBase64(cipherText)), "UTF-8");
}
}
| true |
0c9847d981c35a76fa06dbb28e05a2d7318013f7 | Java | itheimazyh/MyDogHome | /mallplus-mbg/src/main/java/com/zscat/mallplus/build/BuildHomeResult.java | UTF-8 | 980 | 1.679688 | 2 | [
"Apache-2.0"
] | permissive | package com.zscat.mallplus.build;
import com.zscat.mallplus.build.entity.BuildAdv;
import com.zscat.mallplus.build.entity.BuildNotice;
import com.zscat.mallplus.build.entity.BuildingCommunity;
import com.zscat.mallplus.build.entity.BuildingFloor;
import com.zscat.mallplus.oms.vo.ActivityVo;
import com.zscat.mallplus.pms.entity.PmsSmallNaviconCategory;
import com.zscat.mallplus.sys.entity.SysStore;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* 首页内容返回信息封装
* https://github.com/shenzhuan/mallplus on 2019/1/28.
*/
@Getter
@Setter
public class BuildHomeResult {
List<PmsSmallNaviconCategory> navList;
List<ActivityVo> activityList;
//轮播广告
List<BuildAdv> advertiseList;
BuildingCommunity community;
List<BuildingFloor> floorList;
List<BuildingCommunity> communityList;
//推荐品牌
private List<SysStore> storeList;
//推荐专题
private List<BuildNotice> subjectList;
}
| true |
dd6b9503be92dbdbd92fc47eb44b83480412d37c | Java | exemplo12012/Baby-Near | /app/src/main/java/pi/iesb/br/babynear/ConectadaActivity.java | UTF-8 | 8,228 | 2 | 2 | [] | no_license | package pi.iesb.br.babynear;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Random;
import java.util.UUID;
/**
* Created by henrique on 14/11/2017.
*/
public class ConectadaActivity extends AppCompatActivity implements Serializable {
private static final long serialVersionUID = 5890514926067136397L;
Button btn_voltar;
TextView txt_texto;
TextView txt_texto_configuracao;
BluetoothDevice btDevice;
BluetoothSocket btSocket;
private static final String CHANNEL_ID = "BABY NEAR NOTIFICATION CHANNEL";
int sinal;
private InputStream inputStream;
private OutputStream outputStream;
private LinearLayout baseLayout;
private boolean connected;
private BluetoothGatt bluetoothGatt;
private BluetoothGattCallback mGattCallback;
private Integer distanciaAtual = 0;
private Integer distanciaMaxPermitida;
private boolean reproduzirAudio;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
baseLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.activity_conectado, null, false);
setContentView(baseLayout);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
distanciaMaxPermitida = Integer.parseInt(settings.getString("distancia_max_permitida", "10"));
reproduzirAudio = settings.getBoolean("gravacao_baby_near", true);
btn_voltar = findViewById(R.id.btn_voltar);
txt_texto = findViewById(R.id.txt_conectado);
txt_texto_configuracao = findViewById(R.id.txt_configuracao);
btDevice = (BluetoothDevice) getIntent().getExtras().get("device");
btSocket = (BluetoothSocket) getIntent().getExtras().get("socket");
txt_texto.setText(btDevice.getName() + " foi conectado!!");
txt_texto_configuracao.setText("Distância aproximada máxima permitida: " + distanciaMaxPermitida + " metros");
btn_voltar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
createNotificationChannel();
mGattCallback = new BluetoothGattCallback() {
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, final int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
runOnUiThread(new Runnable() {
@Override
public void run() {
sinal = rssi;
getDistanceFromSinal(sinal);
txt_texto.setText(btDevice.getName() + " foi conectado!!\n " +
"RSSI: " + rssi + "dBm\n" +
"A criança está a aproximadamente " + distanciaAtual + " metros" );
}
});
}
};
}
private void getDistanceFromSinal(int sinal) {
if ( sinal > -5 ) {
distanciaAtual = 0;
} else if ( sinal > -10 ) {
distanciaAtual = 3;
} else if ( sinal > -15 ) {
distanciaAtual = 5;
} else if ( sinal > -20 ) {
distanciaAtual = 7;
} else if ( sinal > -30 ) {
distanciaAtual = 9;
} else {
distanciaAtual = 11;
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@Override
public void onStart() {
super.onStart();
try {
connect(btDevice);
} catch (Exception e) {
e.printStackTrace();
}
int corVerde = getResources().getColor(R.color.verde, null);
baseLayout.setBackgroundColor(corVerde);
new ConnectService().execute();
}
private void connect(BluetoothDevice bdDevice) throws Exception {
try {
bluetoothGatt = bdDevice.connectGatt(this, false, mGattCallback);
if (bluetoothGatt == null) {
return;
}
UUID uuid = bdDevice.getUuids() == null ? UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") : bdDevice.getUuids()[0].getUuid();
btSocket = bdDevice.createRfcommSocketToServiceRecord(uuid);
btSocket.connect();
InputStream tmpIn = null;
OutputStream tmpOut = null;
if ( btSocket != null ) {
try{
tmpIn = btSocket.getInputStream();
tmpOut = btSocket.getOutputStream();
} catch (IOException e) { }
}
inputStream = tmpIn;
outputStream = tmpOut;
String configuracao = reproduzirAudio ? "N" : "R";
outputStream.write(configuracao.getBytes());
outputStream.flush();
connected = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private class ConnectService extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... voids) {
while (bluetoothGatt.readRemoteRssi()) {
if ( distanciaAtual > distanciaMaxPermitida ) {
try {
outputStream.write("D".getBytes());
outputStream.flush();
} catch (IOException e) {
break;
}
break;
}
}
publishProgress();
return false;
}
@Override
protected void onProgressUpdate(Void... voids) {
runOnUiThread(myRunnable);
int corVermelha = getResources().getColor(R.color.vermelho, null);
baseLayout.setBackgroundColor(corVermelha);
Toast.makeText(ConectadaActivity.this, "Acabou a conexão", Toast.LENGTH_SHORT).show();
MediaPlayer mp = MediaPlayer.create(ConectadaActivity.this, R.raw.alerta);
mp.start();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(2000, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(2000);
}
createNotificationOnFail();
endSocket();
}
private Runnable myRunnable = new Runnable() {
@Override
public void run() {
Toast toastTdBem = Toast.makeText(ConectadaActivity.this, "Tudo Bem!", Toast.LENGTH_SHORT);
toastTdBem.show();
txt_texto.setText("Conexão acabou!!!!");
}
};
}
public void endSocket() {
try {
btSocket.close();
} catch (IOException e) { }
}
private void createNotificationOnFail() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_notification_alert))
.setContentTitle("ALERTA!!!!!!")
.setContentText("Dispositivo mais distante do que o seguro!!")
.setPriority(NotificationCompat.PRIORITY_MAX);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(new Random().nextInt(), builder.build());
}
}
| true |
5fa1e9d47abeae4c7c376f209df91698621356c0 | Java | sogno12/pro_accountBook_back | /src/main/java/com/book/account/user/repository/impl/UserRepositoryImpl.java | UTF-8 | 2,966 | 2.078125 | 2 | [] | no_license | package com.book.account.user.repository.impl;
import static com.book.account.user.model.QUser.user;
import static com.book.account.auth.model.QUserAuth.userAuth;
import java.util.List;
import javax.persistence.EntityManager;
import com.book.account.user.model.consts.UserConst.Status;
import com.book.account.user.model.dto.UserDto;
import com.book.account.user.repository.custom.UserRepositoryCustom;
import com.book.account.util.JPAQueryUtils;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public class UserRepositoryImpl implements UserRepositoryCustom {
private final JPAQueryFactory queryFactory;
public UserRepositoryImpl(EntityManager em) {
super();
this.queryFactory = new JPAQueryFactory(em);
}
@Override
public Page<UserDto> getUsers(UserDto userDto, Pageable pageable) {
JPAQuery<UserDto> query = queryFactory
.select((Projections.fields(UserDto.class, user.userId, user.userName, user.email, userAuth.loginId,
userAuth.status)))
.from(user).leftJoin(userAuth).on(user.userId.eq(userAuth.user.userId))
.where(userNameLike(userDto.getUserName()), loginIdLike(userDto.getLoginId()), statusEq(userDto.getStatus()))
.offset(pageable.getOffset())
.limit(pageable.getPageSize());
for (Sort.Order o : pageable.getSort()) {
JPAQueryUtils.queryDslGenOrderBy(user, o, query);
}
QueryResults<UserDto> results = query.fetchResults();
List<UserDto> content = results.getResults();
Long total = results.getTotal();
return new PageImpl<>(content, pageable, total);
}
@Override
public UserDto getUser(Long userId) {
UserDto userDto = queryFactory
.select((Projections.fields(UserDto.class, user.userId, user.userName, user.email, userAuth.loginId,
userAuth.status)))
.from(user).leftJoin(userAuth).on(user.userId.eq(userAuth.user.userId)).where(user.userId.eq(userId))
.fetchOne();
return userDto;
}
private BooleanExpression userNameLike(String userName) {
return userName != null ? user.userName.lower().like("%" + userName.toLowerCase() + "%") : null;
}
private BooleanExpression loginIdLike(String loginId) {
return loginId != null ? userAuth.loginId.lower().like("%" + loginId.toLowerCase() + "%") : null;
}
private BooleanExpression statusEq(Status status) {
return status != null ? userAuth.status.eq(status) : null;
}
}
| true |
448aeb1d971de19d82034309c8a4702577d38f55 | Java | Ritam804/SplitTheBill | /app/src/main/java/setergeter/Booking_SetterGetter.java | UTF-8 | 3,716 | 2.25 | 2 | [] | no_license | package setergeter;
/**
* Created by ritam on 29/04/17.
*/
public class Booking_SetterGetter {
String EventId,EventName,VenueName,VenueAddress,ReferenceId,TableName,EventMonth,EventDate,EventTime,TableId,HostId;
String HostName,TotalNoOfSeat,NumberOfAvailableSeat,MaximumMount,GroupId;
public Booking_SetterGetter(String eventid, String eventName, String venueName, String venueAddress, String referenceId, String tableName, String eventMonth, String eventDate , String eventtime, String tableid, String hostid,String hostname,String totalseat,String availableseat,String maximumamount,String groupid) {
EventId = eventid;
EventName = eventName;
VenueName = venueName;
VenueAddress = venueAddress;
ReferenceId = referenceId;
TableName = tableName;
EventMonth = eventMonth;
EventDate = eventDate;
EventTime = eventtime;
TableId = tableid;
HostId = hostid;
HostName = hostname;
TotalNoOfSeat = totalseat;
NumberOfAvailableSeat = availableseat;
MaximumMount = maximumamount;
GroupId = groupid;
}
public String getHostName() {
return HostName;
}
public void setHostName(String hostName) {
HostName = hostName;
}
public String getTotalNoOfSeat() {
return TotalNoOfSeat;
}
public void setTotalNoOfSeat(String totalNoOfSeat) {
TotalNoOfSeat = totalNoOfSeat;
}
public String getNumberOfAvailableSeat() {
return NumberOfAvailableSeat;
}
public void setNumberOfAvailableSeat(String numberOfAvailableSeat) {
NumberOfAvailableSeat = numberOfAvailableSeat;
}
public String getMaximumMount() {
return MaximumMount;
}
public void setMaximumMount(String maximumMount) {
MaximumMount = maximumMount;
}
public String getGroupId() {
return GroupId;
}
public void setGroupId(String groupId) {
GroupId = groupId;
}
public String getTableId() {
return TableId;
}
public void setTableId(String tableId) {
TableId = tableId;
}
public String getHostId() {
return HostId;
}
public void setHostId(String hostId) {
HostId = hostId;
}
public String getEventId() {
return EventId;
}
public void setEventId(String eventId) {
EventId = eventId;
}
public String getEventTime() {
return EventTime;
}
public void setEventTime(String eventTime) {
EventTime = eventTime;
}
public String getEventName() {
return EventName;
}
public void setEventName(String eventName) {
EventName = eventName;
}
public String getVenueName() {
return VenueName;
}
public void setVenueName(String venueName) {
VenueName = venueName;
}
public String getVenueAddress() {
return VenueAddress;
}
public void setVenueAddress(String venueAddress) {
VenueAddress = venueAddress;
}
public String getReferenceId() {
return ReferenceId;
}
public void setReferenceId(String referenceId) {
ReferenceId = referenceId;
}
public String getTableName() {
return TableName;
}
public void setTableName(String tableName) {
TableName = tableName;
}
public String getEventMonth() {
return EventMonth;
}
public void setEventMonth(String eventMonth) {
EventMonth = eventMonth;
}
public String getEventDate() {
return EventDate;
}
public void setEventDate(String eventDate) {
EventDate = eventDate;
}
}
| true |
e0b8279084e6059bb7c46150ed056ead486758c8 | Java | aniket7487/code | /BasicPrograms/src/com/basic/array/SecondLargest.java | UTF-8 | 559 | 3.53125 | 4 | [] | no_license | package com.basic.array;
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
int secMax=0,max=0;
Scanner sc=new Scanner(System.in);
int noElement= sc.nextInt();
int arr[]=new int[noElement];
for(int i=0;i<noElement;i++) {
arr[i]=sc.nextInt();
}
for(int i=0;i<arr.length;i++) {
if(arr[i]>max) {
secMax=max;
max=arr[i];
}else if(arr[i]<max && arr[i]> secMax) {
secMax=arr[i];
}
}
System.out.println("Max:" + max + "Second Max: "+ secMax);
}
}
| true |
ab8aaec0fb57701dc486470f596f7cacb93c1d13 | Java | dpacker123/inhetience | /src/comp/comp152/Main.java | UTF-8 | 689 | 2.8125 | 3 | [] | no_license | package comp.comp152;
import java.util.ArrayList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
var inNetworkDoctors = new ArrayList<doctor>();
inNetworkDoctors.add(new doctor("Pricey University", 400));
inNetworkDoctors.add(new Surgeon("Childrens hospital", "fancy uni", 1000));
var sickPatient = new person("Stu Dent");
var sickPatient2 = new person(("Some Body"));
var picker = new Random();
var choice = picker.nextInt(inNetworkDoctors.size());
doctor doc = inNetworkDoctors.get(choice);
doc.treatPatient(sickPatient);
doc.billPatient(sickPatient);
}
}
| true |
6973eccc3437b0f49c8e9596044136628c2a11f9 | Java | timipaul/shijin3_android-dev | /app/src/main/java/com/shijinsz/shijin/utils/DownloadAPK.java | UTF-8 | 6,066 | 2.0625 | 2 | [] | no_license | package com.shijinsz.shijin.utils;
/**
* Created by yrdan on 2018/11/20.
*/
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import com.hongchuang.hclibrary.utils.AndroidSystemUtil;
import com.shijinsz.shijin.BuildConfig;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 下载APK的异步任务
*/
public class DownloadAPK extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
File file;
Context context;
public onDownloadAPK getDownloadAPK() {
return downloadAPK;
}
public void setDownloadAPK(onDownloadAPK downloadAPK) {
this.downloadAPK = downloadAPK;
}
public onDownloadAPK downloadAPK;
public interface onDownloadAPK{
void onStart();
void onFinish();
void onOpen();
}
public DownloadAPK(Context context,ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
this.context=context;
}
@Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection conn;
BufferedInputStream bis = null;
FileOutputStream fos = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
bis = new BufferedInputStream(conn.getInputStream());
int fileLength = conn.getContentLength();
String fileName = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
.getAbsolutePath() + "/magkare/action.apk";
file = new File(fileName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
fos = new FileOutputStream(file);
byte data[] = new byte[4 * 1024];
long total = 0;
int count;
while ((count = bis.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
fos.write(data, 0, count);
fos.flush();
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
progressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
openFile(file);
progressDialog.dismiss();
if (downloadAPK!=null){
downloadAPK.onFinish();
downloadAPK.onOpen();
}
}
private void openFile(File file) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(activity,"包名.fileprovider", takeImageFile));
// } else {
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(takeImageFile));
// }
if (file != null) {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(file.getAbsolutePath(),
PackageManager.GET_ACTIVITIES);
if (info != null) {
String packageName = info.packageName;
int versionCode = info.versionCode;
Log.i("APKNAME", "openFile: "+packageName);
AndroidSystemUtil androidSystemUtil=new AndroidSystemUtil(context);
if (androidSystemUtil.isAppInstalled(packageName)==1) {
Intent intent = pm.getLaunchIntentForPackage(packageName);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return;
}
}
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
// startActivity(intent);
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else {
// 声明需要的零时权限
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 第二个参数,即第一步中配置的authorities
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
}
}
| true |
cce077a437d51dbde6976935880aee7e9d0f9d2f | Java | csdncyh/chenqian | /src/main/java/com/chenqian/interceptor/interceptor.java | UTF-8 | 2,721 | 2.375 | 2 | [] | no_license | package com.chenqian.interceptor;
import com.chenqian.controller.Result;
import com.chenqian.entity.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
/**
* 拦截器
*/
public class interceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("进入111");
// HandlerMethod handlerMethod = (HandlerMethod)handler;
// String methodName = handlerMethod.getMethod().getName();
// String className = handlerMethod.getClass().getName();
//
// /**
// * 解析控制器方法
// */
// StringBuffer buff = new StringBuffer();
// Map paramMap = request.getParameterMap();
// Iterator it = paramMap.entrySet().iterator();
// while (it.hasNext()){
// Map.Entry entry = (Map.Entry)it.next();
// String mapKey = (String)entry.getKey();
// String mapVaule = "";
//
// Object obj = entry.getValue();
// if (obj instanceof String[]){
// String[] strs = (String[])obj;
// mapVaule = Arrays.toString(strs);
// }
// buff.append(mapKey).append("=").append(mapVaule);
// }
/**
* 判断用户是否已经登录
*/
User user = (User) request.getSession().getAttribute("user");
if (user == null){
//没有登录, 通过HttpServletResponse返回json数据, 不走控制器
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(Result.error("未登录").toString());
System.out.println("没有登录");
out.flush();
out.close();
return false;
}
System.out.println("登录了");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
//第三个参数表示的是控制层被拦截的方法
}
| true |
74a811c0fcb16fe56eff6641c95e869b5bfaf8fc | Java | touchepass/javaProject | /CoVoiturage/src/DAO/DPersonneTresorier.java | UTF-8 | 3,707 | 2.6875 | 3 | [] | no_license | package DAO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import Classe.CCategorie;
import Classe.CPersonneTresorier;
public class DPersonneTresorier extends DAO<CPersonneTresorier> {
public DPersonneTresorier() { }
@Override
public boolean create(CPersonneTresorier obj){
try{
Statement stmt = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate(
"INSERT INTO PersonneTresorier (IdPers,fond) "+
" VALUES ("+3+","+obj.getIdPers()+","+obj.getFond()+");"
);
return true;
}
catch(SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public boolean delete(CPersonneTresorier obj){
try{
Statement stmt = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate("DELETE FROM PersonneTresorier WHERE IdPersTres = "+obj.getIdPersTres()+";");
return true;
}
catch(SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public boolean update(CPersonneTresorier obj){
try{
Statement stmt = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate("UPDATE PersonneTresorier SET"
+ " fond = "+obj.getFond()
+ " WHERE IdPersTres = "+obj.getIdPersTres()+";");
return true;
}
catch(SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public CPersonneTresorier find(Object obj/* ce qui permet de retrouver la balade */){
CPersonneTresorier a = null;
CCategorie c = null;
try{
String pseudo = (String)obj;
Statement stmt = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet result = stmt.executeQuery("select * from Personne p inner join PersonneTresorier pm " + " on pm.IdPers = p.IdPers where pseudo='"+pseudo+"'" );
if(result.first()) {
DCategorie dc = new DCategorie();
c = dc.find(result.getInt("IdCat"));
a = new CPersonneTresorier(result.getInt("IdPers"),
result.getString("nom"),result.getString("prenom"),
result.getDate("dateNaissance"),result.getString("sexe"),
result.getString("numero"),result.getString("rue"),
result.getString("numRue"),result.getString("localite"),
result.getString("CodePostal"),result.getString("pseudo"),
result.getString("pass"),result.getInt("IdPersTres"),
result.getInt("Fond"));
}
}
catch(SQLException e){
e.printStackTrace();
}
return a;
}
public CPersonneTresorier find(int obj){
CPersonneTresorier a = null;
CCategorie c = null;
try{
Statement stmt = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet result = stmt.executeQuery("select * from Personne p inner join PersonneTresorier pm " + " on pm.IdPers = p.IdPers where IdPersTres="+obj+";" );
if(result.first()) {
DCategorie dc = new DCategorie();
c = dc.find(result.getInt("IdCat"));
a = new CPersonneTresorier(result.getInt("IdPers"),
result.getString("nom"),result.getString("prenom"),
result.getDate("dateNaissance"),result.getString("sexe"),
result.getString("numero"),result.getString("rue"),
result.getString("numRue"),result.getString("localite"),
result.getString("CodePostal"),result.getString("pseudo"),
result.getString("pass"),result.getInt("IdPersTres"),
result.getInt("Fond"));
}
}
catch(SQLException e){
e.printStackTrace();
}
return a;
}
}
| true |
78c6d7c84f9486a2949854a7e7443710fc8d29fe | Java | EdersonSouza02/WorkspaceAndroid | /workspace/Workspace/src/br/gov/sp/etec/primeiraaplicacao/MainActivity.java | UTF-8 | 1,261 | 2.3125 | 2 | [] | no_license |
package br.gov.sp.etec.primeiraaplicacao;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editTextNome;
private EditText editTextMostrarNome;
private Button buttonMostrar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextNome = (EditText) findViewById(R.id.editTextNome);
editTextMostrarNome = (EditText) findViewById(R.id.editTextMostarNome);
buttonMostrar = (Button) findViewById(R.id.buttonMostrar);
buttonMostrar.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String mostra = editTextNome.getText().toString();
editTextMostrarNome.setText(mostra);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true |
657d1c013a8f1dcb1daeaaa35063831b9e3aa03b | Java | iligne42/Projet-de-Programmation | /TimeTrialVersion.java | UTF-8 | 1,291 | 2.375 | 2 | [] | no_license |
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.util.Duration;
import java.io.IOException;
public class TimeTrialVersion extends GameVersion {
public final int timeLimit;
public TimeTrialVersion(int length, int width, int nbFloors,int nbObstacles,int nbMonstres,int nbTeleport,int nbDoors,int nbBonus,int typeBonus,String name, int time) throws FormatNotSupported,IOException{
super(length,width,nbFloors,nbObstacles,nbMonstres,nbTeleport,nbDoors,nbBonus,typeBonus,name,new Scores("bestRaces.txt",MazeInterface.getDifficulty(length,width)));
timeLimit=time;
}
public TimeTrialVersion(MazeFloors maze, Player player, int time) throws FormatNotSupported,IOException{
super(maze,player,new Scores("txt/bestRaces.txt",MazeInterface.getDifficulty(maze.getFloor().getFirst().getHeight(),maze.getFloor().getFirst().getWidth())));
timeLimit=time;
}
public TimeTrialVersion(MazeFloors maze, String name, int time) throws FormatNotSupported,IOException{
super(maze,name,new Scores("txt/bestRaces.txt",MazeInterface.getDifficulty(maze.getFloor().getFirst().getHeight(),maze.getFloor().getFirst().getWidth())));
timeLimit=time;
}
@Override
public String scoresFile(){
return "txt/bestRaces.txt";
}
}
| true |
7a7345a98b2ea700c3ac5b6b4b5e0b04228d5332 | Java | edmilson-teixeira/calculo-frete | /src/test/java/br/com/softplan/sienge/calculofrete/FreightCalculatorControllerTest.java | UTF-8 | 5,284 | 2.453125 | 2 | [] | no_license | package br.com.softplan.sienge.calculofrete;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import br.com.softplan.sienge.calculofrete.controller.FreightCalculatorController;
import br.com.softplan.sienge.calculofrete.vehicle.AvailableVehicles;
import br.com.softplan.sienge.calculofrete.vehicle.Vehicle;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FreightCalculatorControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
FreightCalculatorController freightCalculatorController;
private String buildQueryUrl(int pavedRoadDistance, int notPavedRoadDistance, String vehicleType, int weightCargo) {
return new StringBuilder("pavedRoadDistance=")
.append(pavedRoadDistance)
.append("¬PavedRoadDistance=")
.append(notPavedRoadDistance)
.append("&vehicleType=")
.append(vehicleType)
.append("&weightCargo=")
.append(weightCargo).toString();
}
@Test
public void containsThreeVehicles() {
ResponseEntity<AvailableVehicles> freightCalculatorResponse = restTemplate.getForEntity("/vehicle-type", AvailableVehicles.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
List<Vehicle> vehicles = new ArrayList<Vehicle>();
vehicles.add(new Vehicle("CAMINHAO_BAU", "Caminhao Baú"));
vehicles.add(new Vehicle("CAMINHAO_CACAMBA", "Caminhão Caçamba"));
vehicles.add(new Vehicle("CARRETA", "Carreta"));
assertThat(freightCalculatorResponse.getBody().getVehicles().equals(vehicles));
}
@Test
public void invalidVehicleName() {
String queryString = "/calculate?" + this.buildQueryUrl(0, 0, "CAMINHAO_INEXISTENTE", 0);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(freightCalculatorResponse.getBody().equals("Tipo de veículo não encontrado: CAMINHAO_INEXISTENTE."));
}
@Test
public void vehicleNotFound() {
String queryString = "/calculate?" + this.buildQueryUrl(0, 0, "", 0);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(freightCalculatorResponse.getBody().equals("Nenhum tipo de veículo selecionado."));
}
@Test
public void pavedWithBucketTruckOverExceededCargo() {
String queryString = "/calculate?" + this.buildQueryUrl(100, 0, "CAMINHAO_CACAMBA", 8);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(freightCalculatorResponse.getBody().equals("62.70"));
}
@Test
public void notPavedWithTruckTrunkLowerCargo() {
String queryString = "/calculate?" + this.buildQueryUrl(0, 60, "CAMINHAO_BAU", 4);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(freightCalculatorResponse.getBody().equals("37.20"));
}
@Test
public void notPavedWithTruckOverExceededCargo() {
String queryString = "/calculate?" + this.buildQueryUrl(0, 180, "CARRETA", 12);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(freightCalculatorResponse.getBody().equals("150.19"));
}
@Test
public void bothRoadsWithTruckTrunkOverExceededCargo() {
String queryString = "/calculate?" + this.buildQueryUrl(80, 20, "CAMINHAO_BAU", 6);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(freightCalculatorResponse.getBody().equals("57.60"));
}
@Test
public void bothRoadsWithBucketTruckOverLimitCargo() {
String queryString = "/calculate?" + this.buildQueryUrl(50, 30, "CAMINHAO_CACAMBA", 5);
ResponseEntity<String> freightCalculatorResponse = restTemplate.getForEntity(queryString, String.class);
assertThat(freightCalculatorResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(freightCalculatorResponse.getBody().equals("47.88"));
}
}
| true |
f76754c075aacb1a37835c547cdabec437b33480 | Java | felleuch/formation_oct_2020 | /GestionException.java | UTF-8 | 1,849 | 3.140625 | 3 | [] | no_license | package com.formation;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class GestionException {
final static Logger logger = Logger.getLogger(GestionException.class);
public static void main(String[] args) {
logger.info("Debut du programme");
gestionRunTimeException();
/*
try {
gestionExceptionControleWithThrow();
} catch (FileNotFoundException e) {
logger.error("Exception with Throw : ouverture de fichier",e);
}
*/
logger.info("Fin du programme");
}
private static void gestionExceptionControle() {
try{
FileInputStream monFichier = new FileInputStream("c:\\toto.txt");
} catch (FileNotFoundException e) {
logger.error("Exception : ouverture de fichier",e);
}
}
private static void gestionExceptionControleWithThrow() throws FileNotFoundException {
FileInputStream monFichier = new FileInputStream("c:\\toto.txt");
}
private static void gestionRunTimeException() {
int a = 1;
int b=0;
logger.info("Debut du block try");
try{
try {
testEAN(8);
} catch (MonException e) {
logger.error("Exception personalisé ",e);
}
int d = a/b;
logger.debug("Aucune erreur declanché");
}catch(ArithmeticException e){
logger.info("Debut du block catch");
//System.out.println("Exception division par zero ! impossible");
logger.error("Exception division par zero ! impossible",e);
}
}
private static void testEAN(int value) throws MonException {
if (value<13) {
throw new MonException("13");
}
}
}
| true |
cd5dca5fb6d32907b1ccb5d9d4f75f94f07f651c | Java | TangerineSpecter/OrangeManageSystem | /src/main/java/com/tangerineSpecter/oms/system/service/BaseService.java | UTF-8 | 819 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.tangerinespecter.oms.system.service;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.tangerinespecter.oms.common.query.QueryObject;
import java.io.Serializable;
import java.util.List;
/**
* @author 丢失的橘子
*/
public interface BaseService<Param extends Serializable, Result> {
/**
* 分页查询
*
* @param param 请求参数DTO
* @return 分页集合
*/
default PageInfo<Result> queryForPage(QueryObject<Param> param) {
return PageMethod.startPage(param.getPage(), param.getLimit())
.doSelectPageInfo(() -> list(param.getSearchParams()));
}
/**
* 集合查询
*
* @param param 查询参数
* @return 查询响应
*/
List<Result> list(Param param);
}
| true |
69f85ad420edacd5d91db58b6196b951af5a953a | Java | zhangyan-1997/leetcode | /src/huaweiLC/No860.java | UTF-8 | 1,005 | 3.1875 | 3 | [] | no_license | package huaweiLC;
/**
* <h3>leetcode</h3>
* <p>柠檬水找零</p>
*
* @author : 张严
* @date : 2021-06-15 21:31
**/
public class No860 {
public boolean lemonadeChange(int[] bills) {
int exchange_5 = 0;
int exchange_10 = 0;
for (int i = 0; i < bills.length; i++) {
if(bills[i]==5) exchange_5++;
else if(bills[i]==10) {
if(exchange_5<=0) return false;
exchange_10++;
exchange_5--;
}else {
if(exchange_5>0&&exchange_10>0){
exchange_10--;
exchange_5--;
}else if(exchange_5>2){
exchange_5 -=3;
}
else return false;
}
}
return true;
}
public static void main(String[] args) {
No860 no860 = new No860();
System.out.println(no860.lemonadeChange(new int[]{5,5,5,20,5,5,5,20,5,5,5,10,5,20,10,20,10,20,5,5}));
}
}
| true |
95244f9fc7b367ead8fc5943864666514e8b2221 | Java | Eygen/Testing | /src/main/java/com/epam/zt/testing/action/PostUpdateAdminAction.java | UTF-8 | 2,134 | 2.46875 | 2 | [] | no_license | package com.epam.zt.testing.action;
import com.epam.zt.testing.model.Admin;
import com.epam.zt.testing.service.AdminService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.epam.zt.testing.action.ValidationUtil.validate;
public class PostUpdateAdminAction implements Action {
private ActionResult settings = new ActionResult("adminSettings");
private static final String passwordPattern = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
@Override
public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) {
Admin admin = (Admin) req.getSession().getAttribute("user");
String firstname = req.getParameter("firstname");
String lastname = req.getParameter("lastname");
String email = req.getParameter("email");
String password = req.getParameter("password");
req.getSession().setAttribute("successUpdate","");
int i = 0;
if (!admin.getFirstName().equals(firstname)) {
admin.setFirstName(firstname);
i++;
}
if (!admin.getLastName().equals(lastname)) {
admin.setLastName(lastname);
i++;
}
if (!admin.getEmail().equals(email)) {
admin.setEmail(email);
i++;
}
if (!password.equals("")) {
if (validate(passwordPattern, password)) {
admin.setPassword(password);
i++;
} else {
i = 0;
req.setAttribute("passwordError", "Password is not correct");
}
}
if (i > 0) {
AdminService.updateAdmin(admin);
req.getSession().setAttribute("user", admin);
req.setAttribute("successUpdate", "User profile is successfully updated");
}
Admin update = (Admin) req.getSession().getAttribute("user");
req.setAttribute("firstname", update.getFirstName());
req.setAttribute("lastname", update.getLastName());
req.setAttribute("email", update.getEmail());
return settings;
}
}
| true |