text stringlengths 10 2.72M |
|---|
package drivetrain;
import utilities.Controllers;
import edu.wpi.first.wpilibj.Joystick.RumbleType;
public class TiltDecorator extends DriveControlDecorator{ //vibrates controllers when the robot is tilted
private DriveIO driveIO = DriveIO.getInstance();
private final double rollAngle = 5, pitchAngle = 5;
public TiltDecorator(DriveControl driveControl){
super(driveControl);
}
@Override
public void execute(double x1, double y1, double x2, double y2){
//if gyro reads a large enough roll / pitch, rumble controllers
if(Math.abs(driveIO.getRoll()) > rollAngle || Math.abs(driveIO.getPitch()) > pitchAngle){
Controllers.getDriverJoystick().setRumble(RumbleType.kRightRumble, (float) 0.5);
Controllers.getOperatorJoystick().setRumble(RumbleType.kRightRumble, (float) 0.5);
Controllers.getDriverJoystick().setRumble(RumbleType.kLeftRumble, (float) 0.5);
Controllers.getOperatorJoystick().setRumble(RumbleType.kLeftRumble, (float) 0.5);
}
else{ //turn off rumble
Controllers.getDriverJoystick().setRumble(RumbleType.kRightRumble, (float) 0);
Controllers.getOperatorJoystick().setRumble(RumbleType.kRightRumble, (float) 0);
Controllers.getDriverJoystick().setRumble(RumbleType.kLeftRumble, (float) 0);
Controllers.getOperatorJoystick().setRumble(RumbleType.kLeftRumble, (float) 0);
}
super.execute(x1, y1, x2, y2);
}
}
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class MercadoriaGUI extends JFrame {
private JTextArea taLista;
private JScrollPane pLista;
public MercadoriaGUI() {
super("Mercado USJT - v.1.0");
Container tela = getContentPane();
tela.setLayout(new BorderLayout());
taLista = new JTextArea();
pLista = new JScrollPane(taLista);
tela.add(pLista, BorderLayout.CENTER);
Mercadoria mercadoria = new Mercadoria();
taLista.setText(mercadoria.getAllMercadoria());
taLista.setEditable(false);
setSize(400, 500);
setLocation(500, 400);
setVisible(true);
}
}
|
/*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.vrproject;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import com.google.ar.core.Config;
import com.google.ar.core.Session;
import com.google.ar.sceneform.ux.ArFragment;
/**
* Main Fragment for the Cloud Anchors Codelab.
*
* <p>This is where the AR Session and the Cloud Anchors are managed.
*/
public class CloudAnchorFragment extends ArFragment {
@Override
protected Config getSessionConfiguration(Session session) {
Config config = super.getSessionConfiguration(session);
config.setCloudAnchorMode(Config.CloudAnchorMode.ENABLED);
return config;
}
@Override
@SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public View onCreateView(
LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
|
package com.itheima.springboot_rabbitmq_consumer.config;
public class User {
private String name;
private Integer age;
private User(UserBuilder userBuilder) {
this.name = userBuilder.name;
this.age = userBuilder.age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public static class UserBuilder {
private String name;
private Integer age;
public UserBuilder() {
}
public UserBuilder name(String name) {
this.name = name;
return this;
}
public UserBuilder age(Integer age) {
this.age = age;
return this;
}
public User build() {
return new User(this);
}
}
}
|
/*
* Copyright 2016 Grzegorz Skorupa <g.skorupa at 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.cricketmsf.in.http;
import org.cricketmsf.Adapter;
import java.util.HashMap;
import org.cricketmsf.Kernel;
/**
*
* @author Grzegorz Skorupa <g.skorupa at gmail.com>
*/
public class ScriptingAdapter extends HttpAdapter implements HttpAdapterIface, Adapter {
private String responseType;
/**
* This method is executed while adapter is instantiated during the service
* start. It's used to configure the adapter according to the configuration.
*
* @param properties map of properties readed from the configuration file
* @param adapterName name of the adapter set in the configuration file (can
* be different from the interface and class name.
*/
@Override
public void loadProperties(HashMap<String, String> properties, String adapterName) {
super.getServiceHooks(adapterName);
setContext(properties.get("context"));
Kernel.getInstance().getLogger().print("\tcontext=" + getContext());
setResponseType(properties.getOrDefault("response-type","application/json"));
Kernel.getInstance().getLogger().print("\tresponse-type=" + getResponseType());
}
/**
* Formats response sent back by this adapter
*
* @param type ignored
* @param result received back from the service
* @return the payload field of the result modified with parameters
*/
@Override
public byte[] formatResponse(String type, Result result) {
return result.getPayload();
}
protected void setResponseType(String config) {
if(acceptedTypesMap.containsKey(config)){
responseType = config;
}else{
responseType = JSON;
}
}
/**
* @return the responseType
*/
public String getResponseType() {
return responseType;
}
}
|
package elasticsearch.plugin.level.util;
import redis.clients.jedis.Jedis;
import java.util.*;
import static elasticsearch.plugin.level.util.RedisForLevel.getSourceLevelClient;
/**
* Created by geyl on 2018/1/30.
*/
public class CheckLevelStat {
private static final int REDIS_DB = 14;
public static void main(String[] args) {
Jedis jedis = getSourceLevelClient();
if (jedis == null) {
return;
}
jedis.select(REDIS_DB);
Set<String> keys = jedis.keys("*");
Map<String, List<Double>> levelScoreMap = new HashMap<>();
for (String key : keys) {
try {
List<String> result = jedis.hmget(key, "evalLevel", "evalScore");
String level = result.get(0);
Double score = Double.valueOf(result.get(1));
if (levelScoreMap.containsKey(level)) {
levelScoreMap.get(level).add(score);
} else {
levelScoreMap.put(level, new ArrayList<>());
levelScoreMap.get(level).add(score);
}
} catch (Exception e) {
e.printStackTrace();
}
}
for (Map.Entry<String, List<Double>> entry : levelScoreMap.entrySet()) {
String level = entry.getKey();
List<Double> scores = entry.getValue();
int num = scores.size();
double sumScore = 0d;
for (Double score : scores) {
sumScore += score;
}
System.out.println("util:" + level + " num:" + num + " sumScore:" + sumScore + " avgScore:" + sumScore / num);
}
}
}
|
package JavaBasics;
import com.sun.org.apache.xpath.internal.SourceTree;
/**
* Created by RXC8414 on 5/4/2017.
*/
public class ArrayExamples {
public static void main(String[] args) {
double[] numbers = {5.6,4.5,13.2,4.0,34.33,34.0,45.45,3.3,99.993,11123};
// 1. Print out all number inside array
for(int i = 0; i < numbers.length; i++){
System.out.println(numbers[i]);
}
// 2. Print out the sum of all numbers
double sum = 0;
for(int i = 0; i < numbers.length; i++){
sum+=numbers[i]; // sum = sum + number[i]
}
System.out.println("sum="+sum);
// 3. Print out all numbers which are
// greater than 10 but less than 100
for (int i = 0; i < numbers.length; i++){
if(numbers[i] > 10 && numbers[i] < 100){
System.out.println("number:" + numbers[i]);
}
}
// 4. Print out the index occurrence of 34.33
for(int i = 0; i < numbers.length; i++){
if(numbers[i] == 34.33){
System.out.println("index: "+i);
break;
}
}
// 5. Print out the index and the value of the smallest number
double smallest = numbers[0];
int index = 0;
for (int i = 1; i < numbers.length; i++){
if(smallest > numbers[i]){
smallest = numbers[i];
index = i;
}
}
System.out.println("Smallest: "+smallest);
System.out.println("Index: "+index);
}
} |
../../../jvmti-common/Locals.java |
package co.cinemas.ingeneo.controlador;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import co.cinemas.ingeneo.modelo.dto.SalaDto;
import co.cinemas.ingeneo.persistencia.entidad.Sala;
import co.cinemas.ingeneo.persistencia.entidad.Sucursal;
import co.cinemas.ingeneo.persistencia.entidad.TipoSala;
import co.cinemas.ingeneo.servicios.ISalaService;
import co.cinemas.ingeneo.utilidad.Constantes;
import co.cinemas.ingeneo.utilidad.SalaMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
/**
* Controlador de tipo Rest para exponer las operaciones asociadas a la sala
*
* @author Roy López Cardona
*
*/
@CrossOrigin
@RestController
@RequestMapping("/api")
@Api(value = "SalaRestController")
public class SalaRestController {
@Autowired
private ISalaService salaService;
/**
* Método que permite obtener todas las salas registradas en la base de datos
*
* @return Lista de salas registradas en base de datos
*/
@GetMapping("/salas")
@ApiOperation(value = "index", notes = "Operación que permite obtener todas las salas registradas en base de datos", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiResponse(response = List.class, code = 200, message = "Lista de salas")
public List<SalaDto> index() {
return salaService.findAll().stream().map(SalaMapper::convertToDto).collect(Collectors.toList());
}
/**
* Método que permite obtener la información de una sala a partir de su
* identificador
*
* @param id El identificador de la sala
* @return Información tras realizar la operación
*/
@GetMapping("/salas/{id}")
@ApiOperation(value = "show", notes = "Operación que permite obtener una sala registrada en base de datos a partir de su identificador", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiParam(name = "id", required = true)
@ApiResponse(response = ResponseEntity.class, code = 200, message = "Información de la sala solicitada")
public ResponseEntity<?> show(@PathVariable Long id) {
Sala sala = null;
Map<String, Object> mensajes = new HashMap<>();
try {
sala = salaService.findById(id);
} catch (DataAccessException e) {
mensajes.put("mensaje", "Error al realizar la consulta en la base de datos");
mensajes.put("error", e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.INTERNAL_SERVER_ERROR);
}
if (sala == null) {
mensajes.put("mensaje", "La sala con ID: ".concat(id.toString()).concat(" no existe en la base de datos"));
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<SalaDto>(SalaMapper.convertToDto(sala), HttpStatus.OK);
}
/**
* Método que permite realizar la creación de un objeto tipo sala en la base de
* datos
*
* @param salaDto Dto con la información de la sala
* @param result Resultados de validaciones javax
* @return Información de la sala registrada
*/
@PostMapping("/salas")
@ApiOperation(value = "create", notes = "Operación que permite registrar una sala en base de datos", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiResponse(response = ResponseEntity.class, code = 200, message = "Información de la sala registrada")
public ResponseEntity<?> create(@Valid @RequestBody SalaDto salaDto, BindingResult result) {
Sala sala = SalaMapper.convertToSalaEntity(salaDto);
Map<String, Object> mensajes = new HashMap<>();
if (result.hasErrors()) {
List<String> erros = result.getFieldErrors().stream()
.map(s -> "El campo '" + s.getField() + "' " + s.getDefaultMessage())
.collect(Collectors.toCollection(ArrayList::new));
mensajes.put("errors", erros);
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.BAD_REQUEST);
}
Integer maxSillasFila = Integer
.parseInt(salaService.findConfiguracionSistemaById(Constantes.MAX_SILLAS_FILA).getValor());
if (salaDto.getMaxSillasFila().compareTo(maxSillasFila) > 0) {
mensajes.put("mensaje", "El número máximo de sillas es invalido, no debe superar " + maxSillasFila);
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.BAD_REQUEST);
}
Sucursal sucursal = salaService.findSucursalById(salaDto.getIdSucursal());
if (sucursal == null) {
mensajes.put("mensaje", "La sucursal no existe");
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.NOT_FOUND);
}
sala.setSucursal(sucursal);
TipoSala tipoSala = salaService.findTipoSalaById(salaDto.getIdTipoSala());
if (tipoSala == null) {
mensajes.put("mensaje", "El tipo de sala no existe");
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.NOT_FOUND);
}
sala.setTipoSala(tipoSala);
try {
sala = salaService.create(sala);
} catch (DataAccessException e) {
mensajes.put("mensaje", "Error al realizar el registro en la base de datos");
mensajes.put("error", e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.INTERNAL_SERVER_ERROR);
}
salaDto = SalaMapper.convertToDto(sala);
return new ResponseEntity<SalaDto>(salaDto, HttpStatus.OK);
}
/**
* Método que permite simular la disposición de sillas en una sala mediante la
* creación de una secuencia de caracteres
*
* @param filas Número de filas para la sala
* @param sillasFila Número de sillas para cada fila
* @return Cadena de caracteres
*/
@GetMapping("/salas/disposicion/{filas}/{sillas-fila}")
@ApiOperation(value = "disposicion", notes = "Operación que permite simular la disposición de la sala", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> disposicion(@PathVariable(name = "filas") Integer filas,
@PathVariable(name = "sillas-fila") Integer sillasFila) {
Map<String, Object> mensajes = new HashMap<>();
Integer maxSillasFila = Integer
.parseInt(salaService.findConfiguracionSistemaById(Constantes.MAX_SILLAS_FILA).getValor());
if (sillasFila.compareTo(maxSillasFila) > 0 || sillasFila.intValue() < 3) {
mensajes.put("mensaje",
"Número de sillas por fila es invalido, debe ser un valor entre 3 y " + maxSillasFila);
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.BAD_REQUEST);
}
if (filas.intValue() < 3 || filas.intValue() > 27) {
mensajes.put("mensaje", "Número de filas inválido, debe ser un valor entre 3 y 27");
return new ResponseEntity<Map<String, Object>>(mensajes, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<String>(salaService.crearDisposicionSala(filas, sillasFila), HttpStatus.OK);
}
}
|
// KeyboardReader.java
package org.google.code.netapps.bigdigger;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* This class is trying to read from keyboard in form of
* separate process
*
* @version 1.1 08/20/2001
* @author Alexander Shvets
*/
public class KeyboardReader implements Runnable {
private transient Thread thread;
private String line;
private BufferedReader reader;
private boolean done;
/**
* Creates new keyboard reader
*/
public KeyboardReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
/**
* Starts the process of reading
*/
public void start() {
done = false;
if(thread == null) {
thread = new Thread(this);
}
thread.start();
}
/**
* Stops the process of reading
*/
public void stop() {
done = true;
thread.interrupt();
try {
thread.join();
}
catch(InterruptedException e) {
System.out.println(e);
}
thread = null;
}
/**
* Gets the next line from the stream
*
* @return the next line from the stream
*/
public String getLine() {
return line;
}
/**
* Clears the next line
*
*/
public synchronized void nextLine() {
line = null;
}
/**
* Main thread life
*/
public void run() {
while(!done) {
try {
if(line == null) {
synchronized(this) {
line = reader.readLine();
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
String serFileName = "Test.ser";
File serFile = new File(serFileName);
ObjectSaver saver = new ObjectSaver(serFile);
int cnt = 0;
if(serFile.exists()) {
cnt = ((Integer)saver.restore()).intValue();
serFile.delete();
}
KeyboardReader keyboardReader = new KeyboardReader();
keyboardReader.start();
while(true) {
if(cnt > 10000) break;
String line = keyboardReader.getLine();
if(line != null) {
if(line.equalsIgnoreCase("q")) break;
keyboardReader.nextLine();
}
++cnt;
System.out.println(cnt);
}
keyboardReader.stop();
if(cnt < 5000) {
saver.save(new Integer(cnt));
}
}
}
|
import org.junit.runner.JUnitCore;
/**
* Created by Annag on 5/22/2017.
*/
public class Main {
public static void main(String[] args) {
JUnitCore.runClasses(TestPrimary.class);
}
}
|
package com.zevzikovas.aivaras.terraria.activities;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.zevzikovas.aivaras.terraria.R;
import com.zevzikovas.aivaras.terraria.activities.descriptions.SwordsDescriptionActivity;
import com.zevzikovas.aivaras.terraria.adapters.SwordsListAdapter;
import com.zevzikovas.aivaras.terraria.models.Swords;
import com.zevzikovas.aivaras.terraria.repositories.RepositoryManager;
import java.util.List;
public class SwordsActivity extends Activity {
ListView swordsListView;
SwordsListAdapter swordsListAdapter;
List<Swords> swords;
RepositoryManager repositoryManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swords);
repositoryManager = new RepositoryManager(this);
swords = repositoryManager.swordsRepository.getAllSword();
swordsListAdapter = new SwordsListAdapter(this, R.layout.swords_list_item, swords);
swordsListView = findViewById(R.id.SwordsList);
swordsListView.setAdapter(swordsListAdapter);
swordsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent i = new Intent(getApplicationContext(), SwordsDescriptionActivity.class);
int swordsId = swords.get(position).id;
i.putExtra("swordsId", swordsId);
startActivity(i);
}
});
}
} |
package com.example.examenmoviles2020;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.example.examenmoviles2020.Datos.Volumen;
import com.example.examenmoviles2020.WebService.Asynchtask;
import com.example.examenmoviles2020.WebService.WebService;
import com.example.examenmoviles2020.adapters.AdapterVolumenes;
import com.example.examenmoviles2020.adapters.ItemClickListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements Asynchtask, ItemClickListener {
private RecyclerView recyclerView;
private Context context;
private AdapterVolumenes adapterVolumenes;
private List<Volumen> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.rcvvolumenes);
context = this;
Map<String, String> datos = new HashMap<String, String>();
WebService ws= new WebService("http://revistas.uteq.edu.ec/ws/getrevistas.php",
datos, this, this);
ws.execute("");
}
@Override
public void onClick(View view, int position) {
String vol , numero;
numero = data.get(position).getNum();
vol = data.get(position).getVolNUm();
Intent intent = new Intent(MainActivity.this,paperActivity.class);
intent.putExtra("volumen",vol);
intent.putExtra("numero",numero);
startActivity(intent);
}
@Override
public void processFinish(String result) throws JSONException {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("issues");
//Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
Volumen volumen = new Volumen(obj.getString("title"),obj.getString("volume"),obj.getString("number"),obj.getString("date_published"),obj.getString("portada"));
data.add(volumen);
}
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);//numero columnas
adapterVolumenes = new AdapterVolumenes(context,data);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapterVolumenes);
recyclerView.setHasFixedSize(true);
adapterVolumenes.setClickListener(this);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package TSASoftwareDevelopment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.*;
/**
*
* @author Jillian To
*/
public class FillInTheBlanks extends Window {
// objects
JTextField answerFld;
// no-args constructor
public FillInTheBlanks() {
super();
createWindow();
}
private void createWindow() {
// object instantiations
answerFld = new JTextField();
// picks correct answer and what level to go to next depending on
// current level
nextBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch(Window.level) {
case 4:
if(answerFld.getText().toLowerCase().equals("pseudocode"
)) {
Window.levelUp();
JOptionPane.showMessageDialog(null, "Correct, good "
+ "job!");
Window.text = new Text();
Window.text.showWindow();
} else
JOptionPane.showMessageDialog(null, "Incorrect, try"
+ " again.");
break;
default:
JOptionPane.showMessageDialog(null, "Corrupted save, "
+ "please exit the program and delete your save"
+ " file to regenerate it.");
}
}
});
// layout
nextBtn.setText("Check Answer");
// changes question text depending on level
switch(Window.level) {
case 4:
questionLbl.setText("Fill in the blank: Algorithms are written "
+ "in __________.");
break;
default:
questionLbl.setText("Question");
}
// layout
answerFld.setBounds(((int)(Window.windowWidth*0.05)),
((int)(Window.windowHeight*0.75)),
((int)(Window.windowWidth*0.7)),
((int)(Window.windowHeight*0.05)));
// adds components to JFrame
frame.add(answerFld);
}
}
|
package com.flower.core.dao.mapper;
import java.util.List;
/**
* @author cyk
* @date 2018/7/30/030 13:51
* @email choe0227@163.com
* @desc
* @modifier
* @modify_time
* @modify_remark
*/
public interface BaseMapper<T> {
/**
* 分页查询
* @param t 依据T中不为null的属性进行查询
* @param start_time 开始时间
* @param end_time 结束时间
* @param is_desc 是否倒序
* @return 返回页码对应的数据集合
*/
List<T> listPage(T t, Long start_time, Long end_time, boolean is_desc);
/**
* 分页查询
* @param t 依据T中不为null的属性进行查询
* @return 返回页码对应的数据集合
*/
List<T> listPage(T t);
/**
* 修改数据
* (id为null,抛出异常)
* @param t 依据T中id进行修改
* @return 修改条数
*/
Integer update(T t);
/**
* 新增数据
* (无参数返回异常)
* @param t 依据不为空的字段进新增
* @return 返回条数
*/
Integer add(T t);
/**
* 依据id查询一条数据
* @param t 依据T中不为空的字段作为条件
* @return 返回单条数据
*/
T get(T t);
/**
* 依据对象属性值删除数据
* (无参数返回异常)
* @param t 依据T中不为空的字段进行删除
* @return
*/
Integer delete(T t);
/**
* 依据对象属性查询所有数据
* (无分页,全量查询)
* @param t 依据T中不为null的属性进行查询
* @param start_time 开始时间
* @param end_time 结束时间
* @param is_desc 是否倒序
* @return 数据集合
*/
List<T> select(T t, Long start_time, Long end_time, boolean is_desc);
/**
* 依据对象属性查询所有数据
* (无分页,全量查询)
* @param t 依据T中不为null的属性进行查询
* @return 数据集合
*/
List<T> select(T t);
}
|
/**
* <Date Util.>
* Copyright (C) <2009> <Wang XinFeng,ACC http://androidos.cc/dev>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package cn.itcreator.android.reader.util;
import java.util.Calendar;
import java.util.Date;
/**
* Date Util
*
* @author Wang XinFeng
* @version 1.0
*
*/
public class DateUtil {
public static String dateToString(Date d){
Calendar calendar = Calendar.getInstance();
// calendar.setTime(d);
StringBuilder sb= new StringBuilder();
sb.append(calendar.get(Calendar.YEAR));
sb.append("-");
sb.append(calendar.get(Calendar.MONTH)+1);
sb.append("-");
sb.append(calendar.get(Calendar.DATE));
sb.append(" ");
sb.append(calendar.get(Calendar.HOUR_OF_DAY));
sb.append(":");
sb.append(calendar.get(Calendar.MINUTE));
sb.append(":");
sb.append(calendar.get(Calendar.SECOND));
return sb.toString();
}
public static void main(String[] args) {
System.out.println(dateToString(new Date(System.currentTimeMillis())));
}
}
|
package com.lenovohit.ssm.treat.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class UnPayedFeeRecord {
private String prescriptionId; //
private String prescriptionDate;//
private String deptId; //
private String deptName; //
private String doctorId; //
private String doctorName; //
private String typeId; //
private String typeName; //
private BigDecimal totalAmt; //
private List<UnPayedFeeItem> items = new ArrayList<UnPayedFeeItem>();//明细
public String getPrescriptionId() {
return prescriptionId;
}
public void setPrescriptionId(String prescriptionId) {
this.prescriptionId = prescriptionId;
}
public String getPrescriptionDate() {
return prescriptionDate;
}
public void setPrescriptionDate(String prescriptionDate) {
this.prescriptionDate = prescriptionDate;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getDoctorId() {
return doctorId;
}
public void setDoctorId(String doctorId) {
this.doctorId = doctorId;
}
public String getDoctorName() {
return doctorName;
}
public void setDoctorName(String doctorName) {
this.doctorName = doctorName;
}
public String getTypeId() {
return typeId;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public BigDecimal getTotalAmt() {
return totalAmt;
}
public void setTotalAmt(BigDecimal totalAmt) {
this.totalAmt = totalAmt;
}
public List<UnPayedFeeItem> getItems() {
return items;
}
public void setItems(List<UnPayedFeeItem> items) {
this.items = items;
}
}
|
package servlets;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entidad.Alumno;
import entidad.Docente;
import entidad.Provincias;
import negocioimpl.NegocioimplAlumnos;
import negocioimpl.NegocioimplLocalidades;
import negocioimpl.NegocioimplProfesores;
import negocioimpl.NegocioimplProvincias;
/**
* Servlet implementation class ServletAdminAgregarProfesor
*/
@WebServlet("/ServletAdminAgregarProfesor")
public class ServletAdminAgregarProfesor extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletAdminAgregarProfesor() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NegocioimplProfesores negprofes = new NegocioimplProfesores();
NegocioimplProvincias negProv = new NegocioimplProvincias();
int ultlegajo = negprofes.obtenerLegProfesor() + 1;
List<Provincias> provincias = negProv.readAll();
request.setAttribute("provincias", provincias);
request.setAttribute("ultlegajo", ultlegajo);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String todaysdate = dateFormat.format(date);
request.setAttribute("today", todaysdate);
RequestDispatcher rd = request.getRequestDispatcher("/AdminAgregarProfesor.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean funco = false;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
Date fecha = cal.getTime();
String todaysdate = dateFormat.format(fecha);
request.setAttribute("today", todaysdate);
if(request.getParameter("btnAgregar")!=null)
{
NegocioimplProfesores negocioprofe = new NegocioimplProfesores();
NegocioimplLocalidades negocioloca = new NegocioimplLocalidades();
NegocioimplProvincias negocioprov = new NegocioimplProvincias();
Docente d = new Docente();
java.util.Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("DateNacimiento"));
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
d.setLegajo(0);
d.setEstado(1);
d.setDNI(Integer.parseInt(request.getParameter("txtDNI")));
d.setDireccion(request.getParameter("txtDireccion").toString());
d.setLocalidad(negocioloca.obtenerLocalidad(request.getParameter("ddlLocalidades").toString()));
d.setProvincia(negocioprov.obtenerProvincia(request.getParameter("provincia").toString()));
d.setFechaNacimiento(sqlDate);
d.setNombreyAp(request.getParameter("txtNombre").toString());
d.setTelefono(Integer.parseInt(request.getParameter("txtTelefono")));
d.setEmail(request.getParameter("txtEmail").toString());
if(negocioprofe.comprobarEmail(request.getParameter("txtEmail").toString()))
{
int repetido = 1;
request.setAttribute("repetido", repetido);
}
else
{
funco = negocioprofe.spAgregarProfesor(d);
}
List<Provincias> provincias = negocioprov.readAll();
int ultlegajo = negocioprofe.obtenerLegProfesor() + 1;
request.setAttribute("provincias", provincias);
request.setAttribute("ultlegajo", ultlegajo);
request.setAttribute("doc", d);
request.setAttribute("funco", funco);
RequestDispatcher rd = request.getRequestDispatcher("/AdminAgregarProfesor.jsp");
rd.forward(request, response);
}
else
{
doGet(request, response);
}
}
}
|
package block4;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by Hans on 18-5-2016.
*/
public class MyBasicDekkerLock implements BasicLock {
ConcurrentLinkedQueue flags;
Integer turn; //TODO: Do I really need an atomic integer?
public MyBasicDekkerLock(){
flags = new ConcurrentLinkedQueue();
turn = 0;
}
public void lock(int thread_nr) {
//Claims the resource
flags.add(thread_nr);
//Wait if the other process is using the resource
while (flags.contains(thread_nr) && flags.size() > 2){
//If waitign for the resource, also wait for our turn
if (turn != thread_nr){
//but release the resource while waiting
flags.remove(thread_nr);
while (turn != thread_nr){
//Do nothing
}
flags.add(thread_nr);
}
}
}
public void unlock(int thread_nr) {
// Pass the turn on, and release the resource
flags.remove(thread_nr);
//turn = flags.poll();
}
/*
CONCEPT: Both the turn variable and the status flags are combined in a careful way. The entry protocol begins as in Algorithm 3;
we (the requesting process) set our flag and then check our neighbor's flag. If that flag is also set, the turn variable is used.
There is no progress problem now because we know the other process is in its CS or entry protocol. If the turn is ours we wait for the flag
of the other process to clear. No process will wait indefinitely with its flag set. If the turn belongs to the other process we wait,
but we clear our flag before waiting to avoid blocking the other process. When the turn is given to us we reset our flag and proceed.
*/
}
|
package com.zhibo.duanshipin.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.zhibo.duanshipin.R;
import com.zhibo.duanshipin.utils.DisplayUtil;
import com.zhibo.duanshipin.utils.Utils;
import java.util.List;
public class GridViewAdapter extends BaseAdapter {
private Context context;
private List<String> picList;
private int height;
public GridViewAdapter(Context context, List<String> picList) {
this.context = context;
this.picList = picList;
height= (Utils.getDeviceSize(context).x- DisplayUtil.dp2px(context,38))/3*2/3;
}
@Override
public int getCount() {
return picList.size();
}
@Override
public Object getItem(int i) {
return picList == null ? null : picList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
public void setItemHeight(int height) {
this.height = height;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (i < 0 || i > picList.size() - 1) {
return null;
}
ViewHolder holder = null;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.item_grid_pic,viewGroup,false);
holder.imageView = (ImageView) view.findViewById(R.id.item_image);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
holder.imageView.setLayoutParams(lp);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if (!TextUtils.isEmpty(picList.get(i))) {
RequestOptions options = new RequestOptions();
options.placeholder(R.color.divider2).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.color.divider2).centerCrop();
Glide.with(context).load(picList.get(i))
.apply(options)
.transition(new DrawableTransitionOptions().crossFade())
.into(holder.imageView);
}
return view;
}
private class ViewHolder {
//FrameLayout frameLayout;
ImageView imageView;
}
} |
/*
* Copyright 2017 Rundeck, Inc. (http://rundeck.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.rundeck.client.api.model.metrics;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.rundeck.client.api.model.sysinfo.Link;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class EndpointListResult {
private Map<String, Link> endpointLinks;
public int size() {
return endpointLinks != null ? endpointLinks.size() : 0;
}
@JsonProperty("_links")
public Map<String, Link> getEndpointLinks() {
return endpointLinks;
}
@JsonProperty("_links")
public EndpointListResult setEndpointLinks(Map<String, Link> endpointLinks) {
this.endpointLinks = endpointLinks;
return this;
}
@Override
public String toString() {
return "EndpointListResult{" +
"endpointLinks=" + endpointLinks +
'}';
}
}
|
package falcons.server.model;
import java.util.HashMap;
import falcons.plugin.AbstractPlugin;
import falcons.plugin.Pluggable;
public class PluginModel {
private static PluginModel instance;
private static HashMap<String,Pluggable> pluginMap;
/**
* Default constructor
*/
private PluginModel() {
}
/**
*
* @return Returns this model-instance
*/
static PluginModel getInstance(){
if(instance == null){
instance = new PluginModel();
}
return instance;
}
/**
*
* @return Returns the loaded plugins
*/
static HashMap<String, Pluggable> getPlugins(){
return new HashMap<String, Pluggable>(pluginMap);
}
/**
* Sets the current map of the loaded plugins with a new one
* @param pluginMap The map to be set as the new pluginMap
*/
static void setPluginMap(HashMap<String, Pluggable> pluginMap){
PluginModel.pluginMap = pluginMap;
}
}
|
package com.gsccs.sme.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import com.gsccs.sme.api.domain.Itemtype;
import com.gsccs.sme.api.service.ConfigServiceI;
import com.gsccs.sme.api.service.SclassServiceI;
import com.gsccs.sme.api.service.SneedServiceI;
import com.gsccs.sme.api.service.AccountServiceI;
import com.gsccs.sme.web.api.service.RedisService;
/**
* 服务需求控制类
*
* @author x.d zhang
*
*/
@Controller
public class SclassController {
@Autowired
private SclassServiceI sclassAPI;
@Autowired
private ConfigServiceI configAPI;
@Autowired
private RedisService redisService;
@RequestMapping(value = "/sclassList", method = RequestMethod.POST)
@ResponseBody
public List<Itemtype> listData(Long pclassid,
Model model, HttpServletResponse response) {
List<Itemtype> sclasslist = null;
if (null==pclassid){
sclasslist = sclassAPI.getRootClass("S");
}else{
sclasslist = sclassAPI.getSubClass(pclassid);
}
return sclasslist;
}
}
|
package cn.test.demo01;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo1 {
public static void main(String[] args) {
//集合可以存储任意类型的对象,不指定存储的数据类型则什么类型的都存
Collection coll = new ArrayList();
coll.add("1qw");
//coll.add(2);
//coll.add(2.34);
coll.add("e");
Iterator it = coll.iterator();
while(it.hasNext()) {
//Object o = it.next();
//System.out.println(o);
String s = (String)it.next();//不加数据类型,不能调用子类特有的功能,应该加上数据类型
System.out.println(s.length());
}
}
}
|
package pack.cd.interfaces;
import pack.cd.CdAlbum;
import java.util.List;
public interface Sortable {
List<CdAlbum> getSortedByTitleRecords();
List<CdAlbum> getSortedByArtistRecords();
List<CdAlbum> getSortedByRecordPrice();
List<CdAlbum> getSortedByIdAsc();
List<CdAlbum> getSortedByIdDesc();
}
|
package pro.likada.model;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by abuca on 04.03.17.
*/
@Entity
@DynamicInsert
@DynamicUpdate
@Table(name="DRIVERS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Driver {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name="TITLE")
private String title;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@Column(name="PATRONYMIC")
private String patronymic;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="DATE_OF_BIRTH")
private Date dateOfBirth;
@Column(name="DOC_SERIAL")
private String docSerial;
@Column(name="DOC_NUMBER")
private String docNumber;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="DOC_GIVEN_DATE")
private Date docGivenDate;
@Column(name="DOC_GIVEN_FROM")
private String docGivenFrom;
@Column(name="DOC_CODE")
private String docCode;
@Column(name="DOC_DESCRIPTION")
private String docDescription;
@Column(name="PHONE_1")
private String phone1;
@Column(name="PHONE_2")
private String phone2;
@Column(name="PHONE_EMERGENCY")
private String phoneEmergency;
@Column(name = "description")
private String description;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "drivers")
private Set<Vehicle> vehicles;
@OneToMany(mappedBy = "driver")
private Set<Order> ordersOfDriver;
@Override
public String toString() {
return "DRIVER[" +
"id=" + id +
", TITLE='" + title +
", FIRST_NAME='" + firstName +
", LAST_NAME='" + lastName +
", PATRONYMIC='" + patronymic +
", DATE_OF_BIRTH=" + dateOfBirth +
", DOC_SERIAL='" + docSerial +
", DOC_NUMBER='" + docNumber +
", DOC_GIVEN_DATE=" + docGivenDate +
", DOC_GIVEN_FROM='" + docGivenFrom +
", DOC_CODE='" + docCode +
", DOC_DESCRIPTION='" + docDescription +
", PHONE_1='" + phone1 +
", PHONE_2='" + phone2 +
", PHONE_EMERGENCY='" + phoneEmergency +
']';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Driver)) return false;
Driver driver = (Driver) o;
if (id != null ? !id.equals(driver.id) : driver.id != null) return false;
if (title != null ? !title.equals(driver.title) : driver.title != null) return false;
if (firstName != null ? !firstName.equals(driver.firstName) : driver.firstName != null) return false;
if (lastName != null ? !lastName.equals(driver.lastName) : driver.lastName != null) return false;
if (patronymic != null ? !patronymic.equals(driver.patronymic) : driver.patronymic != null) return false;
if (dateOfBirth != null ? !dateOfBirth.equals(driver.dateOfBirth) : driver.dateOfBirth != null) return false;
if (docSerial != null ? !docSerial.equals(driver.docSerial) : driver.docSerial != null) return false;
if (docNumber != null ? !docNumber.equals(driver.docNumber) : driver.docNumber != null) return false;
if (docGivenDate != null ? !docGivenDate.equals(driver.docGivenDate) : driver.docGivenDate != null)
return false;
if (docGivenFrom != null ? !docGivenFrom.equals(driver.docGivenFrom) : driver.docGivenFrom != null)
return false;
if (docCode != null ? !docCode.equals(driver.docCode) : driver.docCode != null) return false;
if (docDescription != null ? !docDescription.equals(driver.docDescription) : driver.docDescription != null)
return false;
if (phone1 != null ? !phone1.equals(driver.phone1) : driver.phone1 != null) return false;
if (phone2 != null ? !phone2.equals(driver.phone2) : driver.phone2 != null) return false;
if (phoneEmergency != null ? !phoneEmergency.equals(driver.phoneEmergency) : driver.phoneEmergency != null)
return false;
return description != null ? description.equals(driver.description) : driver.description == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (patronymic != null ? patronymic.hashCode() : 0);
result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
result = 31 * result + (docSerial != null ? docSerial.hashCode() : 0);
result = 31 * result + (docNumber != null ? docNumber.hashCode() : 0);
result = 31 * result + (docGivenDate != null ? docGivenDate.hashCode() : 0);
result = 31 * result + (docGivenFrom != null ? docGivenFrom.hashCode() : 0);
result = 31 * result + (docCode != null ? docCode.hashCode() : 0);
result = 31 * result + (docDescription != null ? docDescription.hashCode() : 0);
result = 31 * result + (phone1 != null ? phone1.hashCode() : 0);
result = 31 * result + (phone2 != null ? phone2.hashCode() : 0);
result = 31 * result + (phoneEmergency != null ? phoneEmergency.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
return result;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String middleName) {
this.patronymic = middleName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDocSerial() {
return docSerial;
}
public void setDocSerial(String docSerial) {
this.docSerial = docSerial;
}
public String getDocNumber() {
return docNumber;
}
public void setDocNumber(String docNumber) {
this.docNumber = docNumber;
}
public Date getDocGivenDate() {
return docGivenDate;
}
public void setDocGivenDate(Date docGivenDate) {
this.docGivenDate = docGivenDate;
}
public String getDocGivenFrom() {
return docGivenFrom;
}
public void setDocGivenFrom(String docGivenFrom) {
this.docGivenFrom = docGivenFrom;
}
public String getDocCode() {
return docCode;
}
public void setDocCode(String docCode) {
this.docCode = docCode;
}
public String getDocDescription() {
return docDescription;
}
public void setDocDescription(String docDescription) {
this.docDescription = docDescription;
}
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
public String getPhoneEmergency() {
return phoneEmergency;
}
public void setPhoneEmergency(String phoneEmergency) {
this.phoneEmergency = phoneEmergency;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(Set<Vehicle> vehicles) {
this.vehicles = vehicles;
}
public List<Vehicle> getVehicleList(){
if(vehicles != null){
return new ArrayList<>(vehicles);
}
else{
return null;
}
}
public void setVehicleList(List<Vehicle> vehicleList){
if(vehicleList != null) {
this.vehicles = new HashSet<>(vehicleList);
}
else {
this.vehicles = null;
}
}
public Set<Order> getOrdersOfDriver() {
return ordersOfDriver;
}
public void setOrdersOfDriver(Set<Order> ordersOfDriver) {
this.ordersOfDriver = ordersOfDriver;
}
public String getStringOfVehicleGovNumbers(){
StringBuilder sb = new StringBuilder();
List<String> govNumberList = getVehicleList().stream()
.map(vehicle -> vehicle.getTruck().getGovNumber())
.sorted()
.collect(Collectors.toList());
for(String govNumber : govNumberList){
sb.append(govNumber);
sb.append(',');
}
if(sb.length()>0){
sb.delete(sb.length()-1,sb.length());
}
return sb.toString();
}
}
|
/**
*
*/
package com.application.beans;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author Vikalp Patel(VikalpPatelCE)
*
*/
public class MobcastFeedbackSubmit implements Parcelable {
private String mobcastFeedbackId;
private String mobcastFeedbackQueId;
private String mobcastFeedbackQueType;
private String mobcastFeedbackAnswer;
public MobcastFeedbackSubmit() {
super();
// TODO Auto-generated constructor stub
}
public MobcastFeedbackSubmit(String mobcastFeedbackId,
String mobcastFeedbackQueId, String mobcastFeedbackQueType,
String mobcastFeedbackAnswer) {
super();
this.mobcastFeedbackId = mobcastFeedbackId;
this.mobcastFeedbackQueId = mobcastFeedbackQueId;
this.mobcastFeedbackQueType = mobcastFeedbackQueType;
this.mobcastFeedbackAnswer = mobcastFeedbackAnswer;
}
public String getMobcastFeedbackId() {
return mobcastFeedbackId;
}
public void setMobcastFeedbackId(String mobcastFeedbackId) {
this.mobcastFeedbackId = mobcastFeedbackId;
}
public String getMobcastFeedbackQueId() {
return mobcastFeedbackQueId;
}
public void setMobcastFeedbackQueId(String mobcastFeedbackQueId) {
this.mobcastFeedbackQueId = mobcastFeedbackQueId;
}
public String getMobcastFeedbackQueType() {
return mobcastFeedbackQueType;
}
public void setMobcastFeedbackQueType(String mobcastFeedbackQueType) {
this.mobcastFeedbackQueType = mobcastFeedbackQueType;
}
public String getMobcastFeedbackAnswer() {
return mobcastFeedbackAnswer;
}
public void setMobcastFeedbackAnswer(String mobcastFeedbackAnswer) {
this.mobcastFeedbackAnswer = mobcastFeedbackAnswer;
}
protected MobcastFeedbackSubmit(Parcel in) {
mobcastFeedbackId = in.readString();
mobcastFeedbackQueId = in.readString();
mobcastFeedbackQueType = in.readString();
mobcastFeedbackAnswer = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mobcastFeedbackId);
dest.writeString(mobcastFeedbackQueId);
dest.writeString(mobcastFeedbackQueType);
dest.writeString(mobcastFeedbackAnswer);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<MobcastFeedbackSubmit> CREATOR = new Parcelable.Creator<MobcastFeedbackSubmit>() {
@Override
public MobcastFeedbackSubmit createFromParcel(Parcel in) {
return new MobcastFeedbackSubmit(in);
}
@Override
public MobcastFeedbackSubmit[] newArray(int size) {
return new MobcastFeedbackSubmit[size];
}
};
}
|
package does_this_linked_list_have_a_cycle;
import java.util.HashSet;
import java.util.Set;
// https://www.interviewcake.com/question/linked-list-cycles
public class App {
public static void main(String args[]) {
SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
singlyLinkedList.add(1);
singlyLinkedList.add(2);
singlyLinkedList.add(3);
singlyLinkedList.add(4);
singlyLinkedList.add(5);
singlyLinkedList.print();
System.out.println(singlyLinkedList.hasLoopInefficientSolution(singlyLinkedList.getHead()));
System.out.println(singlyLinkedList.hasLoopBestSolution(singlyLinkedList.getHead()));
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node2);
System.out.println(singlyLinkedList.hasLoopInefficientSolution(node1));
System.out.println(singlyLinkedList.hasLoopBestSolution(node1));
}
}
class SinglyLinkedList {
private Node head;
public SinglyLinkedList() {
this.head = null;
}
public void add(Object data) {
if (head == null) {
head = new Node(data);
} else {
Node newNode = new Node(data);
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(newNode);
}
}
public Node getHead() {
return head;
}
// Keep a hash set of all nodes seen so far
// O(n) time complexity, O(n) space complexity
// http://blog.ostermiller.org/find-loop-singly-linked-list
public boolean hasLoopInefficientSolution(Node head) {
Set<Node> nodesSeen = new HashSet<Node>();
Node current = head;
while (current != null) {
if (nodesSeen.contains(current)) {
return true;
}
nodesSeen.add(current);
current = current.getNext();
}
return false;
}
// Catch Loops in Two Passes
// O(n) time complexity
// http://javarevisited.blogspot.com/2013/05/find-if-linked-list-contains-loops-cycle-cyclic-circular-check.html
// http://stackoverflow.com/questions/24794467/in-tortoise-and-hare-algorithm-why-we-make-the-hare-make-2-step-forwards-and-ch
public boolean hasLoopBestSolution(Node head) {
Node fast = head;
Node slow = head;
while (fast != null && fast.getNext() != null) {
fast = fast.getNext().getNext();
slow = slow.getNext();
if (fast == slow) {
return true;
}
}
return false;
}
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.getData() + " ");
current = current.getNext();
}
System.out.println();
}
}
class Node {
private Node next;
private Object data;
public Node(Object data) {
this.next = null;
this.data = data;
}
public Node(Node next, Object data) {
this.next = next;
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
} |
package edu.cricket.api.cricketscores.task;
import com.cricketfoursix.cricketdomain.aggregate.GameAggregate;
import com.cricketfoursix.cricketdomain.repository.GamePlayerPointsRepository;
import edu.cricket.api.cricketscores.async.RefreshEventPlayerPointsTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class EventPlayerPointsTask {
private static final Logger logger = LoggerFactory.getLogger(EventPlayerPointsTask.class);
@Autowired
Map<Long, GameAggregate> liveGamesCache;
@Autowired
GamePlayerPointsRepository gamePlayerPointsRepository;
@Autowired
TaskExecutor taskExecutor;
@Autowired
RefreshEventPlayerPointsTask refreshEventPlayerPointsTask;
public void updateEventPlayerPointsAsync() {
taskExecutor.execute(refreshEventPlayerPointsTask);
}
public void updateEventPlayerPoints() {
updateEventPlayerPointsAsync();
}
}
|
package com.agamidev.newsfeedsapp.Fragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.agamidev.newsfeedsapp.Activities.MainActivity;
import com.agamidev.newsfeedsapp.Adapters.NavigationDrawerAdapter;
import com.agamidev.newsfeedsapp.Interfaces.DrawerListener;
import com.agamidev.newsfeedsapp.Models.DrawerItemModel;
import com.agamidev.newsfeedsapp.R;
import com.agamidev.newsfeedsapp.Utils.DrawerActions;
import com.agamidev.newsfeedsapp.Widget.Toaster;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
public class NavigationDrawerFragment extends Fragment implements DrawerListener {
@BindView(R.id.civ_avatar)
CircleImageView civ_avatar;
@BindView(R.id.tv_welcome)
TextView tv_welcome;
@BindView(R.id.tv_username)
TextView tv_username;
@BindView(R.id.iv_go_profile)
ImageView iv_go_profile;
@BindView(R.id.rv_drawer)
RecyclerView rv_drawer;
NavigationDrawerAdapter drawerAdapter;
ArrayList<DrawerItemModel> drawerItemsArray;
Toaster toaster;
int row_index;
DrawerActions drawerActions;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.navigation_drawer, container, false);
ButterKnife.bind(this, view);
initViews(view);
setDrawerData();
return view;
}
private void initViews(View v){
toaster = new Toaster(getActivity());
drawerItemsArray = new ArrayList<>();
drawerActions = new DrawerActions(getActivity());
}
public void setDrawerData() {
drawerItemsArray = new ArrayList<>();
drawerItemsArray.add(new DrawerItemModel(R.mipmap.explore, getString(R.string.explore), true));
drawerItemsArray.add(new DrawerItemModel(R.mipmap.live_chat, getString(R.string.live_chat), false));
drawerItemsArray.add(new DrawerItemModel(R.mipmap.gallery, getString(R.string.gallery), false));
drawerItemsArray.add(new DrawerItemModel(R.mipmap.wish_list, getString(R.string.wish_list), false));
drawerItemsArray.add(new DrawerItemModel(R.mipmap.magazine, getString(R.string.e_magazine), false));
row_index = -1;
rv_drawer.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
drawerAdapter = new NavigationDrawerAdapter(getActivity(), drawerItemsArray,this);
rv_drawer.setAdapter(drawerAdapter);
}
@Override
public int drawerItemClickListener(int itemPosition) {
MainActivity.drawerLayout.closeDrawer(Gravity.START);
row_index = itemPosition;
drawerAdapter.notifyDataSetChanged();
switch(itemPosition)
{
case 0:
drawerActions.goExplore();
break;
case 1:
drawerActions.goLiveChat();
break;
case 2:
drawerActions.goGallery();
break;
case 3:
drawerActions.goWishList();
break;
case 4:
drawerActions.goE_Magazine();
break;
default:
drawerActions.goExplore();
}
return row_index;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller.Admin;
import Business.TypeRoomBAL;
import Entity.TypeRoom;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author TUNT
*/
@ManagedBean
@RequestScoped
public class TypeRoomList {
/** Creates a new instance of TypeRoomList */
public TypeRoomList() {
}
private String redirect = "?faces-redirect=true";
private static TypeRoom typeRoom;
private String errorMessage = "none";
public TypeRoom getTypeRoom() {
return typeRoom;
}
public void setTypeRoom(TypeRoom typeRoom) {
TypeRoomList.typeRoom = typeRoom;
}
public List<TypeRoom> getTypeRoomList() {
return TypeRoomBAL.getInstance().getTypeRoomList();
}
public String getErrorMessage() {
return errorMessage;
}
public String viewTypeRoom() {
return "TypeRoomDetails" + redirect;
}
public String updateTypeRoom() {
if (TypeRoomBAL.getInstance().updateTypeRoom(typeRoom)) {
return "TypeRoomList" + redirect;
}
errorMessage = "block";
return "TypeRoomDetails" + redirect;
}
public String deleteTypeRoom() {
if (TypeRoomBAL.getInstance().deleteTypeRoom(typeRoom)) {
return "TypeRoomList" + redirect;
}
return "TypeRoomList" + redirect;
}
} |
package mx.redts.adendas.model;
// Generated 15-jul-2014 23:09:21 by Hibernate Tools 3.4.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
/**
* Perfil generated by hbm2java
*/
@Entity
@Table(name = "perfil", schema = "public")
public class Role implements GrantedAuthority {
/**
*
*/
private static final long serialVersionUID = 7359459891687275955L;
private String username;
private String autoridad;
public Role() {
}
public Role(String username, String autoridad) {
super();
this.username = username;
this.autoridad = autoridad;
}
@Column(name = "authority", nullable = false, length = 80)
public String getAuthority() {
return this.autoridad.trim();
}
@Id
@Column(name = "username", nullable = false)
// @JoinColumn(name = "username", nullable = false, insertable = false,
// updatable = false)
public String getUsername() {
return this.username;
}
public void setAuthority(String autoridad) {
this.autoridad = autoridad;
}
public void setUsername(String username) {
this.username = username;
}
// @Override
// public String toString() {
// return autoridad.trim();
// }
}
|
package com.zhaoyan.ladderball.service.event.handler;
import com.zhaoyan.ladderball.dao.match.MatchPartDao;
import com.zhaoyan.ladderball.domain.eventofmatch.db.EventOfMatch;
import com.zhaoyan.ladderball.domain.match.db.MatchPart;
public class EventXiaoJieJieShuHandler extends EventHandler {
@Override
public boolean handleAddEvent(EventOfMatch event) {
logger.debug("handleEvent() event: " + event);
MatchPartDao matchPartDao = getMatchPartDao();
MatchPart matchPart = matchPartDao.getMatchPartByMatchIdPartNumber(event.matchId, event.partNumber);
if (matchPart != null) {
matchPart.isComplete = true;
matchPartDao.modifyMatchPart(matchPart);
return true;
} else {
return false;
}
}
@Override
public boolean handleDeleteEvent(EventOfMatch event) {
// 暂时不需要处理
return true;
}
}
|
package com.citibank.ods.entity.pl.valueobject;
import java.math.BigInteger;
import java.util.Date;
import com.citibank.ods.common.entity.valueobject.BaseEntityVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.entity.pl.valueobject;
* @version 1.0
* @author gerson.a.rodrigues,Mar 13, 2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public class BaseTplClassCmplcEntityVO extends BaseEntityVO
{
private BigInteger m_classCmplcCode;
private String m_classCmplcText;
private String m_sensInd;
private Date m_lastUpdDate;
private String m_lastUpdUserId;
private String m_recStatCode;
/**
* @return Returns classCmplcCode.
*/
public BigInteger getClassCmplcCode()
{
return m_classCmplcCode;
}
/**
* @param classCmplcCode_ Field classCmplcCode to be setted.
*/
public void setClassCmplcCode( BigInteger classCmplcCode_ )
{
m_classCmplcCode = classCmplcCode_;
}
/**
* @return Returns classCmplcText.
*/
public String getClassCmplcText()
{
return m_classCmplcText;
}
/**
* @param classCmplcText_ Field classCmplcText to be setted.
*/
public void setClassCmplcText( String classCmplcText_ )
{
m_classCmplcText = classCmplcText_;
}
/**
* @return Returns lastUpdDate.
*/
public Date getLastUpdDate()
{
return m_lastUpdDate;
}
/**
* @param lastUpdDate_ Field lastUpdDate to be setted.
*/
public void setLastUpdDate( Date lastUpdDate_ )
{
m_lastUpdDate = lastUpdDate_;
}
/**
* @return Returns lastUpdUserId.
*/
public String getLastUpdUserId()
{
return m_lastUpdUserId;
}
/**
* @param lastUpdUserId_ Field lastUpdUserId to be setted.
*/
public void setLastUpdUserId( String lastUpdUserId_ )
{
m_lastUpdUserId = lastUpdUserId_;
}
/**
* @return Returns recStatCode.
*/
public String getRecStatCode()
{
return m_recStatCode;
}
/**
* @param recStatCode_ Field recStatCode to be setted.
*/
public void setRecStatCode( String recStatCode_ )
{
m_recStatCode = recStatCode_;
}
/**
* @return Returns sensInd.
*/
public String getSensInd()
{
return m_sensInd;
}
/**
* @param sensInd_ Field sensInd to be setted.
*/
public void setSensInd( String sensInd_ )
{
m_sensInd = sensInd_;
}
} |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Method;
class Circle {
Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public double getArea() {
return radius * radius * Math.PI;
}
private double radius;
}
class TestClass {
static {
sTestClassObj = new TestClass(-1, -2);
}
TestClass() {
}
TestClass(int i, int j) {
this.i = i;
this.j = j;
}
int i;
int j;
volatile int k;
TestClass next;
String str;
static int si;
static TestClass sTestClassObj;
}
class SubTestClass extends TestClass {
int k;
}
class TestClass2 {
int i;
int j;
}
class TestClass3 {
float floatField = 8.0f;
boolean test1 = true;
}
class Finalizable {
static boolean sVisited = false;
static final int VALUE1 = 0xbeef;
static final int VALUE2 = 0xcafe;
int i;
protected void finalize() {
if (i != VALUE1) {
System.out.println("Where is the beef?");
}
sVisited = true;
}
}
interface Filter {
public boolean isValid(int i);
}
public class Main {
/// CHECK-START: double Main.calcCircleArea(double) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: double Main.calcCircleArea(double) load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
static double calcCircleArea(double radius) {
return new Circle(radius).getArea();
}
/// CHECK-START: int Main.test1(TestClass, TestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test1(TestClass, TestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: NullCheck
/// CHECK-NOT: InstanceFieldGet
// Different fields shouldn't alias.
static int test1(TestClass obj1, TestClass obj2) {
obj1.i = 1;
obj2.j = 2;
return obj1.i + obj2.j;
}
/// CHECK-START: int Main.test2(TestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test2(TestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK-NOT: NullCheck
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
// Redundant store of the same value.
static int test2(TestClass obj) {
obj.j = 1;
obj.j = 1;
return obj.j;
}
/// CHECK-START: int Main.test3(TestClass) load_store_elimination (before)
/// CHECK: StaticFieldGet
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test3(TestClass) load_store_elimination (after)
/// CHECK: StaticFieldGet
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
/// CHECK-NOT: StaticFieldGet
// A new allocation (even non-singleton) shouldn't alias with pre-existing values.
static int test3(TestClass obj) {
TestClass obj1 = TestClass.sTestClassObj;
TestClass obj2 = new TestClass(); // Cannot alias with obj or obj1 which pre-exist.
obj.next = obj2; // Make obj2 a non-singleton.
// All stores below need to stay since obj/obj1/obj2 are not singletons.
obj.i = 1;
obj1.j = 2;
// Following stores won't kill values of obj.i and obj1.j.
obj2.i = 3;
obj2.j = 4;
return obj.i + obj1.j + obj2.i + obj2.j;
}
/// CHECK-START: int Main.test6(TestClass, TestClass, boolean) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test6(TestClass, TestClass, boolean) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-NOT: NullCheck
/// CHECK-NOT: InstanceFieldGet
// Setting the same value doesn't clear the value for aliased locations.
static int test6(TestClass obj1, TestClass obj2, boolean b) {
obj1.i = 1;
obj1.j = 2;
if (b) {
obj2.j = 2;
}
return obj1.j + obj2.j;
}
/// CHECK-START: int Main.test7(TestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test7(TestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
// Invocation should kill values in non-singleton heap locations.
static int test7(TestClass obj) {
obj.i = 1;
System.out.print("");
return obj.i;
}
/// CHECK-START: int Main.test8() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InvokeVirtual
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test8() load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK: InvokeVirtual
/// CHECK-NOT: NullCheck
/// CHECK-NOT: InstanceFieldGet
// Invocation should not kill values in singleton heap locations.
static int test8() {
TestClass obj = new TestClass();
obj.i = 1;
System.out.print("");
return obj.i;
}
/// CHECK-START: int Main.test9(TestClass) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test9(TestClass) load_store_elimination (after)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
// Invocation should kill values in non-singleton heap locations.
static int test9(TestClass obj) {
TestClass obj2 = new TestClass();
obj2.i = 1;
obj.next = obj2;
System.out.print("");
return obj2.i;
}
/// CHECK-START: int Main.test11(TestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test11(TestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK-NOT: NullCheck
/// CHECK-NOT: InstanceFieldGet
// Loop without heap writes.
// obj.i is actually hoisted to the loop pre-header by licm already.
static int test11(TestClass obj) {
obj.i = 1;
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += obj.i;
}
return sum;
}
/// CHECK-START: int Main.test12(TestClass, TestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
/// CHECK-START: int Main.test12(TestClass, TestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
// Loop with heap writes.
static int test12(TestClass obj1, TestClass obj2) {
obj1.i = 1;
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += obj1.i;
obj2.i = sum;
}
return sum;
}
/// CHECK-START: int Main.test13(TestClass, TestClass2) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test13(TestClass, TestClass2) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: NullCheck
/// CHECK-NOT: InstanceFieldGet
// Different classes shouldn't alias.
static int test13(TestClass obj1, TestClass2 obj2) {
obj1.i = 1;
obj2.i = 2;
return obj1.i + obj2.i;
}
/// CHECK-START: int Main.test14(TestClass, SubTestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test14(TestClass, SubTestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
// Subclass may alias with super class.
static int test14(TestClass obj1, SubTestClass obj2) {
obj1.i = 1;
obj2.i = 2;
return obj1.i;
}
/// CHECK-START: int Main.test15() load_store_elimination (before)
/// CHECK: StaticFieldSet
/// CHECK: StaticFieldSet
/// CHECK: StaticFieldGet
/// CHECK-START: int Main.test15() load_store_elimination (after)
/// CHECK: <<Const2:i\d+>> IntConstant 2
/// CHECK: StaticFieldSet
/// CHECK-NOT: StaticFieldGet
/// CHECK: Return [<<Const2>>]
// Static field access from subclass's name.
static int test15() {
TestClass.si = 1;
SubTestClass.si = 2;
return TestClass.si;
}
/// CHECK-START: int Main.test16() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test16() load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
// Test inlined constructor.
static int test16() {
TestClass obj = new TestClass(1, 2);
return obj.i + obj.j;
}
/// CHECK-START: int Main.test17() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test17() load_store_elimination (after)
/// CHECK: <<Const0:i\d+>> IntConstant 0
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
/// CHECK: Return [<<Const0>>]
// Test getting default value.
static int test17() {
TestClass obj = new TestClass();
obj.j = 1;
return obj.i;
}
/// CHECK-START: int Main.test18(TestClass) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test18(TestClass) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
// Volatile field load/store shouldn't be eliminated.
static int test18(TestClass obj) {
obj.k = 1;
return obj.k;
}
/// CHECK-START: float Main.test19(float[], float[]) load_store_elimination (before)
/// CHECK: {{f\d+}} ArrayGet
/// CHECK: {{f\d+}} ArrayGet
/// CHECK-START: float Main.test19(float[], float[]) load_store_elimination (after)
/// CHECK: {{f\d+}} ArrayGet
/// CHECK-NOT: {{f\d+}} ArrayGet
// I/F, J/D aliasing should not happen any more and LSE should eliminate the load.
static float test19(float[] fa1, float[] fa2) {
fa1[0] = fa2[0];
return fa1[0];
}
/// CHECK-START: TestClass Main.test20() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK-START: TestClass Main.test20() load_store_elimination (after)
/// CHECK: NewInstance
/// CHECK-NOT: InstanceFieldSet
// Storing default heap value is redundant if the heap location has the
// default heap value.
static TestClass test20() {
TestClass obj = new TestClass();
obj.i = 0;
return obj;
}
/// CHECK-START: void Main.test21(TestClass) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: void Main.test21(TestClass) load_store_elimination (after)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
// Loop side effects can kill heap values, stores need to be kept in that case.
static void test21(TestClass obj0) {
TestClass obj = new TestClass();
obj0.str = "abc";
obj.str = "abc";
for (int i = 0; i < 2; i++) {
// Generate some loop side effect that writes into obj.
obj.str = "def";
}
System.out.print(obj0.str.substring(0, 0) + obj.str.substring(0, 0));
}
/// CHECK-START: int Main.test22() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.test22() load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
/// CHECK-NOT: InstanceFieldGet
// For a singleton, loop side effects can kill its field values only if:
// (1) it dominiates the loop header, and
// (2) its fields are stored into inside a loop.
static int test22() {
int sum = 0;
TestClass obj1 = new TestClass();
obj1.i = 2; // This store can be eliminated since obj1 is never stored into inside a loop.
for (int i = 0; i < 2; i++) {
TestClass obj2 = new TestClass();
obj2.i = 3; // This store can be eliminated since the singleton is inside the loop.
sum += obj2.i;
}
TestClass obj3 = new TestClass();
obj3.i = 5; // This store can be eliminated since the singleton is created after the loop.
sum += obj1.i + obj3.i;
return sum;
}
/// CHECK-START: void Main.testFinalizable() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-START: void Main.testFinalizable() load_store_elimination (after)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK-NOT: InstanceFieldSet
// Allocations of finalizable objects cannot be eliminated.
static void testFinalizable() {
Finalizable finalizable = new Finalizable();
finalizable.i = Finalizable.VALUE2;
finalizable.i = Finalizable.VALUE1;
}
static java.lang.ref.WeakReference<Object> getWeakReference() {
return new java.lang.ref.WeakReference<>(new Object());
}
static void testFinalizableByForcingGc() {
testFinalizable();
java.lang.ref.WeakReference<Object> reference = getWeakReference();
Runtime runtime = Runtime.getRuntime();
for (int i = 0; i < 20; ++i) {
runtime.gc();
System.runFinalization();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
// Check to see if the weak reference has been garbage collected.
if (reference.get() == null) {
// A little bit more sleep time to make sure.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
if (!Finalizable.sVisited) {
System.out.println("finalize() not called.");
}
return;
}
}
System.out.println("testFinalizableByForcingGc() failed to force gc.");
}
/// CHECK-START: int Main.$noinline$testHSelect(boolean) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: Select
/// CHECK-START: int Main.$noinline$testHSelect(boolean) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: Select
// Test that HSelect creates alias.
static int $noinline$testHSelect(boolean b) {
if (sFlag) {
throw new Error();
}
TestClass obj = new TestClass();
TestClass obj2 = null;
obj.i = 0xdead;
if (b) {
obj2 = obj;
}
return obj2.i;
}
static int sumWithFilter(int[] array, Filter f) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
if (f.isValid(array[i])) {
sum += array[i];
}
}
return sum;
}
/// CHECK-START: int Main.sumWithinRange(int[], int, int) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.sumWithinRange(int[], int, int) load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
// A lambda-style allocation can be eliminated after inlining.
static int sumWithinRange(int[] array, final int low, final int high) {
Filter filter = new Filter() {
public boolean isValid(int i) {
return (i >= low) && (i <= high);
}
};
return sumWithFilter(array, filter);
}
private static int mI = 0;
private static float mF = 0f;
/// CHECK-START: float Main.testAllocationEliminationWithLoops() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: NewInstance
/// CHECK: NewInstance
/// CHECK-START: float Main.testAllocationEliminationWithLoops() load_store_elimination (after)
/// CHECK-NOT: NewInstance
private static float testAllocationEliminationWithLoops() {
for (int i0 = 0; i0 < 5; i0++) {
for (int i1 = 0; i1 < 5; i1++) {
for (int i2 = 0; i2 < 5; i2++) {
int lI0 = ((int) new Integer(((int) new Integer(mI))));
if (((boolean) new Boolean(false))) {
for (int i3 = 576 - 1; i3 >= 0; i3--) {
mF -= 976981405.0f;
}
}
}
}
}
return 1.0f;
}
/// CHECK-START: TestClass2 Main.testStoreStore() load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-START: TestClass2 Main.testStoreStore() load_store_elimination (after)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: InstanceFieldSet
private static TestClass2 testStoreStore() {
TestClass2 obj = new TestClass2();
obj.i = 41;
obj.j = 42;
obj.i = 41;
obj.j = 43;
return obj;
}
/// CHECK-START: void Main.testStoreStore2(TestClass2) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-START: void Main.testStoreStore2(TestClass2) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: InstanceFieldSet
private static void testStoreStore2(TestClass2 obj) {
obj.i = 41;
obj.j = 42;
obj.i = 43;
obj.j = 44;
}
/// CHECK-START: void Main.testStoreStore3(TestClass2, boolean) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-START: void Main.testStoreStore3(TestClass2, boolean) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: InstanceFieldSet
private static void testStoreStore3(TestClass2 obj, boolean flag) {
obj.i = 41;
obj.j = 42; // redundant since it's overwritten in both branches below.
if (flag) {
obj.j = 43;
} else {
obj.j = 44;
}
}
/// CHECK-START: void Main.testStoreStore4() load_store_elimination (before)
/// CHECK: StaticFieldSet
/// CHECK: StaticFieldSet
/// CHECK-START: void Main.testStoreStore4() load_store_elimination (after)
/// CHECK: StaticFieldSet
/// CHECK-NOT: StaticFieldSet
private static void testStoreStore4() {
TestClass.si = 61;
TestClass.si = 62;
}
/// CHECK-START: int Main.testStoreStore5(TestClass2, TestClass2) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
/// CHECK-START: int Main.testStoreStore5(TestClass2, TestClass2) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
private static int testStoreStore5(TestClass2 obj1, TestClass2 obj2) {
obj1.i = 71; // This store is needed since obj2.i may load from it.
int i = obj2.i;
obj1.i = 72;
return i;
}
/// CHECK-START: int Main.testStoreStore6(TestClass2, TestClass2) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
/// CHECK-START: int Main.testStoreStore6(TestClass2, TestClass2) load_store_elimination (after)
/// CHECK-NOT: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
private static int testStoreStore6(TestClass2 obj1, TestClass2 obj2) {
obj1.i = 81; // This store is not needed since obj2.j cannot load from it.
int j = obj2.j;
obj1.i = 82;
return j;
}
/// CHECK-START: int Main.testNoSideEffects(int[]) load_store_elimination (before)
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testNoSideEffects(int[]) load_store_elimination (after)
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK-NOT: ArraySet
/// CHECK-NOT: ArrayGet
private static int testNoSideEffects(int[] array) {
array[0] = 101;
array[1] = 102;
int bitCount = Integer.bitCount(0x3456);
array[1] = 103;
return array[0] + bitCount;
}
/// CHECK-START: void Main.testThrow(TestClass2, java.lang.Exception) load_store_elimination (before)
/// CHECK: InstanceFieldSet
/// CHECK: Throw
/// CHECK-START: void Main.testThrow(TestClass2, java.lang.Exception) load_store_elimination (after)
/// CHECK: InstanceFieldSet
/// CHECK: Throw
// Make sure throw keeps the store.
private static void testThrow(TestClass2 obj, Exception e) throws Exception {
obj.i = 55;
throw e;
}
/// CHECK-START: int Main.testStoreStoreWithDeoptimize(int[]) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK: Deoptimize
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testStoreStoreWithDeoptimize(int[]) load_store_elimination (after)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldSet
/// CHECK-NOT: InstanceFieldSet
/// CHECK: Deoptimize
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK-NOT: ArrayGet
private static int testStoreStoreWithDeoptimize(int[] arr) {
TestClass2 obj = new TestClass2();
obj.i = 41;
obj.j = 42;
obj.i = 41;
obj.j = 43;
arr[0] = 1; // One HDeoptimize here.
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
return arr[0] + arr[1] + arr[2] + arr[3];
}
/// CHECK-START: double Main.getCircleArea(double, boolean) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK-START: double Main.getCircleArea(double, boolean) load_store_elimination (after)
/// CHECK-NOT: NewInstance
private static double getCircleArea(double radius, boolean b) {
double area = 0d;
if (b) {
area = new Circle(radius).getArea();
}
return area;
}
/// CHECK-START: double Main.testDeoptimize(int[], double[], double) load_store_elimination (before)
/// CHECK: Deoptimize
/// CHECK: NewInstance
/// CHECK: Deoptimize
/// CHECK: NewInstance
/// CHECK-START: double Main.testDeoptimize(int[], double[], double) load_store_elimination (after)
/// CHECK: Deoptimize
/// CHECK: NewInstance
/// CHECK: Deoptimize
/// CHECK-NOT: NewInstance
private static double testDeoptimize(int[] iarr, double[] darr, double radius) {
iarr[0] = 1; // One HDeoptimize here. Not triggered.
iarr[1] = 1;
Circle circle1 = new Circle(radius);
iarr[2] = 1;
darr[0] = circle1.getRadius(); // One HDeoptimize here, which holds circle1 live. Triggered.
darr[1] = circle1.getRadius();
darr[2] = circle1.getRadius();
darr[3] = circle1.getRadius();
return new Circle(Math.PI).getArea();
}
/// CHECK-START: int Main.testAllocationEliminationOfArray1() load_store_elimination (before)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testAllocationEliminationOfArray1() load_store_elimination (after)
/// CHECK-NOT: NewArray
/// CHECK-NOT: ArraySet
/// CHECK-NOT: ArrayGet
private static int testAllocationEliminationOfArray1() {
int[] array = new int[4];
array[2] = 4;
array[3] = 7;
return array[0] + array[1] + array[2] + array[3];
}
/// CHECK-START: int Main.testAllocationEliminationOfArray2() load_store_elimination (before)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testAllocationEliminationOfArray2() load_store_elimination (after)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
private static int testAllocationEliminationOfArray2() {
// Cannot eliminate array allocation since array is accessed with non-constant
// index (only 3 elements to prevent vectorization of the reduction).
int[] array = new int[3];
array[1] = 4;
array[2] = 7;
int sum = 0;
for (int e : array) {
sum += e;
}
return sum;
}
/// CHECK-START: int Main.testAllocationEliminationOfArray3(int) load_store_elimination (before)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testAllocationEliminationOfArray3(int) load_store_elimination (after)
/// CHECK-NOT: NewArray
/// CHECK-NOT: ArraySet
/// CHECK-NOT: ArrayGet
private static int testAllocationEliminationOfArray3(int i) {
int[] array = new int[4];
array[i] = 4;
return array[i];
}
/// CHECK-START: int Main.testAllocationEliminationOfArray4(int) load_store_elimination (before)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testAllocationEliminationOfArray4(int) load_store_elimination (after)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK-NOT: ArrayGet
private static int testAllocationEliminationOfArray4(int i) {
// Cannot eliminate array allocation due to index aliasing between 1 and i.
int[] array = new int[4];
array[1] = 2;
array[i] = 4;
return array[1] + array[i];
}
/// CHECK-START: int Main.testAllocationEliminationOfArray5(int) load_store_elimination (before)
/// CHECK: NewArray
/// CHECK: ArraySet
/// CHECK: ArrayGet
/// CHECK-START: int Main.testAllocationEliminationOfArray5(int) load_store_elimination (after)
/// CHECK: NewArray
/// CHECK-NOT: ArraySet
/// CHECK-NOT: ArrayGet
private static int testAllocationEliminationOfArray5(int i) {
// Cannot eliminate array allocation due to unknown i that may
// cause NegativeArraySizeException.
int[] array = new int[i];
array[1] = 12;
return array[1];
}
/// CHECK-START: int Main.testExitMerge(boolean) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: Return
/// CHECK: InstanceFieldSet
/// CHECK: Throw
/// CHECK-START: int Main.testExitMerge(boolean) load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
/// CHECK: Return
/// CHECK-NOT: InstanceFieldSet
/// CHECK: Throw
private static int testExitMerge(boolean cond) {
TestClass obj = new TestClass();
if (cond) {
obj.i = 1;
return obj.i + 1;
} else {
obj.i = 2;
throw new Error();
}
}
/// CHECK-START: int Main.testExitMerge2(boolean) load_store_elimination (before)
/// CHECK: NewInstance
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK: InstanceFieldSet
/// CHECK: InstanceFieldGet
/// CHECK-START: int Main.testExitMerge2(boolean) load_store_elimination (after)
/// CHECK-NOT: NewInstance
/// CHECK-NOT: InstanceFieldSet
/// CHECK-NOT: InstanceFieldGet
private static int testExitMerge2(boolean cond) {
TestClass obj = new TestClass();
int res;
if (cond) {
obj.i = 1;
res = obj.i + 1;
} else {
obj.i = 2;
res = obj.j + 2;
}
return res;
}
/// CHECK-START: void Main.testStoreSameValue() load_store_elimination (before)
/// CHECK: NewArray
/// CHECK: ArrayGet
/// CHECK: ArraySet
/// CHECK-START: void Main.testStoreSameValue() load_store_elimination (after)
/// CHECK: NewArray
/// CHECK-NOT: ArrayGet
/// CHECK-NOT: ArraySet
private static void testStoreSameValue() {
Object[] array = new Object[2];
sArray = array;
Object obj = array[0];
array[1] = obj; // store the same value as the defaut value.
}
static Object[] sArray;
/// CHECK-START: int Main.testLocalArrayMerge1(boolean) load_store_elimination (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1
/// CHECK-DAG: <<A:l\d+>> NewArray
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const0>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const1>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const1>>]
/// CHECK-DAG: <<Get:i\d+>> ArrayGet [<<A>>,<<Const0>>]
/// CHECK-DAG: Return [<<Get>>]
//
/// CHECK-START: int Main.testLocalArrayMerge1(boolean) load_store_elimination (after)
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1
/// CHECK-DAG: Return [<<Const1>>]
//
/// CHECK-START: int Main.testLocalArrayMerge1(boolean) load_store_elimination (after)
/// CHECK-NOT: NewArray
/// CHECK-NOT: ArraySet
/// CHECK-NOT: ArrayGet
private static int testLocalArrayMerge1(boolean x) {
// The explicit store can be removed right away
// since it is equivalent to the default.
int[] a = { 0 };
// The diamond pattern stores/load can be replaced
// by the direct value.
if (x) {
a[0] = 1;
} else {
a[0] = 1;
}
return a[0];
}
/// CHECK-START: int Main.testLocalArrayMerge2(boolean) load_store_elimination (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1
/// CHECK-DAG: <<Const2:i\d+>> IntConstant 2
/// CHECK-DAG: <<Const3:i\d+>> IntConstant 3
/// CHECK-DAG: <<A:l\d+>> NewArray
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const1>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const2>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const3>>]
/// CHECK-DAG: <<Get:i\d+>> ArrayGet [<<A>>,<<Const0>>]
/// CHECK-DAG: Return [<<Get>>]
//
/// CHECK-START: int Main.testLocalArrayMerge2(boolean) load_store_elimination (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0
/// CHECK-DAG: <<A:l\d+>> NewArray
/// CHECK-DAG: <<Get:i\d+>> ArrayGet [<<A>>,<<Const0>>]
/// CHECK-DAG: Return [<<Get>>]
//
/// CHECK-START: int Main.testLocalArrayMerge2(boolean) load_store_elimination (after)
/// CHECK-DAG: ArraySet
/// CHECK-DAG: ArraySet
/// CHECK-NOT: ArraySet
private static int testLocalArrayMerge2(boolean x) {
// The explicit store can be removed eventually even
// though it is not equivalent to the default.
int[] a = { 1 };
// The diamond pattern stores/load remain.
if (x) {
a[0] = 2;
} else {
a[0] = 3;
}
return a[0];
}
/// CHECK-START: int Main.testLocalArrayMerge3(boolean) load_store_elimination (after)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1
/// CHECK-DAG: <<Const2:i\d+>> IntConstant 2
/// CHECK-DAG: <<A:l\d+>> NewArray
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const1>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const2>>]
/// CHECK-DAG: <<Get:i\d+>> ArrayGet [<<A>>,<<Const0>>]
/// CHECK-DAG: Return [<<Get>>]
private static int testLocalArrayMerge3(boolean x) {
// All stores/load remain.
int[] a = { 1 };
if (x) {
a[0] = 2;
}
return a[0];
}
/// CHECK-START: int Main.testLocalArrayMerge4(boolean) load_store_elimination (before)
/// CHECK-DAG: <<Const0:i\d+>> IntConstant 0
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1
/// CHECK-DAG: <<A:l\d+>> NewArray
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const0>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const1>>]
/// CHECK-DAG: ArraySet [<<A>>,<<Const0>>,<<Const1>>]
/// CHECK-DAG: <<Get1:b\d+>> ArrayGet [<<A>>,<<Const0>>]
/// CHECK-DAG: <<Get2:a\d+>> ArrayGet [<<A>>,<<Const0>>]
/// CHECK-DAG: <<Add:i\d+>> Add [<<Get1>>,<<Get2>>]
/// CHECK-DAG: Return [<<Add>>]
//
/// CHECK-START: int Main.testLocalArrayMerge4(boolean) load_store_elimination (after)
/// CHECK-DAG: <<Const1:i\d+>> IntConstant 1
/// CHECK-DAG: <<Cnv1:b\d+>> TypeConversion [<<Const1>>]
/// CHECK-DAG: <<Cnv2:a\d+>> TypeConversion [<<Const1>>]
/// CHECK-DAG: <<Add:i\d+>> Add [<<Cnv1>>,<<Cnv2>>]
/// CHECK-DAG: Return [<<Add>>]
//
/// CHECK-START: int Main.testLocalArrayMerge4(boolean) load_store_elimination (after)
/// CHECK-NOT: NewArray
/// CHECK-NOT: ArraySet
/// CHECK-NOT: ArrayGet
private static int testLocalArrayMerge4(boolean x) {
byte[] a = { 0 };
if (x) {
a[0] = 1;
} else {
a[0] = 1;
}
// Differently typed (signed vs unsigned),
// but same reference.
return a[0] + (a[0] & 0xff);
}
static void assertIntEquals(int result, int expected) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
static void assertFloatEquals(float result, float expected) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
static void assertDoubleEquals(double result, double expected) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
public static void main(String[] args) throws Exception {
Class main2 = Class.forName("Main2");
Method test4 = main2.getMethod("test4", TestClass.class, boolean.class);
Method test5 = main2.getMethod("test5", TestClass.class, boolean.class);
Method test10 = main2.getMethod("test10", TestClass.class);
Method test23 = main2.getMethod("test23", boolean.class);
Method test24 = main2.getMethod("test24");
assertDoubleEquals(Math.PI * Math.PI * Math.PI, calcCircleArea(Math.PI));
assertIntEquals(test1(new TestClass(), new TestClass()), 3);
assertIntEquals(test2(new TestClass()), 1);
TestClass obj1 = new TestClass();
TestClass obj2 = new TestClass();
obj1.next = obj2;
assertIntEquals(test3(obj1), 10);
assertIntEquals((int)test4.invoke(null, new TestClass(), true), 1);
assertIntEquals((int)test4.invoke(null, new TestClass(), false), 1);
assertIntEquals((int)test5.invoke(null, new TestClass(), true), 1);
assertIntEquals((int)test5.invoke(null, new TestClass(), false), 2);
assertIntEquals(test6(new TestClass(), new TestClass(), true), 4);
assertIntEquals(test6(new TestClass(), new TestClass(), false), 2);
assertIntEquals(test7(new TestClass()), 1);
assertIntEquals(test8(), 1);
obj1 = new TestClass();
obj2 = new TestClass();
obj1.next = obj2;
assertIntEquals(test9(new TestClass()), 1);
assertIntEquals((int)test10.invoke(null, new TestClass(3, 4)), 3);
assertIntEquals(TestClass.si, 3);
assertIntEquals(test11(new TestClass()), 10);
assertIntEquals(test12(new TestClass(), new TestClass()), 10);
assertIntEquals(test13(new TestClass(), new TestClass2()), 3);
SubTestClass obj3 = new SubTestClass();
assertIntEquals(test14(obj3, obj3), 2);
assertIntEquals(test15(), 2);
assertIntEquals(test16(), 3);
assertIntEquals(test17(), 0);
assertIntEquals(test18(new TestClass()), 1);
float[] fa1 = { 0.8f };
float[] fa2 = { 1.8f };
assertFloatEquals(test19(fa1, fa2), 1.8f);
assertFloatEquals(test20().i, 0);
test21(new TestClass());
assertIntEquals(test22(), 13);
assertIntEquals((int)test23.invoke(null, true), 4);
assertIntEquals((int)test23.invoke(null, false), 5);
assertFloatEquals((float)test24.invoke(null), 8.0f);
testFinalizableByForcingGc();
assertIntEquals($noinline$testHSelect(true), 0xdead);
int[] array = {2, 5, 9, -1, -3, 10, 8, 4};
assertIntEquals(sumWithinRange(array, 1, 5), 11);
assertFloatEquals(testAllocationEliminationWithLoops(), 1.0f);
assertFloatEquals(mF, 0f);
assertDoubleEquals(Math.PI * Math.PI * Math.PI, getCircleArea(Math.PI, true));
assertDoubleEquals(0d, getCircleArea(Math.PI, false));
int[] iarray = {0, 0, 0};
double[] darray = {0d, 0d, 0d};
try {
assertDoubleEquals(Math.PI * Math.PI * Math.PI, testDeoptimize(iarray, darray, Math.PI));
} catch (Exception e) {
System.out.println(e);
}
assertIntEquals(iarray[0], 1);
assertIntEquals(iarray[1], 1);
assertIntEquals(iarray[2], 1);
assertDoubleEquals(darray[0], Math.PI);
assertDoubleEquals(darray[1], Math.PI);
assertDoubleEquals(darray[2], Math.PI);
assertIntEquals(testAllocationEliminationOfArray1(), 11);
assertIntEquals(testAllocationEliminationOfArray2(), 11);
assertIntEquals(testAllocationEliminationOfArray3(2), 4);
assertIntEquals(testAllocationEliminationOfArray4(2), 6);
assertIntEquals(testAllocationEliminationOfArray5(2), 12);
try {
testAllocationEliminationOfArray5(-2);
} catch (NegativeArraySizeException e) {
System.out.println("Got NegativeArraySizeException.");
}
assertIntEquals(testStoreStore().i, 41);
assertIntEquals(testStoreStore().j, 43);
assertIntEquals(testExitMerge(true), 2);
assertIntEquals(testExitMerge2(true), 2);
assertIntEquals(testExitMerge2(false), 2);
TestClass2 testclass2 = new TestClass2();
testStoreStore2(testclass2);
assertIntEquals(testclass2.i, 43);
assertIntEquals(testclass2.j, 44);
testStoreStore3(testclass2, true);
assertIntEquals(testclass2.i, 41);
assertIntEquals(testclass2.j, 43);
testStoreStore3(testclass2, false);
assertIntEquals(testclass2.i, 41);
assertIntEquals(testclass2.j, 44);
testStoreStore4();
assertIntEquals(TestClass.si, 62);
int ret = testStoreStore5(testclass2, testclass2);
assertIntEquals(testclass2.i, 72);
assertIntEquals(ret, 71);
testclass2.j = 88;
ret = testStoreStore6(testclass2, testclass2);
assertIntEquals(testclass2.i, 82);
assertIntEquals(ret, 88);
ret = testNoSideEffects(iarray);
assertIntEquals(iarray[0], 101);
assertIntEquals(iarray[1], 103);
assertIntEquals(ret, 108);
try {
testThrow(testclass2, new Exception());
} catch (Exception e) {}
assertIntEquals(testclass2.i, 55);
assertIntEquals(testStoreStoreWithDeoptimize(new int[4]), 4);
assertIntEquals(testLocalArrayMerge1(true), 1);
assertIntEquals(testLocalArrayMerge1(false), 1);
assertIntEquals(testLocalArrayMerge2(true), 2);
assertIntEquals(testLocalArrayMerge2(false), 3);
assertIntEquals(testLocalArrayMerge3(true), 2);
assertIntEquals(testLocalArrayMerge3(false), 1);
assertIntEquals(testLocalArrayMerge4(true), 2);
assertIntEquals(testLocalArrayMerge4(false), 2);
}
static boolean sFlag;
}
|
package com.precipicegames.zeryl.hidenseek;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
/**
*
* @author Zeryl
*/
public class HideNSeekPlayerListener implements Listener {
private final HideNSeek plugin;
public HideNSeekPlayerListener(HideNSeek instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
plugin.removePlayer(player);
}
} |
/**
* Support classes for the open source cache in
* <a href="https://github.com/ben-manes/caffeine/">Caffeine</a> library,
* allowing to set up Caffeine caches within Spring's cache abstraction.
*/
@NonNullApi
@NonNullFields
package org.springframework.cache.caffeine;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.hamatus.repository.search;
import com.hamatus.domain.SectorTranslation;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data ElasticSearch repository for the SectorTranslation entity.
*/
public interface SectorTranslationSearchRepository extends ElasticsearchRepository<SectorTranslation, Long> {
}
|
package com.needii.dashboard.model.form;
import com.needii.dashboard.model.DeliveryOrder;
import java.util.Date;
public class DeliveryOrderForm {
private long id;
private Long shippersId;
private Long customerIdCallShipper;
private String orderCode;
private String merchantOrderId;
private Integer paymentType;
private Integer deliveryOrderStatus;
private Long shipFee;
private Long extendFee;
private Long discountPrice;
private Long totalFee;
private Double orgLat;
private Double orgLng;
private Double desLat;
private Double desLng;
private Date deliveryDate;
private String deliveryTime;
private String orderNote;
private String shippersNote;
private String reasonCancel;
private String promotionalCode;
private Integer deliveryOrderShippingType;
private String customerName;
private String phoneNumber;
private String buildingFloorCustomer;
private String receiverName;
private String receiverPhoneNumber;
private String buildingFloorReceiver;
private Integer paymentTypePickupUser;
private Integer paymentTypeCarry;
public DeliveryOrderForm(){
super();
}
public DeliveryOrderForm(DeliveryOrder entity) {
this.id = entity.getId();
//this.shippersId = entity.getShipper().getId();
this.shippersId = entity.getShippersId();
this.customerIdCallShipper = entity.getCustomer().getId();
this.orderCode = entity.getOrderCode();
this.merchantOrderId = entity.getMerchantOrderId();
this.paymentType = entity.getPaymentType();
this.deliveryOrderStatus = entity.getDeliveryOrderStatus();
this.shipFee = entity.getShipFee();
this.extendFee = entity.getExtendFee();
this.discountPrice = entity.getDiscountPrice();
this.totalFee = entity.getTotalFee();
this.orgLat = entity.getOrgLat();
this.orgLng = entity.getOrgLng();
this.desLat = entity.getDesLat();
this.desLng = entity.getDesLng();
this.deliveryDate = entity.getDeliveryDate();
this.deliveryTime = entity.getDeliveryTime();
this.orderNote = entity.getOrderNote();
this.shippersNote = entity.getShippersNote();
this.reasonCancel = entity.getReasonCancel();
this.promotionalCode = entity.getPromotion().getCode();
this.deliveryOrderStatus = entity.getDeliveryOrderStatus();
this.deliveryOrderShippingType = entity.getDeliveryOrderShippingType();
this.customerName = entity.getCustomerName();
this.phoneNumber = entity.getPhoneNumber();
this.buildingFloorCustomer = entity.getBuildingFloorCustomer();
this.receiverName = entity.getReceiverName();
this.receiverPhoneNumber = entity.getReceiverPhoneNumber();
this.buildingFloorReceiver = entity.getBuildingFloorReceiver();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Long getShippersId() {
return shippersId;
}
public void setShippersId(Long shippersId) {
this.shippersId = shippersId;
}
public Long getCustomerIdCallShipper() {
return customerIdCallShipper;
}
public void setCustomerIdCallShipper(Long customerIdCallShipper) {
this.customerIdCallShipper = customerIdCallShipper;
}
public String getOrderCode() {
return orderCode;
}
public void setOrderCode(String orderCode) {
this.orderCode = orderCode;
}
public String getMerchantOrderId() {
return merchantOrderId;
}
public void setMerchantOrderId(String merchantOrderId) {
this.merchantOrderId = merchantOrderId;
}
public Integer getPaymentType() {
return paymentType;
}
public void setPaymentType(Integer paymentType) {
this.paymentType = paymentType;
}
public Integer getDeliveryOrderStatus() {
return deliveryOrderStatus;
}
public void setDeliveryOrderStatus(Integer deliveryOrderStatus) {
this.deliveryOrderStatus = deliveryOrderStatus;
}
public Long getShipFee() {
return shipFee;
}
public void setShipFee(Long shipFee) {
this.shipFee = shipFee;
}
public Long getExtendFee() {
return extendFee;
}
public void setExtendFee(Long extendFee) {
this.extendFee = extendFee;
}
public Long getDiscountPrice() {
return discountPrice;
}
public void setDiscountPrice(Long discountPrice) {
this.discountPrice = discountPrice;
}
public Long getTotalFee() {
return totalFee;
}
public void setTotalFee(Long totalFee) {
this.totalFee = totalFee;
}
public Double getOrgLat() {
return orgLat;
}
public void setOrgLat(Double orgLat) {
this.orgLat = orgLat;
}
public Double getOrgLng() {
return orgLng;
}
public void setOrgLng(Double orgLng) {
this.orgLng = orgLng;
}
public Double getDesLat() {
return desLat;
}
public void setDesLat(Double desLat) {
this.desLat = desLat;
}
public Double getDesLng() {
return desLng;
}
public void setDesLng(Double desLng) {
this.desLng = desLng;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public String getDeliveryTime() {
return deliveryTime;
}
public void setDeliveryTime(String deliveryTime) {
this.deliveryTime = deliveryTime;
}
public String getOrderNote() {
return orderNote;
}
public void setOrderNote(String orderNote) {
this.orderNote = orderNote;
}
public String getShippersNote() {
return shippersNote;
}
public void setShippersNote(String shippersNote) {
this.shippersNote = shippersNote;
}
public String getReasonCancel() {
return reasonCancel;
}
public void setReasonCancel(String reasonCancel) {
this.reasonCancel = reasonCancel;
}
public String getPromotionalCode() {
return promotionalCode;
}
public void setPromotionalCode(String promotionalCode) {
this.promotionalCode = promotionalCode;
}
public Integer getDeliveryOrderShippingType() {
return deliveryOrderShippingType;
}
public void setDeliveryOrderShippingType(Integer deliveryOrderShippingType) {
this.deliveryOrderShippingType = deliveryOrderShippingType;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getBuildingFloorCustomer() {
return buildingFloorCustomer;
}
public void setBuildingFloorCustomer(String buildingFloorCustomer) {
this.buildingFloorCustomer = buildingFloorCustomer;
}
public String getReceiverName() {
return receiverName;
}
public void setReceiverName(String receiverName) {
this.receiverName = receiverName;
}
public String getReceiverPhoneNumber() {
return receiverPhoneNumber;
}
public void setReceiverPhoneNumber(String receiverPhoneNumber) {
this.receiverPhoneNumber = receiverPhoneNumber;
}
public String getBuildingFloorReceiver() {
return buildingFloorReceiver;
}
public void setBuildingFloorReceiver(String buildingFloorReceiver) {
this.buildingFloorReceiver = buildingFloorReceiver;
}
public Integer getPaymentTypePickupUser() {
return paymentTypePickupUser;
}
public void setPaymentTypePickupUser(Integer paymentTypePickupUser) {
this.paymentTypePickupUser = paymentTypePickupUser;
}
public Integer getPaymentTypeCarry() {
return paymentTypeCarry;
}
public void setPaymentTypeCarry(Integer paymentTypeCarry) {
this.paymentTypeCarry = paymentTypeCarry;
}
}
|
package com.hd.stepbar.indicator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hd.stepbar.R;
import com.hd.stepbar.StepBarBean;
import com.hd.stepbar.StepBarConfig;
import com.hd.stepbar.animator.StepBarAnimator;
import java.util.LinkedList;
/**
* Created by hd on 2017/12/30 .
* step bar
*/
public abstract class StepBarViewIndicator extends VIndicator {
private String TAG = StepBarViewIndicator.class.getSimpleName();
protected StepBarConfig config;
protected Paint mainPaint, runPaint;
protected float iconRadius, outsideIconRingRadius;
protected float textSize;
protected float availableTextWidth;
protected float paddingRight, paddingLeft, paddingTop, paddingBottom;
protected float middleMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 10, getResources().getDisplayMetrics());
protected float connectLineLength;
/**
* all icon center point position
*/
protected LinkedList<Point> centerPointList = new LinkedList<>();
/**
* all icon rect position
*/
protected Rect[] iconRectArray;
/**
* all text rect position
*/
protected Rect[] textRectArray;
/**
* all text drawable position
*/
protected Drawable[] textDrawableArray;
/**
* all icon drawable position
*/
protected Drawable[] iconDrawableArray;
/**
* all connect line position ,
* connectLineArray[0] show {@link #position},
* connectLineArray[position] ={startX, startY, stopX, stopY}
*/
protected float[][] connectLineArray;
/**
* current running state icon position
*/
protected int position = -1;
protected StepBarAnimator ringAnimator;
/**
* step bar orientation ,0: horizontal, 1 :vertical
*/
private int orientation;
protected Paint initSmoothPaint() {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(2);
return paint;
}
protected void init() {
mainPaint = initSmoothPaint();
runPaint = initSmoothPaint();
if (config != null && config.getBeanList() != null) {
iconRectArray = new Rect[config.getBeanList().size()];
textRectArray = new Rect[config.getBeanList().size()];
textDrawableArray = new Drawable[config.getBeanList().size()];
iconDrawableArray = new Drawable[config.getBeanList().size()];
connectLineArray = new float[config.getBeanList().size() - 1][4];
setPaintTextSize();
checkStartPosition();
startRingAnimator();
}
}
protected void checkStartPosition() {
for (StepBarBean bean : config.getBeanList()) {
if (bean.getState() == StepBarConfig.StepSate.RUNNING) {
position = config.getBeanList().indexOf(bean);
break;
}
}
if (position < 0)
position = 0;
}
protected void setPaintTextSize() {
textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, config.getTextSize(), getResources().getDisplayMetrics());
}
protected float[] measureFontSize(String text, float size) {
float[] fontSize = new float[2];
Rect rect = new Rect();
Paint paint = new Paint();
paint.setTextSize(size);
paint.getTextBounds(text, 0, text.length(), rect);
fontSize[0] = rect.right - rect.left;
fontSize[1] = rect.bottom - rect.top;
return fontSize;
}
protected float[] measureFontSize(String text) {
return measureFontSize(text, textSize);
}
protected float[] measureFontSize() {
return measureFontSize(getResources().getString(R.string.test_text));
}
protected void stopRingAnimator() {
post(new Runnable() {
@Override
public void run() {
if (ringAnimator != null) {
ringAnimator.cancelAnimator();
ringAnimator = null;
}
}
});
}
protected void startRingAnimator() {
if (config.getOutSideIconRingCallback() == null)
post(new Runnable() {
@Override
public void run() {
initOutSideRingAnimator();
}
});
}
protected void initOutSideRingAnimator() {
ringAnimator = new StepBarAnimator();
Path path = new Path();
Point point = centerPointList.get(position);
path.addCircle(point.x, point.y, outsideIconRingRadius, Path.Direction.CW);
ringAnimator.createAnimator(path, 800, ValueAnimator.INFINITE);
}
/**
* start draw step bar
*/
protected void startDraw(Canvas canvas) {
for (int index = 0, count = centerPointList.size(); index < count; index++) {
Point point = centerPointList.get(index);
StepBarBean bean = config.getBeanList().get(index);
drawIconAndText(index, canvas);
drawConnectLine(canvas, index, bean);
drawRing(canvas, point, bean);
}
}
/**
* draw icon and text
*/
protected void drawIconAndText(int index, Canvas canvas) {
//draw icon
Drawable drawable = iconDrawableArray[index];
Rect bounds = iconRectArray[index];
drawable.setBounds(bounds);
drawable.draw(canvas);
//draw text
drawable = textDrawableArray[index];
bounds = textRectArray[index];
drawable.setBounds(bounds);
drawable.draw(canvas);
}
/**
* draw connect background line
*/
protected void drawConnectLine(Canvas canvas, int index, StepBarBean bean) {
mainPaint.setColor(bean.getConnectLineColor());
if (index < centerPointList.size() - 1) {
canvas.drawLine(connectLineArray[index][0], connectLineArray[index][1], //
connectLineArray[index][2], connectLineArray[index][3], mainPaint);
}
}
/**
* draw outside icon ring
*/
protected void drawRing(Canvas canvas, Point point, StepBarBean bean) {
if (config.getShowState() == StepBarConfig.StepShowState.DYNAMIC) {
//draw dynamic outside ring
if (bean.getState() == StepBarConfig.StepSate.RUNNING && outsideIconRingRadius > iconRadius) {
if (config.getOutSideIconRingCallback() != null) {
config.getOutSideIconRingCallback().drawRing(config, canvas, point, outsideIconRingRadius, position);
} else if (ringAnimator != null) {
drawDefaultRingAnimatorEffect(canvas, point, bean);
}
}
} else {//static state
//draw static outside ring
if (bean.getState() == StepBarConfig.StepSate.RUNNING && outsideIconRingRadius > iconRadius) {
if (config.getOutSideIconRingCallback() != null) {
config.getOutSideIconRingCallback().drawRing(config, canvas, point, outsideIconRingRadius, position);
} else {
drawBackgroundRing(canvas, point, bean);
}
}
}
}
/**
* draw default outside icon ring dynamic effect
*/
protected void drawDefaultRingAnimatorEffect(Canvas canvas, Point point, StepBarBean bean) {
drawBackgroundRing(canvas, point, bean);
drawForegroundRing(canvas, bean);
}
/**
* draw ring with background color
*/
private void drawBackgroundRing(Canvas canvas, Point point, StepBarBean bean) {
runPaint.setStrokeWidth(config.getOutsideIconRingWidth());
runPaint.setStyle(Paint.Style.STROKE);
runPaint.setColor(bean.getOutsideIconRingBackgroundColor());
canvas.drawCircle(point.x, point.y, outsideIconRingRadius, runPaint);
}
/**
* draw ring with foreground color
*/
private void drawForegroundRing(Canvas canvas, StepBarBean bean) {
ringAnimator.mPath.reset();
ringAnimator.mPath.lineTo(0, 0);
float stop = ringAnimator.pathLength * ringAnimator.animatorValue;
float start = (float) (stop - ((0.5 - Math.abs(ringAnimator.animatorValue - 0.5)) * ringAnimator.pathLength));
ringAnimator.pathMeasure.getSegment(start, stop, ringAnimator.mPath, true);
runPaint.setStrokeWidth(config.getOutsideIconRingWidth());
runPaint.setStyle(Paint.Style.STROKE);
runPaint.setColor(bean.getOutsideIconRingForegroundColor());
canvas.drawPath(ringAnimator.mPath, runPaint);
}
/**
* select right circle radius
* the length of a connecting line is at least a outside circle radius
*/
protected void selectRightRadius(int width, int height, int beanSize) {
if (config.getIconCircleRadius() > 0) {
iconRadius = config.getIconCircleRadius();
adjustRingWidth(iconRadius);
outsideIconRingRadius = iconRadius + config.getOutsideIconRingWidth();
} else {
// automatically resized
outsideIconRingRadius = (orientation == 0 ? width : height) / ((beanSize * 3.0f + 1.0f));
adjustRingWidth(outsideIconRingRadius);
iconRadius = outsideIconRingRadius - config.getOutsideIconRingWidth();
}
middleMargin = outsideIconRingRadius / 2.0f;
if (orientation == 0) {//horizontal
paddingTop = paddingBottom = (height - outsideIconRingRadius * 2 - measureFontSize()[1] - middleMargin) / 2.0f;
connectLineLength = paddingLeft = paddingRight = outsideIconRingRadius;
availableTextWidth = 3 * outsideIconRingRadius;
} else {//vertical
connectLineLength = paddingTop = paddingBottom = outsideIconRingRadius;
paddingLeft = paddingRight = outsideIconRingRadius / 2.0f;
availableTextWidth = width - paddingLeft - paddingRight - getPaddingLeft() - //
getPaddingRight() - middleMargin - outsideIconRingRadius * 2;
}
}
/**
* adjust ring width size automatically
*/
private void adjustRingWidth(float size) {
if (config.getOutsideIconRingWidth() < 0) {
config.setOutsideIconRingWidth(size * 0.08f);
}
}
/**
* adjust text font size,avoid the overlay of the text
*/
protected void adjustFontSize() {
adjustFontSize(getMaxCountText());
}
protected void adjustFontSize(String maxCountText) {
Log.e(TAG, "text font size adjust start :" + textSize + "==max count text :" + maxCountText);
float maxTextCountSize = measureFontSize(maxCountText)[orientation];
while (maxTextCountSize > 2.8 * outsideIconRingRadius) {
textSize -= 0.2f;
config.setTextSize(textSize);
setPaintTextSize();
maxTextCountSize = measureFontSize(maxCountText)[orientation];
}
Log.e(TAG, "text font size adjust complete :" + textSize);
}
@NonNull
protected String getMaxCountText() {
String maxCountText = "";
if (config != null && config.getBeanList() != null) {
// select max count of text
for (StepBarBean bean : config.getBeanList()) {
String running_text = bean.getRunningText();
String waiting_text = bean.getWaitingText();
String completed_text = bean.getCompletedText();
String failed_text = bean.getFailedText();
maxCountText = running_text.length() > waiting_text.length() ? running_text : waiting_text;
maxCountText = maxCountText.length() > completed_text.length() ? maxCountText : completed_text;
maxCountText = maxCountText.length() > failed_text.length() ? maxCountText : failed_text;
}
}
return maxCountText;
}
public void addConfig(StepBarConfig config) {
this.config = config;
init();
requestLayout();
}
public interface SlideCallback {
/**
* slide view
*/
void slide(int iconCenterX, int iconCenterY, float radius);
}
private SlideCallback slideCallback;
public void addSlideCallback(SlideCallback slideCallback) {
this.slideCallback = slideCallback;
}
public StepBarViewIndicator(Context context, int orientation) {
super(context);
this.orientation = orientation <= 0 ? 0 : 1;
init();
}
public StepBarViewIndicator(Context context, AttributeSet attrs, int orientation) {
super(context, attrs);
this.orientation = orientation <= 0 ? 0 : 1;
init();
}
public StepBarViewIndicator(Context context, AttributeSet attrs, int defStyleAttr, int orientation) {
super(context, attrs, defStyleAttr);
this.orientation = orientation <= 0 ? 0 : 1;
init();
}
@Override
public boolean isStatic() {
return config != null && config.getShowState() == StepBarConfig.StepShowState.STATIC;
}
@Override
public void drawStepBar(Canvas canvas) {
if (!isStatic()) {
if (config.getStepCallback() != null) {
if (config.getStepCallback().step(config, position)) {
updatePosition();
updateCurrentData();
stopRingAnimator();
startRingAnimator();
slideView();
} else {
//the current position icon state is no longer the running state,
//set static display,not refresh all the time
if (config.getBeanList().get(position).getState() != StepBarConfig.StepSate.RUNNING) {
config.setShowState(StepBarConfig.StepShowState.STATIC);
updateCurrentData();
slideView();
}
}
}
startDraw(canvas);
} else {
stopRingAnimator();
startDraw(canvas);
}
}
private void slideView() {
if (slideCallback != null) {
Point point = centerPointList.get(position);
slideCallback.slide(point.x, point.y, outsideIconRingRadius);
}
}
private void updatePosition() {
config.getBeanList().get(position).setState(StepBarConfig.StepSate.COMPLETED);
if (position == config.getBeanList().size() - 1) {//completed
config.setShowState(StepBarConfig.StepShowState.STATIC);
stopRingAnimator();
} else {
//open the next step
position += 1;
config.getBeanList().get(position).setState(StepBarConfig.StepSate.RUNNING);
}
}
protected void updateCurrentData() {
clearReference();
for (int index = 0, count = config.getBeanList().size(); index < count; index++) {
Point point = centerPointList.get(index);
adjustConnectLineLength(index, count, point);
updateTextRectAndDrawableData(index, point, config.getBeanList().get(index));
}
}
private void clearReference() {
if (textDrawableArray[0] != null) {
for (int index = 0; index > textDrawableArray.length; index++) {
textDrawableArray[index].setCallback(null);
iconDrawableArray[index].setCallback(null);
textRectArray[index] = null;
iconRectArray[index] = null;
connectLineArray[index] = null;
}
textView.destroyDrawingCache();
relativeLayout.destroyDrawingCache();
if (linearLayout != null) {
linearLayout.destroyDrawingCache();
}
textView = null;
relativeLayout = null;
linearLayout = null;
}
}
/**
* update connect line ,adjust the outside icon ring position
*/
private void adjustConnectLineLength(int index, int count, Point point) {
if (index < count - 1) {
float startX, startY, endX, endY;
if (orientation == 0) {//horizontal
if (config.getBeanList().get(index).getState() == StepBarConfig.StepSate.RUNNING) {
startX = point.x + outsideIconRingRadius;
} else {
startX = point.x + iconRadius;
}
if (config.getBeanList().get(index + 1).getState() == StepBarConfig.StepSate.RUNNING) {
endX = point.x + outsideIconRingRadius + connectLineLength;
} else {
endX = point.x + iconRadius + 2 * config.getOutsideIconRingWidth() + connectLineLength;
}
startY = endY = point.y;
} else {//vertical
if (config.getBeanList().get(index).getState() == StepBarConfig.StepSate.RUNNING) {
startY = point.y + outsideIconRingRadius;
} else {
startY = point.y + iconRadius;
}
if (config.getBeanList().get(index + 1).getState() == StepBarConfig.StepSate.RUNNING) {
endY = point.y + outsideIconRingRadius + connectLineLength;
} else {
endY = point.y + iconRadius + 2 * config.getOutsideIconRingWidth() + connectLineLength;
}
startX = endX = point.x;
}
connectLineArray[index][0] = startX;
connectLineArray[index][1] = startY;
connectLineArray[index][2] = endX;
connectLineArray[index][3] = endY;
}
}
private void updateTextRectAndDrawableData(int index, Point point, StepBarBean bean) {
Drawable icon;
String text;
int textColor;
switch (bean.getState()) {
case RUNNING:
icon = bean.getRunningIcon();
text = bean.getRunningText();
textColor = bean.getRunningTextColor();
break;
case WAITING:
icon = bean.getWaitingIcon();
text = bean.getWaitingText();
textColor = bean.getWaitingTextColor();
break;
case COMPLETED:
icon = bean.getCompletedIcon();
text = bean.getCompletedText();
textColor = bean.getCompletedTextColor();
break;
case FAILED:
icon = bean.getFailedIcon();
text = bean.getFailedText();
textColor = bean.getFailedTextColor();
break;
default:
icon = bean.getWaitingIcon();
text = "";
textColor = bean.getWaitingTextColor();
break;
}
iconDrawableArray[index] = icon;
initTextContainer();
float[] textSizes = measureFontSize(text);
float textWidth = textSizes[0];
float textHeight = textSizes[1];
Rect rect;
if (orientation == 0) {//horizontal
if (config.getTextLocation() == StepBarConfig.StepTextLocation.TOP) {
rect = new Rect((int) (point.x - textWidth / 2), (int) paddingTop,//
(int) (point.x + textWidth / 2), (int) (paddingTop+textHeight));
} else {
rect = new Rect((int) (point.x - textWidth / 2), (int) (point.y + outsideIconRingRadius + middleMargin),//
(int) (point.x + textWidth / 2), (int) (point.y + outsideIconRingRadius + textHeight + middleMargin));
}
} else {//vertical
if(config.getTextLocation()== StepBarConfig.StepTextLocation.LEFT){
rect = new Rect((int)paddingLeft,(int) (point.y - outsideIconRingRadius - outsideIconRingRadius / 3.0f),//
(int) (paddingLeft+availableTextWidth),//
(int) (point.y + outsideIconRingRadius + outsideIconRingRadius / 3.0f));
}else {
rect = new Rect(
(int) (point.x + outsideIconRingRadius + middleMargin), //
(int) (point.y - outsideIconRingRadius - outsideIconRingRadius / 3.0f),//
(int) (getMeasuredWidth() - getPaddingRight() - paddingRight),//
(int) (point.y + outsideIconRingRadius + outsideIconRingRadius / 3.0f));
}
}
if (config.isShowTextBold()) {
if (bean.getState() == StepBarConfig.StepSate.RUNNING) {
textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
} else {
textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}
} else {
textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}
textView.setText(text);
textView.setTextColor(textColor);
relativeLayout.addView(textView);
if (linearLayout != null) {
linearLayout.addView(relativeLayout);
}
Drawable drawable = convertViewToDrawable(orientation == 1 ? linearLayout : relativeLayout);
textDrawableArray[index] = drawable;
textRectArray[index] = rect;
drawable.setCallback(null);
}
/**
* textView convert drawable
*/
private Drawable convertViewToDrawable(View view) {
view.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), //
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
return new BitmapDrawable(null, view.getDrawingCache());
}
private LinearLayout linearLayout = null;
private RelativeLayout relativeLayout;
private TextView textView;
protected void initTextContainer() {
relativeLayout = new RelativeLayout(getContext());
textView = new TextView(getContext());
if (orientation == 0) {
relativeLayout.setGravity(Gravity.CENTER);
} else {
relativeLayout.setGravity(Gravity.START | Gravity.CENTER);
}
if (orientation == 0) {
textView.setGravity(Gravity.CENTER);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams((int) availableTextWidth, RelativeLayout.LayoutParams.WRAP_CONTENT));
} else if (orientation == 1) {
textView.setGravity(Gravity.START | Gravity.CENTER);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(
(int) (availableTextWidth),//
(int) (3 * outsideIconRingRadius + 2 * (outsideIconRingRadius / 3.0f))));
linearLayout = new LinearLayout(getContext());
linearLayout.setGravity(Gravity.START | Gravity.CENTER);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
textView.setSingleLine(false);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
}
|
/**
*
*/
package com.rd.monitoring.subapp;
import javax.inject.Inject;
import com.rd.monitoring.ui.IFactoriaElementosUI;
import com.vaadin.ui.Component;
import com.vaadin.ui.VerticalLayout;
/**
* @author David Caviedes
*
*/
public class MonitoringMainSubappViewImpl implements MonitoringMainSubappView {
private static final long serialVersionUID = 1L;
private VerticalLayout layout;
private Listener listener;
private IFactoriaElementosUI factoriaElementosUI;
@Inject
public MonitoringMainSubappViewImpl(IFactoriaElementosUI factoriaElementosUI) {
this.factoriaElementosUI = factoriaElementosUI;
this.layout = this.factoriaElementosUI.inicializarLayoutPrincipal(this);
}
/* (non-Javadoc)
* @see info.magnolia.ui.api.view.View#asVaadinComponent()
*/
@Override
public Component asVaadinComponent() {
return this.layout;
}
/* (non-Javadoc)
* @see com.rd.monitoring.subapp.MonitoringMainSubappView#setListener(com.rd.monitoring.subapp.MonitoringMainSubappView.Listener)
*/
@Override
public void setListener(Listener listener) {
this.listener = listener;
}
/* (non-Javadoc)
* @see com.rd.monitoring.subapp.MonitoringMainSubappView#getListener()
*/
@Override
public Listener getListener() {
return this.listener;
}
@Override
public IFactoriaElementosUI getFactoriaElementosUI() {
return this.factoriaElementosUI;
}
}
|
package com.stk123.service.core;
import com.stk123.entity.StkKeywordEntity;
import com.stk123.entity.StkKeywordLinkEntity;
import com.stk123.repository.BaseRepository;
import com.stk123.repository.StkKeywordLinkRepository;
import com.stk123.repository.StkKeywordRepository;
import com.stk123.service.StkConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class KeywordService {
@Autowired
private StkKeywordRepository stkKeywordRepository;
@Autowired
private StkKeywordLinkRepository stkKeywordLinkRepository;
private static String sql_getKeywordByLinkType = "select distinct b.name name from stk_keyword_link a, stk_keyword b " +
"where a.link_type=:1 and a.keyword_id=b.id";
@Transactional
public List<String> getKeywordByLinkType(int linkType) {
return BaseRepository.getInstance().list2String(sql_getKeywordByLinkType, linkType);
}
private static String sql_getKeywordByStatus = "select name from stk_keyword where status=:1";
@Transactional
public List<String> getKeywordByStatus(int status) {
return BaseRepository.getInstance().list2String(sql_getKeywordByStatus, status);
}
public int addKeywordAndLink(String keyword, String code, Integer codeType, Integer linkType){
StkKeywordEntity stkKeywordEntity = stkKeywordRepository.findByName(keyword);
if(stkKeywordEntity != null){
if(stkKeywordEntity.getStatus() == StkConstant.KEYWORD_STATUS__1){
return -1;
}
}else{
stkKeywordEntity = new StkKeywordEntity();
stkKeywordEntity.setName(keyword);
stkKeywordEntity.setStatus(StkConstant.KEYWORD_STATUS_1);
stkKeywordEntity.setInsertTime(new Date());
stkKeywordRepository.save(stkKeywordEntity);
}
StkKeywordLinkEntity stkKeywordLinkEntity = stkKeywordLinkRepository.findByKeywordIdAndCodeAndCodeTypeAndLinkType(stkKeywordEntity.getId(), code, codeType, linkType);
if(stkKeywordLinkEntity == null){
stkKeywordLinkEntity = new StkKeywordLinkEntity();
stkKeywordLinkEntity.setKeywordId(stkKeywordEntity.getId());
stkKeywordLinkEntity.setCode(code);
stkKeywordLinkEntity.setCodeType(codeType);
stkKeywordLinkEntity.setLinkType(linkType);
stkKeywordLinkEntity.setInsertTime(new Date());
stkKeywordLinkRepository.save(stkKeywordLinkEntity);
return 1;
}
return 0;
}
}
|
package com.programapprentice.app;
import java.util.*;
/**
* User: program-apprentice
* Date: 10/11/15
* Time: 10:31 PM
*/
public class WordDictionary {
private final int R = 26;
class TrieNode {
public char c;
public boolean endOfWord = false;
public TrieNode[] next = null;
public TrieNode(char c) {
next = new TrieNode[R];
endOfWord = false;
this.c = c;
}
}
private TrieNode root;
public WordDictionary() {
root = new TrieNode(' ');
}
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode node = this.root;
TrieNode child = null;
for(int i = 0; i < word.length(); i++) {
char cur = word.charAt(i);
child = node.next[cur-'a'];
if(child == null) {
child = new TrieNode(cur);
node.next[cur-'a'] = child;
}
if(i == word.length()-1) {
child.endOfWord = true;
}
node = child;
}
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
Queue<TrieNode> queue = new LinkedList<TrieNode>();
Queue<Integer> depthQueue = new LinkedList<Integer>();
queue.add(root);
depthQueue.add(0);
while(!queue.isEmpty()) {
int depth = depthQueue.remove();
if(depth == word.length()) {
break;
}
TrieNode node = queue.remove();
char cur = word.charAt(depth);
if(depth == word.length()-1) {
if(cur == '.') {
for(TrieNode child : node.next) {
if(child != null && child.endOfWord) {
return true;
}
}
// return false; // this one should be removed.
} else {
if(node.next[cur-'a'] != null && node.next[cur-'a'].endOfWord) {
return true;
}
}
} else {
if(cur == '.') {
for(TrieNode child : node.next) {
if(child != null) {
queue.add(child);
depthQueue.add(depth + 1);
}
}
} else {
if(node.next[cur-'a'] != null) { // wrong: if(node.c == cur && node.next[cur-'a'] != null) {
queue.add(node.next[cur - 'a']);
depthQueue.add(depth + 1);
}
}
}
}
return false;
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern"); |
package com.experian.brand.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
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 com.experian.base.pojo.PagePojo;
import com.experian.brand.entity.BrandUrl;
import com.experian.brand.service.BrandUrlService;
import com.experian.main.pojo.Result;
@Controller
@RequestMapping("/brand")
public class BrandUrlController {
@Autowired
private BrandUrlService brandUrlService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(HttpServletRequest request) {
request.setAttribute("list", brandUrlService.findAll());
return "brand/list";
}
@RequestMapping(value = "/listByPage", method = RequestMethod.GET)
@ResponseBody
public PagePojo<BrandUrl> listByPage(PagePojo<BrandUrl> page){
return brandUrlService.findByPage(page);
}
@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String edit(HttpServletRequest request,Integer id) {
if(id!=null){
request.setAttribute("pojo",brandUrlService.get(id));
}
return "brand/edit";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public Result save(BrandUrl brandUrl) {
Result rs=new Result();
if(brandUrl.getId()!=null){
brandUrlService.update(brandUrl);
}else{
brandUrlService.save(brandUrl);
}
rs.setCode(Result.SUCCESS);
return rs;
}
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public Result delete(Integer id) {
Result rs=new Result();
brandUrlService.delete(id);
rs.setCode(Result.SUCCESS);
return rs;
}
}
|
package trees;
import java.util.LinkedList;
import java.util.Queue;
class Manode {
int data;
Manode left, right;
public Manode(int value) {
data = value;
left = right = null;
}
}
public class MxNode {
Manode root;
// recursive method
int maxRec(Manode node) {
int max = Integer.MIN_VALUE;
if (node != null) {
int left = maxRec(node.left);
int right = maxRec(node.right);
if (left > right)
max = left;
else
max = right;
}
if (node.data > max)
max = node.data;
return max;
}
int maxIte(Manode node) {
int max = Integer.MIN_VALUE;
if (node == null)
return max;
Queue<Manode> queue = new LinkedList<>();
queue.offer(node);
while (!queue.isEmpty()) {
Manode temp = queue.poll();
if (temp.data > max) {
max = temp.data;
}
if (temp != null) {
if (temp.left != null)
queue.add(temp.left);
if (temp.right != null)
queue.add(temp.right);
}
}
return max;
}
}
|
package com.cninnovatel.ev.db;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import com.cninnovatel.ev.db.RestCallRow_;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "REST_CALL_ROW_".
*/
public class RestCallRow_Dao extends AbstractDao<RestCallRow_, Long> {
public static final String TABLENAME = "REST_CALL_ROW_";
/**
* Properties of entity RestCallRow_.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property PeerSipNum = new Property(1, String.class, "peerSipNum", false, "PEER_SIP_NUM");
public final static Property IsOutgoing = new Property(2, Boolean.class, "isOutgoing", false, "IS_OUTGOING");
public final static Property IsVideoCall = new Property(3, Boolean.class, "isVideoCall", false, "IS_VIDEO_CALL");
public final static Property StartTime = new Property(4, Long.class, "startTime", false, "START_TIME");
public final static Property Duration = new Property(5, Long.class, "duration", false, "DURATION");
};
public RestCallRow_Dao(DaoConfig config) {
super(config);
}
public RestCallRow_Dao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"REST_CALL_ROW_\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"PEER_SIP_NUM\" TEXT," + // 1: peerSipNum
"\"IS_OUTGOING\" INTEGER," + // 2: isOutgoing
"\"IS_VIDEO_CALL\" INTEGER," + // 3: isVideoCall
"\"START_TIME\" INTEGER," + // 4: startTime
"\"DURATION\" INTEGER);"); // 5: duration
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"REST_CALL_ROW_\"";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, RestCallRow_ entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String peerSipNum = entity.getPeerSipNum();
if (peerSipNum != null) {
stmt.bindString(2, peerSipNum);
}
Boolean isOutgoing = entity.getIsOutgoing();
if (isOutgoing != null) {
stmt.bindLong(3, isOutgoing ? 1L: 0L);
}
Boolean isVideoCall = entity.getIsVideoCall();
if (isVideoCall != null) {
stmt.bindLong(4, isVideoCall ? 1L: 0L);
}
Long startTime = entity.getStartTime();
if (startTime != null) {
stmt.bindLong(5, startTime);
}
Long duration = entity.getDuration();
if (duration != null) {
stmt.bindLong(6, duration);
}
}
/** @inheritdoc */
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
/** @inheritdoc */
@Override
public RestCallRow_ readEntity(Cursor cursor, int offset) {
RestCallRow_ entity = new RestCallRow_( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // peerSipNum
cursor.isNull(offset + 2) ? null : cursor.getShort(offset + 2) != 0, // isOutgoing
cursor.isNull(offset + 3) ? null : cursor.getShort(offset + 3) != 0, // isVideoCall
cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4), // startTime
cursor.isNull(offset + 5) ? null : cursor.getLong(offset + 5) // duration
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, RestCallRow_ entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setPeerSipNum(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setIsOutgoing(cursor.isNull(offset + 2) ? null : cursor.getShort(offset + 2) != 0);
entity.setIsVideoCall(cursor.isNull(offset + 3) ? null : cursor.getShort(offset + 3) != 0);
entity.setStartTime(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
entity.setDuration(cursor.isNull(offset + 5) ? null : cursor.getLong(offset + 5));
}
/** @inheritdoc */
@Override
protected Long updateKeyAfterInsert(RestCallRow_ entity, long rowId) {
entity.setId(rowId);
return rowId;
}
/** @inheritdoc */
@Override
public Long getKey(RestCallRow_ entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
|
package io.nuls.consensus.network.message.v1.thread;
import io.nuls.base.basic.AddressTool;
import io.nuls.base.signture.SignatureUtil;
import io.nuls.consensus.network.constant.NetworkCmdConstant;
import io.nuls.consensus.network.service.ConsensusNetService;
import io.nuls.consensus.network.service.NetworkService;
import io.nuls.consensus.v1.entity.BasicRunnable;
import io.nuls.core.core.ioc.SpringLiteContext;
import io.nuls.core.exception.NulsException;
import io.nuls.core.model.StringUtils;
import io.nuls.consensus.model.bo.Chain;
import io.nuls.consensus.network.model.ConsensusKeys;
import io.nuls.consensus.network.model.ConsensusNet;
import io.nuls.consensus.network.model.message.ConsensusIdentitiesMsg;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Niels
*/
public class IdentityProcessor extends BasicRunnable {
private ConsensusNetService consensusNetService;
private NetworkService networkService;
public IdentityProcessor(Chain chain) {
super(chain);
this.running = true;
}
@Override
public void run() {
while (this.running) {
try {
process();
} catch (Throwable e) {
log.error(e);
}
}
}
private void process() throws Exception {
if (null == consensusNetService) {
consensusNetService = SpringLiteContext.getBean(ConsensusNetService.class);
}
if (null == networkService) {
networkService = SpringLiteContext.getBean(NetworkService.class);
}
ConsensusIdentitiesMsg message = chain.getConsensusCache().getIdentityMessageQueue().take();
String nodeId = message.getNodeId();
int chainId = chain.getChainId();
String msgHash = message.getMsgHash().toHex();
// //chain.getLogger().debug("Identity message,msgHash={} recv from node={}", msgHash, nodeId);
try {
//校验签名
if (!SignatureUtil.validateSignture(message.getConsensusIdentitiesSub().serialize(), message.getSign())) {
chain.getLogger().error("Identity message,msgHash={} recv from node={} validateSignture false", msgHash, nodeId);
return;
}
} catch (NulsException | IOException e) {
chain.getLogger().error(e);
return;
}
/*
接受身份信息,判断是否有自己的包,有解析,1.解析后判断是否在自己连接列表内,存在则跃迁,不存在进行第三步,同时 广播转发/ 普通节点直接转发
*/
ConsensusKeys consensusKeys = consensusNetService.getSelfConsensusKeys(chainId);
if (null == consensusKeys) {
//只需要转发消息
// //chain.getLogger().debug("=======不是共识节点,只转发{}消息", nodeId);
} else {
//如果为当前节点签名消息则直接返回
String signAddress = AddressTool.getStringAddressByBytes(AddressTool.getAddress(message.getSign().getPublicKey(), chainId));
if (signAddress.equals(consensusKeys.getAddress())) {
return;
}
//如果无法解密直接返回
ConsensusNet consensusNet = message.getConsensusIdentitiesSub().getDecryptConsensusNet(chain, consensusKeys.getAddress(), consensusKeys.getPubKey());
if (null == consensusNet) {
// chain.getLogger().error("=======无法解密消息,返回!", nodeId);
return;
}
if (StringUtils.isBlank(consensusNet.getAddress())) {
consensusNet.setAddress(AddressTool.getStringAddressByBytes(AddressTool.getAddress(consensusNet.getPubKey(), chainId)));
}
//解出的包,需要判断对方是否共识节点
ConsensusNet dbConsensusNet = consensusNetService.getConsensusNode(chainId, consensusNet.getAddress());
if (null == dbConsensusNet) {
//这边需要注意,此时如果共识节点列表里面还没有该节点,可能就会误判,所以必须保障 在收到消息时候,共识列表里已经存在该消息。
chain.getLogger().error("nodeId = {} not in consensus Group", consensusNet.getNodeId());
return;
}
//可能没公钥,更新下公钥信息
String consensusNetNodeId = consensusNet.getNodeId();
//每次从网络模块查询,是为了避免某节点断开然后重连导致本地连接缓存信息失效
boolean isConnect = networkService.connectPeer(chainId, consensusNetNodeId);
if (!isConnect) {
chain.getLogger().warn("connect fail .nodeId = {}", consensusNet.getNodeId());
} else {
// //chain.getLogger().debug("connect {} success", consensusNetNodeId);
dbConsensusNet.setNodeId(consensusNetNodeId);
dbConsensusNet.setPubKey(consensusNet.getPubKey());
dbConsensusNet.setHadConnect(true);
List<String> ips = new ArrayList<>();
ips.add(consensusNetNodeId.split(":")[0]);
networkService.addIps(chainId, NetworkCmdConstant.NW_GROUP_FLAG, ips);
}
//分享所有已连接共识信息给对端
networkService.sendShareMessage(chainId, consensusNetNodeId, consensusNet.getPubKey());
//如果为新节点消息则需要,如果为其他链接节点的回执信息则不需要
if (message.getConsensusIdentitiesSub().isBroadcast()) {
//同时分享新增的连接信息给其他已连接节点
networkService.sendShareMessageExNode(chainId, consensusNetNodeId, consensusNet);
}
//如果为新节点消息则需要将本节点的身份信息回执给对方(用于对方节点将本节点设置为共识网络节点)
if (message.getConsensusIdentitiesSub().isBroadcast()) {
chain.getLogger().info("begin broadCastIdentityMsg to={} success", nodeId);
networkService.sendIdentityMessage(chainId, consensusNet.getNodeId(), consensusNet.getPubKey());
}
}
//如果为新节点消息则需要转发,如果为其他链接节点的回执信息则不需要广播
if (message.getConsensusIdentitiesSub().isBroadcast()) {
// chain.getLogger().info("begin broadCastIdentityMsg exclude={} success", nodeId);
networkService.broadCastIdentityMsg(chain, NetworkCmdConstant.POC_IDENTITY_MESSAGE, message.getMsgStr(), nodeId);
}
}
}
|
package se.rtz.bindings.view.enable_disable;
import se.rtz.bindings.model.OneWayConverterProperty;
import se.rtz.bindings.model.Property;
import se.rtz.bindings.model.SModel;
import se.rtz.bindings.model.SimpleProperty;
public class TestEnableDisableModel extends SModel {
private Property<String> textValue = new SimpleProperty<>("Hello");
private Property<Boolean> enabledDisabledModel = new SimpleProperty<Boolean>(Boolean.TRUE);
public Property<String> getTextValue() {
return textValue;
}
public Property<Boolean> getEnabledDisabledModel() {
return enabledDisabledModel;
}
public Property<String> getEnabledTextModel() {
return new OneWayConverterProperty<Boolean, String>(enabledDisabledModel) {
@Override
public String convert(Boolean value) {
if (value == null) {
return "null";
}
return value ? "on" : "off";
}
};
}
}
|
public class UltimateTeam {
public ArrayList<UltimatePlayer> players;
public ArrayList<Coach> coaches;
public UltimateTeam(ArrayList<UltimatePlayer> players, ArrayList<Coach> coaches) {
this.players = players;
this.coaches = coaches;
}
public String getCutters() {
String str = "";
for (UltimatePlayer b: players) {
if (b.getPosition().equals("cutter")) {
str += b.toString();
str += "\n";
}
}
return str;
}
public String getHandlers() {
String str = "";
for (UltimatePlayer b: players) {
if (b.getPosition().equals("handler")) {
str += b.toString();
str += "\n";
}
}
return str;
}
public String toString() {
String str = "COACHES\n";
for (Coach a: this.coaches) {
str += a.toString();
str += "\n";
}
str += "\nPLAYERS\n";
for (UltimatePlayer b: this.players) {
str += b.toString();
str += "\n";
}
return str;
}
}
|
package factorypattern.noodle.abstractfactory.ingredient;
/**
* The beef soup.
*
* @author Thomson Tang
*/
public class BeefSoup extends Soup {
}
|
package com.seven.jdbc.tables;
import java.sql.ResultSet;
import java.sql.SQLException;
public class States {
public static void displayData(ResultSet rs) throws SQLException {
while (rs.next()) {
String str = rs.getString("stateId") + ": " + rs.getString("stateName");
System.out.println(str);
}
System.out.println();
}
}
|
/*
* Lesson 14 Coding Activity 2
* Write a program to input two integers and print
* "Both are positive or zero." to the screen, if both are positive or zero.
* Print "One or both are negative." otherwise.
*/
import java.util.Scanner;
class Lesson_14_Activity_Two {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println(
(input.nextInt() > -1) && (input.nextInt() > -1) ? "Both are positive or zero."
: "One or both are negative."
);
input.close();
}
} |
package com.temp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) throws IOException, ParseException {
Scanner s = new Scanner(System.in);
Date date = null;
File file = new File("/home/valuelabs/workspace/Bs/src/com/temp/abc.txt");
FileInputStream fis = new FileInputStream(file);
FileToObject fto = new FileToObject();
Map<Emp,Integer> map =fto.filetoobj(file);
System.out.println("Enter your choice:");
int choice=0 ;//= s.nextInt();
switch(choice){
case 1:
//to find number of Emp's on entered date
break;
case 2:
//to find Emp Time
break;
}
//System.out.println("Map object is "+map);
System.out.println("Enter Date : ");
String date1 = s.nextLine();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = formatter.parse(date1);
//System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
CountingEmps ce = new CountingEmps();
System.out.println("Number of Emp's on "+ formatter.format(date) +" are");
ce.EmpsCount(map);
}
}
|
package io.pivotal.gcp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import(org.springframework.cloud.stream.app.time.source.TimeSourceConfiguration.class)
public class TimeSourceApplication {
public static void main(String[] args) {
SpringApplication.run(TimeSourceApplication.class, args);
}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DAO.HistoryDAO;
import model.DAO.UserDAO;
import model.DAO.UserStatusDAO;
import model.object.Book;
import model.object.BorrowedBook;
import model.object.User;
import model.object.UserStatus;
import model.utils.Convert;
@WebServlet("/getUserInfo")
public class GetUserInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// set up response
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter printWriter = response.getWriter();
// get user
Integer libraryCardId = Convert.convertStringToInt(request.getParameter("libraryCardId"));
String activity = request.getParameter("activity");
if (libraryCardId != null) {
User reader = UserDAO.getUserByLibraryCardId(libraryCardId);
if (reader != null) {
// get
UserStatus readerStatus = UserStatusDAO.getStatusById(reader.getUserStatusId());
List<BorrowedBook> borrowedBooks = HistoryDAO.getBorrowedBookByLibraryCardId(libraryCardId);
LinkedList<Book> preparedBooks = new LinkedList<Book>();
// save in session
HttpSession session = request.getSession(true);
session.setAttribute("reader", reader);
session.setAttribute("readerStatus", readerStatus);
session.setAttribute("borrowedBooks", borrowedBooks);
session.setAttribute("preparedBooks", preparedBooks);
// test activity
switch (activity) {
case "borrow":
request.getRequestDispatcher("default?page=borrowBook").forward(request, response);
return;
case "pay":
request.getRequestDispatcher("default?page=payBook").forward(request, response);
return;
}
}
}
printWriter.println("error");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
package com.example.demo.DAO;
import com.example.demo.DO.TeacherDO;
import java.util.List;
public interface TeacherMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table teacher
*
* @mbg.generated
*/
int deleteByPrimaryKey(String tno);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table teacher
*
* @mbg.generated
*/
int insert(TeacherDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table teacher
*
* @mbg.generated
*/
TeacherDO selectByPrimaryKey(String tno);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table teacher
*
* @mbg.generated
*/
List<TeacherDO> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table teacher
*
* @mbg.generated
*/
int updateByPrimaryKey(TeacherDO record);
} |
//package alien4cloud.it.cloud;
//
//import static org.junit.Assert.*;
//
//import java.io.IOException;
//import java.util.List;
//import java.util.Map;
//
//import org.apache.commons.lang3.StringUtils;
//import org.apache.http.NameValuePair;
//import org.apache.http.message.BasicNameValuePair;
//
//import alien4cloud.dao.model.GetMultipleDataResult;
//import alien4cloud.it.Context;
//import alien4cloud.it.Entry;
//import alien4cloud.it.plugin.ProviderConfig;
//import alien4cloud.model.application.EnvironmentType;
//import alien4cloud.model.cloud.Cloud;
//import alien4cloud.model.cloud.IaaSType;
//import alien4cloud.paas.exception.NotSupportedException;
//import alien4cloud.rest.cloud.CloudDTO;
//import alien4cloud.rest.model.RestResponse;
//import alien4cloud.rest.utils.JsonUtil;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
//
//import cucumber.api.java.en.And;
//import cucumber.api.java.en.Given;
//import cucumber.api.java.en.Then;
//import cucumber.api.java.en.When;
//
//public class CloudDefinitionsSteps {
//
// @Given("^I create a cloud with name \"([^\"]*)\" and plugin id \"([^\"]*)\" and bean name \"([^\"]*)\"$")
// public void I_create_a_cloud_with_name_and_plugin_id_and_bean_name(String cloudName, String pluginId, String pluginBeanName) throws Throwable {
// Cloud cloud = new Cloud();
// cloud.setIaaSType(IaaSType.OPENSTACK);
// cloud.setName(cloudName);
// cloud.setPaasPluginId(pluginId);
// cloud.setPaasPluginBean(pluginBeanName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().postJSon("/rest/clouds", JsonUtil.toString(cloud)));
// RestResponse<String> cloudIdResponse = JsonUtil.read(Context.getInstance().getRestResponse(), String.class);
// Context.getInstance().registerCloud(cloudIdResponse.getData(), cloudName);
// }
//
// @Given("^I enable the cloud \"([^\"]*)\"$")
// public void I_enable_the_cloud(String cloudName) throws IOException {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/" + cloudId + "/enable"));
// }
//
// @When("^I list clouds$")
// public void I_list_clouds() throws IOException {
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/search"));
// }
//
// @Then("^Response should contains (\\d+) cloud$")
// public void I_list_enabled_clouds(int exepectedCloudCount) throws IOException {
// RestResponse<GetMultipleDataResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), GetMultipleDataResult.class);
// assertEquals(exepectedCloudCount, response.getData().getTotalResults());
// }
//
// @Then("^Response should contains a cloud with name \"([^\"]*)\"$")
// public void Response_should_contains_a_cloud_with_name(String cloudName) throws IOException {
// RestResponse<GetMultipleDataResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), GetMultipleDataResult.class);
// boolean contains = false;
// for (Object cloudAsMap : response.getData().getData()) {
// Cloud cloud = JsonUtil.readObject(JsonUtil.toString(cloudAsMap), Cloud.class);
// if (cloudName.equals(cloud.getName())) {
// contains = true;
// }
// }
// assertTrue(contains);
// }
//
// @Then("^Response should contains a cloud with deploymentNamePattern \"([^\"]*)\"$")
// public void Response_should_contains_a_cloud_with_deploymentNamePattern(String deploymentNamePattern) throws IOException {
// RestResponse<GetMultipleDataResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), GetMultipleDataResult.class);
// boolean contains = false;
// for (Object cloudAsMap : response.getData().getData()) {
// Cloud cloud = JsonUtil.readObject(JsonUtil.toString(cloudAsMap), Cloud.class);
// if (deploymentNamePattern.equals(cloud.getDeploymentNamePattern())) {
// contains = true;
// }
// }
// assertTrue(contains);
// }
//
// @When("^I update cloud name from \"([^\"]*)\" to \"([^\"]*)\"$")
// public void I_update_cloud_name_from_to(String cloudName, String newCloudName) throws IOException {
// Cloud cloud = new Cloud();
// cloud.setName(newCloudName);
// updateCloud(cloudName, cloud);
// RestResponse<?> restResponse = JsonUtil.read(Context.getInstance().getRestResponse());
// if (restResponse.getError() == null && !cloudName.equals(newCloudName)) {
// Context.getInstance().unregisterCloud(cloudName);
// Context.getInstance().registerCloud(cloud.getId(), newCloudName);
// }
// }
//
// @When("^I update deployment name pattern of \"([^\"]*)\" to \"([^\"]*)\"$")
// public void I_update_deployment_name_pattern_of_to(String cloudName, String newDeploymentNamePattern) throws IOException {
// Cloud cloud = new Cloud();
// cloud.setDeploymentNamePattern(newDeploymentNamePattern);
// updateCloud(cloudName, cloud);
// RestResponse<?> restResponse = JsonUtil.read(Context.getInstance().getRestResponse());
// if (restResponse.getError() == null) {
// Context.getInstance().unregisterCloud(cloudName);
// Context.getInstance().registerCloud(cloud.getId(), cloudName);
// }
// }
//
// @When("^I update cloud named \"([^\"]*)\" iaas type to \"([^\"]*)\"$")
// public void I_update_cloud_named_iaas_type_to(String cloudName, String iaaSType) throws IOException {
// Cloud cloud = new Cloud();
// cloud.setIaaSType(IaaSType.valueOf(iaaSType));
// updateCloud(cloudName, cloud);
// }
//
// @Then("^Response should contains a cloud with name \"([^\"]*)\" and iass type \"([^\"]*)\"$")
// public void Response_should_contains_a_cloud_with_name_and_iass_type(String cloudName, String iaaSTypeStr) throws IOException {
// IaaSType iaaSType = IaaSType.valueOf(iaaSTypeStr);
// RestResponse<GetMultipleDataResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), GetMultipleDataResult.class);
// boolean contains = false;
// for (Object cloudAsMap : response.getData().getData()) {
// Cloud cloud = JsonUtil.readObject(JsonUtil.toString(cloudAsMap), Cloud.class);
// if (cloudName.equals(cloud.getName()) && iaaSType.equals(cloud.getIaaSType())) {
// contains = true;
// }
// }
// assertTrue(contains);
// }
//
// @Then("^Response should contains a cloud with name \"([^\"]*)\" and environment type \"([^\"]*)\"$")
// public void Response_should_contains_a_cloud_with_name_and_environment_type(String cloudName, String environmentTypeStr) throws IOException {
// EnvironmentType environmentType = EnvironmentType.valueOf(environmentTypeStr);
// RestResponse<GetMultipleDataResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), GetMultipleDataResult.class);
// boolean contains = false;
// for (Object cloudAsMap : response.getData().getData()) {
// Cloud cloud = JsonUtil.readObject(JsonUtil.toString(cloudAsMap), Cloud.class);
// if (cloudName.equals(cloud.getName()) && environmentType.equals(cloud.getEnvironmentType())) {
// contains = true;
// }
// }
// assertTrue(contains);
// }
//
// @When("^I update cloud named \"([^\"]*)\" environment type to \"([^\"]*)\"$")
// public void I_update_cloud_named_environment_type_to(String cloudName, String environmentType) throws IOException {
// Cloud cloud = new Cloud();
// cloud.setEnvironmentType(EnvironmentType.valueOf(environmentType));
// updateCloud(cloudName, cloud);
// }
//
// private void updateCloud(String cloudName, Cloud updatedCloud) throws JsonProcessingException, IOException {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// updatedCloud.setId(cloudId);
// Context.getInstance().registerRestResponse(
// Context.getRestClientInstance().putJSon("/rest/clouds", Context.getInstance().getJsonMapper().writeValueAsString(updatedCloud)));
// }
//
// @When("^I delete a cloud with name \"([^\"]*)\"$")
// public void I_delete_a_cloud_with_name(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().delete("/rest/clouds/" + cloudId));
// }
//
// @When("^I disable cloud \"([^\"]*)\"$")
// public void I_disable_cloud(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/" + cloudId + "/disable"));
// }
//
// @When("^I disable all clouds$")
// public void I_disable_all_clouds() throws Throwable {
// for (String cloudId : Context.getInstance().getOrchestratorIds()) {
// Context.getRestClientInstance().get("/rest/clouds/" + cloudId + "/disable");
// }
// }
//
// @When("^I enable \"([^\"]*)\"$")
// public void I_enable(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/" + cloudId + "/enable"));
// }
//
// @Then("^Response should contains a cloud with state enabled \"([^\"]*)\"$")
// public void Response_should_contains_a_cloud_with_state_enabled(String enabledStr) throws Throwable {
// Boolean enabled = Boolean.valueOf(enabledStr);
// RestResponse<GetMultipleDataResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), GetMultipleDataResult.class);
// boolean contains = false;
// for (Object cloudAsMap : response.getData().getData()) {
// Cloud cloud = JsonUtil.readObject(JsonUtil.toString(cloudAsMap), Cloud.class);
// if (enabled.equals(cloud.isEnabled())) {
// contains = true;
// }
// }
// assertTrue(contains);
// }
//
// @When("^I get configuration for cloud \"([^\"]*)\"$")
// public void I_get_configuration_for_cloud(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/" + cloudId + "/configuration"));
// }
//
// @When("^I update configuration for cloud \"([^\"]*)\"$")
// public void I_update_configuration_for_cloud(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
//
// ProviderConfig config = new ProviderConfig();
// config.setFirstArgument("firstArgument");
// config.setSecondArgument("secondArgument");
//
// Context.getInstance().registerRestResponse(
// Context.getRestClientInstance().putJSon("/rest/clouds/" + cloudId + "/configuration", JsonUtil.toString(config)));
// }
//
// @When("^I update configuration for cloud \"([^\"]*)\" with wrong configuration$")
// public void I_update_configuration_for_cloud_with_wrong_configuration(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance()
// .registerRestResponse(Context.getRestClientInstance().putJSon("/rest/clouds/" + cloudId + "/configuration", JsonUtil.toString("")));
// }
//
// @Then("^The cloud configuration should be null$")
// public void The_cloud_configuration_should_be_null() throws Throwable {
// RestResponse<ProviderConfig> response = JsonUtil.read(Context.getInstance().getRestResponse(), ProviderConfig.class);
// assertNull(response.getData());
// }
//
// @Then("^The cloud configuration should not be null$")
// public void The_cloud_configuration_should_not_be_null() throws Throwable {
// RestResponse<ProviderConfig> response = JsonUtil.read(Context.getInstance().getRestResponse(), ProviderConfig.class);
// assertNotNull(response.getData());
// }
//
// @When("^I get the cloud by name \"([^\"]*)\"$")
// public void I_get_the_cloud_by_name(String name) throws Throwable {
// NameValuePair nvp = new BasicNameValuePair("cloudName", name);
// String restResponse = Context.getRestClientInstance().getUrlEncoded("/rest/clouds/getByName", Lists.newArrayList(nvp));
// Context.getInstance().registerRestResponse(restResponse);
// RestResponse<Cloud> response = JsonUtil.read(Context.getInstance().getRestResponse(), Cloud.class);
// if (response != null && response.getData() != null) {
// String cloudId = response.getData().getId();
// if (cloudId != null) {
// Context.getInstance().registerCloud(cloudId, name);
// }
// }
// }
//
// @When("^I get the cloud \"([^\"]*)\"$")
// public void I_get_the_cloud_by_id(String name) throws Throwable {
// // get the cloud by its ID
// String cloudId = Context.getInstance().getCloudId(name);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/" + cloudId));
// }
//
// @Then("^I should receive a cloud with name \"([^\"]*)\"$")
// public void I_should_receive_a_cloud_with_name(String expectedName) throws Throwable {
// Cloud cloud = JsonUtil.read(Context.getInstance().getRestResponse(), Cloud.class).getData();
// assertNotNull(cloud);
// assertEquals(expectedName, cloud.getName());
// }
//
// @Then("^The Response should contains cloud with name \"([^\"]*)\" and iass type \"([^\"]*)\" and environment type \"([^\"]*)\"$")
// public void the_Response_should_contains_cloud_with_name_and_iass_type_and_environment_type(String expectedName, String expectedIasSType,
// String expectedEnvType) throws Throwable {
// // get cloud by id returns a CloudDTO whereas get cloud by name returns a Cloud object
// // This assert will be used only after a get by ID
// CloudDTO cloud = JsonUtil.read(Context.getInstance().getRestResponse(), CloudDTO.class).getData();
// assertNotNull(cloud);
// assertEquals(expectedName, cloud.getCloud().getName());
// assertEquals(IaaSType.valueOf(expectedIasSType.toUpperCase()), cloud.getCloud().getIaaSType());
// assertEquals(EnvironmentType.valueOf(expectedEnvType.toUpperCase()), cloud.getCloud().getEnvironmentType());
// }
//
// @When("^I get deployment properties for cloud \"([^\"]*)\"$")
// public void I_get_deployment_properties_for_cloud(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/clouds/" + cloudId + "/deploymentpropertydefinitions"));
// }
//
// @Then("^The RestResponse should contain the following properties and values$")
// public void The_RestResponse_should_contain_the_following_properties_and_values(List<Entry> properties) throws Throwable {
// Map<String, String> props = (Map<String, String>) JsonUtil.read(Context.getInstance().getRestResponse()).getData();
// assertNotNull(props);
// for (Entry expectedProperty : properties) {
// assertTrue(props.containsKey(expectedProperty.getName()));
// String propValue = props.get(props.get(expectedProperty.getName()));
// if (StringUtils.isBlank(expectedProperty.getValue())) {
// assertNull(propValue);
// } else {
// assertNotNull(propValue);
// assertEquals(expectedProperty.getValue(), propValue);
// }
// }
// }
//
// @When("^I clone the cloud with name \"([^\"]*)\"$")
// public void I_clone_the_cloud_with_name(String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Context.getInstance().registerRestResponse(Context.getRestClientInstance().postJSon("/rest/clouds/" + cloudId + "/clone", "{}"));
// }
//
// @And("^I create a cloud with name \"([^\"]*)\" from cloudify (\\d+) PaaS provider$")
// public void I_create_a_cloud_with_name_from_cloudify_PaaS_provider(String cloudName, int cloudifyVersion) throws Throwable {
// String pluginId;
// String beanName;
// switch (cloudifyVersion) {
// case 2:
// pluginId = "alien-cloudify-2-paas-provider:" + Context.VERSION;
// beanName = "cloudify-paas-provider";
// break;
// case 3:
// pluginId = "alien-cloudify-3-paas-provider:" + Context.VERSION;
// beanName = "cloudify-paas-provider";
// break;
// default:
// throw new IllegalArgumentException("Cloudify version not supported " + cloudifyVersion);
// }
// I_create_a_cloud_with_name_and_plugin_id_and_bean_name(cloudName, pluginId, beanName);
// }
//
// @And("^I update cloudify (\\d+) manager's url to \"([^\"]*)\" for cloud with name \"([^\"]*)\"$")
// public void I_update_cloudify_manager_s_url_to_for_cloud_with_name(int cloudifyVersion, String cloudifyUrl, String cloudName) throws Throwable {
// I_update_cloudify_manager_s_url_to_with_login_and_password_for_cloud_with_name(cloudifyVersion, cloudifyUrl, null, null, cloudName);
// }
//
// @And("^I update cloudify (\\d+) manager's url to \"([^\"]*)\" with login \"([^\"]*)\" and password \"([^\"]*)\" for cloud with name \"([^\"]*)\"$")
// public void I_update_cloudify_manager_s_url_to_with_login_and_password_for_cloud_with_name(int cloudifyVersion, String cloudifyUrl, String login,
// String password, String cloudName) throws Throwable {
// String cloudId = Context.getInstance().getCloudId(cloudName);
// Map<String, Object> config = Maps.newHashMap();
// switch (cloudifyVersion) {
// case 2:
// config.put("cloudifyURLs", Lists.newArrayList(cloudifyUrl));
// if (StringUtils.isNotBlank(login)) {
// config.put("username", login);
// }
// if (StringUtils.isNotBlank(password)) {
// config.put("password", password);
// }
// break;
// case 3:
// config.put("url", cloudifyUrl);
// config.put("cloudInit",
// "#!/bin/sh\nsudo cp /etc/hosts /tmp/hosts\necho 127.0.0.1 `hostname` | sudo tee /etc/hosts > /dev/null\ncat /tmp/hosts | sudo tee -a /etc/hosts > /dev/null");
// break;
// default:
// throw new IllegalArgumentException("Cloudify version not supported " + cloudifyVersion);
// }
// Context.getInstance().registerRestResponse(
// Context.getRestClientInstance().putJSon("/rest/clouds/" + cloudId + "/configuration", JsonUtil.toString(config)));
// }
//
// @And("^I update cloudify (\\d+) manager's url to the OpenStack's jenkins management server for cloud with name \"([^\"]*)\"$")
// public void I_update_cloudify_manager_s_url_to_the_OpenStack_s_jenkins_management_server_for_cloud_with_name(int cloudifyVersion, String cloudName)
// throws Throwable {
// switch (cloudifyVersion) {
// case 2:
// I_update_cloudify_manager_s_url_to_with_login_and_password_for_cloud_with_name(2, Context.getInstance().getCloudify2ManagerUrl(), Context
// .getInstance().getAppProperty("openstack.cfy2.manager_user"), Context.getInstance().getAppProperty("openstack.cfy2.manager_password"),
// cloudName);
// break;
// case 3:
// I_update_cloudify_manager_s_url_to_with_login_and_password_for_cloud_with_name(3, Context.getInstance().getCloudify3ManagerUrl(), Context
// .getInstance().getAppProperty("openstack.cfy3.manager_user"), Context.getInstance().getAppProperty("openstack.cfy3.manager_password"),
// cloudName);
// break;
// default:
// throw new NotSupportedException("Version " + cloudifyVersion + " of provider cloudify is not supported");
// }
// }
//} |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.limegroup.gnutella.gui;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.dnd.DropTarget;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.limewire.setting.SettingsGroupManager;
import org.limewire.util.OSUtils;
import com.frostwire.gui.bittorrent.BTDownloadMediator;
import com.frostwire.gui.library.LibraryMediator;
import com.frostwire.gui.tabs.LibraryTab;
import com.frostwire.gui.tabs.SearchDownloadTab;
import com.frostwire.gui.tabs.Tab;
import com.limegroup.gnutella.gui.GUIMediator.Tabs;
import com.limegroup.gnutella.gui.dnd.DNDUtils;
import com.limegroup.gnutella.gui.dnd.TransferHandlerDropTargetListener;
import com.limegroup.gnutella.gui.menu.MenuMediator;
import com.limegroup.gnutella.gui.options.OptionsMediator;
import com.limegroup.gnutella.gui.search.MagnetClipboardListener;
import com.limegroup.gnutella.settings.ApplicationSettings;
/**
* This class constructs the main <tt>JFrame</tt> for the program as well as
* all of the other GUI classes.
*/
public final class MainFrame {
/**
* Handle to the <tt>JTabbedPane</tt> instance.
*/
private JPanel TABBED_PANE;
private BTDownloadMediator BT_DOWNLOAD_MEDIATOR;
/**
* Constant handle to the <tt>LibraryView</tt> class that is
* responsible for displaying files in the user's repository.
*/
private LibraryMediator LIBRARY_MEDIATOR;
/**
* Constant handle to the <tt>OptionsMediator</tt> class that is
* responsible for displaying customizable options to the user.
*/
private OptionsMediator OPTIONS_MEDIATOR;
/**
* Constant handle to the <tt>StatusLine</tt> class that is
* responsible for displaying the status of the network and
* connectivity to the user.
*/
private StatusLine STATUS_LINE;
/**
* Handle the <tt>MenuMediator</tt> for use in changing the menu
* depending on the selected tab.
*/
private MenuMediator MENU_MEDIATOR;
/**
* The main <tt>JFrame</tt> for the application.
*/
private final JFrame FRAME;
/**
* The array of tabs in the main application window.
*/
private Map<GUIMediator.Tabs, Tab> TABS = new HashMap<GUIMediator.Tabs, Tab>(3);
/**
* The last state of the X/Y location and the time it was set.
* This is necessary to preserve the maximize size & prior size,
* as on Windows a move event is occasionally triggered when
* maximizing, prior to the state actually becoming maximized.
*/
private WindowState lastState = null;
private ApplicationHeader APPLICATION_HEADER;
/** simple state. */
private static class WindowState {
private final int x;
private final int y;
private final long time;
WindowState() {
x = ApplicationSettings.WINDOW_X.getValue();
y = ApplicationSettings.WINDOW_Y.getValue();
time = System.currentTimeMillis();
}
}
/**
* Initializes the primary components of the main application window,
* including the <tt>JFrame</tt> and the <tt>JTabbedPane</tt>
* contained in that window.
*/
MainFrame(JFrame frame) {
//starts the Frostwire update manager, and will trigger a task in 5 seconds.
// RELEASE
com.frostwire.gui.updates.UpdateManager.scheduleUpdateCheckTask(0);
// DEBUG
//com.frostwire.gui.updates.UpdateManager.scheduleUpdateCheckTask(0,"http://update1.frostwire.com/example.php");
FRAME = frame;
new DropTarget(FRAME, new TransferHandlerDropTargetListener(DNDUtils.DEFAULT_TRANSFER_HANDLER));
TABBED_PANE = new JPanel(new CardLayout());
// Add a listener for saving the dimensions of the window &
// position the search icon overlay correctly.
FRAME.addComponentListener(new ComponentListener() {
public void componentHidden(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
lastState = new WindowState();
saveWindowState();
}
public void componentResized(ComponentEvent e) {
saveWindowState();
}
});
// Listen for the size/state changing.
FRAME.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
saveWindowState();
}
});
// Listen for the window closing, to save settings.
FRAME.addWindowListener(new WindowAdapter() {
public void windowDeiconified(WindowEvent e) {
// Handle reactivation on systems which do not support
// the system tray. Windows systems call the
// WindowsNotifyUser.restoreApplication()
// method to restore applications from minimize and
// auto-shutdown modes. Non-windows systems restore
// the application using the following code.
if (!OSUtils.supportsTray() || !ResourceManager.instance().isTrayIconAvailable())
GUIMediator.restoreView();
}
public void windowClosing(WindowEvent e) {
saveWindowState();
SettingsGroupManager.instance().save();
GUIMediator.close(true);
}
});
FRAME.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.setFrameDimensions();
FRAME.setJMenuBar(getMenuMediator().getMenuBar());
JPanel contentPane = new JPanel();
FRAME.setContentPane(contentPane);
contentPane.setLayout(new MigLayout("insets 0, gap 0"));
buildTabs();
APPLICATION_HEADER = new ApplicationHeader(TABS);
contentPane.add(APPLICATION_HEADER, "growx, dock north");
contentPane.add(TABBED_PANE, "wrap");
contentPane.add(getStatusLine().getComponent(), "dock south, shrink 0");
setMinimalSize(FRAME, APPLICATION_HEADER, APPLICATION_HEADER, TABBED_PANE, getStatusLine().getComponent());
FRAME.setJMenuBar(getMenuMediator().getMenuBar());
if (ApplicationSettings.MAGNET_CLIPBOARD_LISTENER.getValue()) {
FRAME.addWindowListener(MagnetClipboardListener.getInstance());
}
}
private void setMinimalSize(JFrame frame, JComponent horizontal, JComponent... verticals) {
int width = 0;
int height = 0;
width = horizontal.getMinimumSize().width;
for (JComponent c : verticals) {
height += c.getMinimumSize().height;
}
// for some reason I can pack the frame
// this disallow me of getting the right size of the title bar
// and in general the insets's frame
// lets add some fixed value for now
height += 50;
frame.setMinimumSize(new Dimension(width, height));
}
public ApplicationHeader getApplicationHeader() {
return APPLICATION_HEADER;
}
/** Saves the state of the Window to settings. */
void saveWindowState() {
int state = FRAME.getExtendedState();
if (state == Frame.NORMAL) {
// save the screen size and location
Dimension dim = GUIMediator.getAppSize();
if ((dim.height > 100) && (dim.width > 100)) {
Point loc = GUIMediator.getAppLocation();
ApplicationSettings.APP_WIDTH.setValue(dim.width);
ApplicationSettings.APP_HEIGHT.setValue(dim.height);
ApplicationSettings.WINDOW_X.setValue(loc.x);
ApplicationSettings.WINDOW_Y.setValue(loc.y);
ApplicationSettings.MAXIMIZE_WINDOW.setValue(false);
}
} else if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
ApplicationSettings.MAXIMIZE_WINDOW.setValue(true);
if (lastState != null && lastState.time == System.currentTimeMillis()) {
ApplicationSettings.WINDOW_X.setValue(lastState.x);
ApplicationSettings.WINDOW_Y.setValue(lastState.y);
lastState = null;
}
}
}
/**
* Build the Tab Structure based on advertising mode and Windows
*/
private void buildTabs() {
TABBED_PANE.addMouseListener(com.frostwire.gui.tabs.TabRightClickAdapter.getInstance());
TABS.put(GUIMediator.Tabs.SEARCH, new SearchDownloadTab(getBTDownloadMediator()));
TABS.put(GUIMediator.Tabs.LIBRARY, new LibraryTab(getLibraryMediator()));
//TABS.put(GUIMediator.Tabs.CHAT, new ChatTab());
TABBED_PANE.setPreferredSize(new Dimension(10000, 10000));
// add all tabs initially....
for (GUIMediator.Tabs tab : GUIMediator.Tabs.values()) {
Tab t = TABS.get(tab);
if (t != null && t.getComponent() != null) {
this.addTab(t);
}
}
TABBED_PANE.setRequestFocusEnabled(false);
}
/**
* Adds a tab to the <tt>JTabbedPane</tt> based on the data supplied
* in the <tt>Tab</tt> instance.
*
* @param tab the <tt>Tab</tt> instance containing data for the tab to
* add
*/
private void addTab(Tab tab) {
TABBED_PANE.add(tab.getComponent(), tab.getTitle());
}
/**
* Sets the selected index in the wrapped <tt>JTabbedPane</tt>.
*
* @param index the tab index to select
*/
public final void setSelectedTab(GUIMediator.Tabs tab) {
CardLayout cl = (CardLayout) (TABBED_PANE.getLayout());
Tab t = TABS.get(tab);
cl.show(TABBED_PANE, t.getTitle());
APPLICATION_HEADER.selectTab(t);
}
/**
* Sets the x,y location as well as the height and width of the main
* application <tt>Frame</tt>.
*/
private final void setFrameDimensions() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int locX = 0;
int locY = 0;
int appWidth = Math.min(screenSize.width - insets.left - insets.right, ApplicationSettings.APP_WIDTH.getValue());
int appHeight = Math.min(screenSize.height - insets.top - insets.bottom, ApplicationSettings.APP_HEIGHT.getValue());
// Set the location of our window based on whether or not
// the user has run the program before, and therefore may have
// modified the location of the main window.
if (ApplicationSettings.RUN_ONCE.getValue()) {
locX = Math.max(insets.left, ApplicationSettings.WINDOW_X.getValue());
locY = Math.max(insets.top, ApplicationSettings.WINDOW_Y.getValue());
} else {
locX = (screenSize.width - appWidth) / 2;
locY = (screenSize.height - appHeight) / 2;
}
// Make sure the Window is visible and not for example
// somewhere in the very bottom right corner.
if (locX + appWidth > screenSize.width) {
locX = Math.max(insets.left, screenSize.width - insets.left - insets.right - appWidth);
}
if (locY + appHeight > screenSize.height) {
locY = Math.max(insets.top, screenSize.height - insets.top - insets.bottom - appHeight);
}
FRAME.setLocation(locX, locY);
FRAME.setSize(new Dimension(appWidth, appHeight));
FRAME.getContentPane().setSize(new Dimension(appWidth, appHeight));
((JComponent) FRAME.getContentPane()).setPreferredSize(new Dimension(appWidth, appHeight));
//re-maximize if we shutdown while maximized.
if (ApplicationSettings.MAXIMIZE_WINDOW.getValue() && Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
FRAME.setExtendedState(Frame.MAXIMIZED_BOTH);
}
}
final BTDownloadMediator getBTDownloadMediator() {
if (BT_DOWNLOAD_MEDIATOR == null) {
BT_DOWNLOAD_MEDIATOR = BTDownloadMediator.instance();
}
return BT_DOWNLOAD_MEDIATOR;
}
/**
* Returns a reference to the <tt>LibraryMediator</tt> instance.
*
* @return a reference to the <tt>LibraryMediator</tt> instance
*/
final com.frostwire.gui.library.LibraryMediator getLibraryMediator() {
if (LIBRARY_MEDIATOR == null) {
LIBRARY_MEDIATOR = LibraryMediator.instance();
}
return LIBRARY_MEDIATOR;
}
/**
* Returns a reference to the <tt>StatusLine</tt> instance.
*
* @return a reference to the <tt>StatusLine</tt> instance
*/
final StatusLine getStatusLine() {
if (STATUS_LINE == null) {
STATUS_LINE = new StatusLine();
}
return STATUS_LINE;
}
/**
* Returns a reference to the <tt>MenuMediator</tt> instance.
*
* @return a reference to the <tt>MenuMediator</tt> instance
*/
public final MenuMediator getMenuMediator() {
if (MENU_MEDIATOR == null) {
MENU_MEDIATOR = MenuMediator.instance();
}
return MENU_MEDIATOR;
}
/**
* Returns a reference to the <tt>OptionsMediator</tt> instance.
*
* @return a reference to the <tt>OptionsMediator</tt> instance
*/
final OptionsMediator getOptionsMediator() {
if (OPTIONS_MEDIATOR == null) {
OPTIONS_MEDIATOR = OptionsMediator.instance();
}
return OPTIONS_MEDIATOR;
}
public Tabs getSelectedTab() {
Component comp = getCurrentTabComponent();
if (comp != null) {
for (Tabs t : TABS.keySet()) {
if (TABS.get(t).getComponent().equals(comp)) {
return t;
}
}
}
return null;
}
private Component getCurrentTabComponent() {
Component currentPanel = null;
for (Component component : TABBED_PANE.getComponents()) {
if (component.isVisible()) {
if (component instanceof JPanel)
currentPanel = component;
else if (component instanceof JScrollPane)
currentPanel = ((JScrollPane) component).getViewport().getComponent(0);
}
}
return currentPanel;
}
public Tab getTab(Tabs tabs) {
return TABS.get(tabs);
}
public void resizeSearchTransferDivider(int newLocation) {
SearchDownloadTab searchTab = (SearchDownloadTab) TABS.get(GUIMediator.Tabs.SEARCH);
searchTab.setDividerLocation(newLocation);
}
}
|
package org.gracejvc.vanrin.dao;
import java.util.List;
import org.gracejvc.vanrin.model.Nationality;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class NationalityADOImpl implements NationalityADO {
private SessionFactory sessionFactory;
public NationalityADOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<Nationality> allNationlity() {
Session session = this.sessionFactory.getCurrentSession();
List<Nationality> nationalities = session.createQuery("from Nationality").list();
return nationalities;
}
@Override
public Nationality findNationalityById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Nationality n = session.load(Nationality.class,new Integer(id));
return n;
}
@Override
public void newNationality(Nationality n) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(n);
}
@Override
public void removeNationality(int id) {
// TODO Auto-generated method stub
}
@Override
public void updateNationlity(Nationality n) {
// TODO Auto-generated method stub
}
}
|
package com.dusan.demoproject.controller;
import com.dusan.demoproject.domain.Todo;
import com.dusan.demoproject.shared.TodoNotFoundException;
import com.dusan.demoproject.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TodoController {
@Autowired
private TodoService todoService;
@GetMapping("/users/{name}/todos")
public List<Todo> retrieveTodos(@PathVariable String name){
return todoService.retrieveTodos(name);
}
@GetMapping(path = "/users/{name}/todos/{id}")
public Todo retrieveTodo(@PathVariable String name, @PathVariable int id){
Todo todo = todoService.retrieveTodo(id);
if (todo == null){
throw new TodoNotFoundException("Todo not found");
}
return todo;
}
}
|
package edu.betygreg.data;
public class DataFacade {
public DataFacade() {
}
public void setGrade(String id, String grade) throws Exception {
DBFacadeSingleton.getDBFacadeSingleton().setStudentGrade(id, grade);
}
public String getGrade(String id) throws Exception {
return DBFacadeSingleton.getDBFacadeSingleton().getStudentGrade(id);
}
}
|
package com.framgia.fsalon.screen.customer;
import com.framgia.fsalon.data.model.CustomerResponse;
import com.framgia.fsalon.data.source.UserRepository;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import static com.framgia.fsalon.utils.Constant.ApiParram.FIRST_PAGE;
/**
* Listens to user actions from the UI ({@link CustomerFragment}), retrieves the data and updates
* the UI as required.
*/
public class CustomerPresenter implements CustomerContract.Presenter {
private final CustomerContract.ViewModel mViewModel;
private static final int PER_PAGE = 10;
private UserRepository mUserRepository;
private int mPage = FIRST_PAGE;
private CompositeDisposable mCompositeDisposable;
public CustomerPresenter(CustomerContract.ViewModel viewModel,
UserRepository userRepository) {
mViewModel = viewModel;
mUserRepository = userRepository;
mCompositeDisposable = new CompositeDisposable();
getCustomers(FIRST_PAGE);
}
@Override
public void onStart() {
}
@Override
public void onStop() {
mCompositeDisposable.clear();
}
@Override
public void getCustomers(int page) {
Disposable disposable = mUserRepository.getAllCustomers(page, PER_PAGE)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(@NonNull Disposable disposable) throws Exception {
mViewModel.showLoadMore();
}
}).subscribeWith(new DisposableObserver<CustomerResponse>() {
@Override
public void onNext(@NonNull CustomerResponse bookingCustomers) {
mViewModel.onCustomersSuccessful(bookingCustomers.getData());
}
@Override
public void onError(@NonNull Throwable e) {
mViewModel.onCustomerFail();
mViewModel.hideLoadMore();
}
@Override
public void onComplete() {
mViewModel.hideLoadMore();
}
});
mCompositeDisposable.add(disposable);
mPage = page;
}
@Override
public void searchUser(String keyword, int page) {
Disposable disposable = mUserRepository.searchCustomer(keyword, PER_PAGE, page)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(@NonNull Disposable disposable) throws Exception {
mViewModel.showLoadMore();
}
}).subscribeWith(new DisposableObserver<CustomerResponse>() {
@Override
public void onNext(@NonNull CustomerResponse customers) {
mViewModel.onSearchSuccessful(customers.getData());
}
@Override
public void onError(@NonNull Throwable e) {
mViewModel.onSearchFail();
mViewModel.hideLoadMore();
}
@Override
public void onComplete() {
mViewModel.hideLoadMore();
}
});
mCompositeDisposable.add(disposable);
mPage = page;
}
@Override
public void loadMoreData() {
mPage++;
getCustomers(mPage);
}
@Override
public void loadMoreSearch(String keyword) {
mPage++;
searchUser(keyword, mPage);
}
}
|
package com.example.BankOperation.service;
import com.example.BankOperation.model.Credit;
import com.example.BankOperation.model.Payment;
import java.util.List;
public interface PaymentService {
// Credit addPayment(Payment p);
//
List<Payment> getPaymentHistory(Long id);
//
// Payment getPayment(Long id);
//
// Payment updatePayment(Payment p);
// void deletePayment(Long id);
Payment beginPayment(Payment payment);
Payment confirmPayment(Long id, Integer confirmationCode);
}
|
package com.data.main.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class EMPLOYEE_INFORMATIONS_E {
@Id
private Number EMPLOYEE_ID;
private String EMPLOYEE_NAME;
private String EMPLOYEE_ID_CARD;
private String EMPLOYEE_SEX;
private Date EMPLOYEE_BIRTHDAY;
private String EMPLOYEE_BUMBER;
private String EMPLOYEE_NATIVE_PLACE;
private String EMPLOYEE_PERMANENT_ADDRESS;
private Number EMPLOYEE_PHONE_NUMBER;
private String EMPLOYEE_CONTACT_INFORMATION;
private String EMPLOYEE_EMERGENCY_CONTACT;
@Override
public String toString() {
// TODO Auto-generated method stub
return "EMPLOYEE_NAME : " + EMPLOYEE_NAME + " ," +
"EMPLOYEE_ID_CARD : " + EMPLOYEE_ID_CARD + " ," +
"EMPLOYEE_SEX : " + EMPLOYEE_SEX + " ," +
"EMPLOYEE_BIRTHDAY : " + EMPLOYEE_BIRTHDAY + " ," +
"EMPLOYEE_BUMBER : " + EMPLOYEE_BUMBER + " ," +
"EMPLOYEE_NATIVE_PLACE : " + EMPLOYEE_NATIVE_PLACE + " ," +
"EMPLOYEE_PERMANENT_ADDRESS : " + EMPLOYEE_PERMANENT_ADDRESS + " ," +
"EMPLOYEE_PHONE_NUMBER : " + EMPLOYEE_PHONE_NUMBER + " ," +
"EMPLOYEE_CONTACT_INFORMATION : " + EMPLOYEE_CONTACT_INFORMATION + " ," +
"EMPLOYEE_EMERGENCY_CONTACT : " + EMPLOYEE_EMERGENCY_CONTACT + " ,";
}
public Number getEMPLOYEE_ID() {
return EMPLOYEE_ID;
}
public void setEMPLOYEE_ID(Number eMPLOYEE_ID) {
EMPLOYEE_ID = eMPLOYEE_ID;
}
public String getEMPLOYEE_NAME() {
return EMPLOYEE_NAME;
}
public void setEMPLOYEE_NAME(String eMPLOYEE_NAME) {
EMPLOYEE_NAME = eMPLOYEE_NAME;
}
public String getEMPLOYEE_ID_CARD() {
return EMPLOYEE_ID_CARD;
}
public void setEMPLOYEE_ID_CARD(String eMPLOYEE_ID_CARD) {
EMPLOYEE_ID_CARD = eMPLOYEE_ID_CARD;
}
public String getEMPLOYEE_SEX() {
return EMPLOYEE_SEX;
}
public void setEMPLOYEE_SEX(String eMPLOYEE_SEX) {
EMPLOYEE_SEX = eMPLOYEE_SEX;
}
public Date getEMPLOYEE_BIRTHDAY() {
return EMPLOYEE_BIRTHDAY;
}
public void setEMPLOYEE_BIRTHDAY(Date eMPLOYEE_BIRTHDAY) {
EMPLOYEE_BIRTHDAY = eMPLOYEE_BIRTHDAY;
}
public String getEMPLOYEE_BUMBER() {
return EMPLOYEE_BUMBER;
}
public void setEMPLOYEE_BUMBER(String eMPLOYEE_BUMBER) {
EMPLOYEE_BUMBER = eMPLOYEE_BUMBER;
}
public String getEMPLOYEE_NATIVE_PLACE() {
return EMPLOYEE_NATIVE_PLACE;
}
public void setEMPLOYEE_NATIVE_PLACE(String eMPLOYEE_NATIVE_PLACE) {
EMPLOYEE_NATIVE_PLACE = eMPLOYEE_NATIVE_PLACE;
}
public String getEMPLOYEE_PERMANENT_ADDRESS() {
return EMPLOYEE_PERMANENT_ADDRESS;
}
public void setEMPLOYEE_PERMANENT_ADDRESS(String eMPLOYEE_PERMANENT_ADDRESS) {
EMPLOYEE_PERMANENT_ADDRESS = eMPLOYEE_PERMANENT_ADDRESS;
}
public Number getEMPLOYEE_PHONE_NUMBER() {
return EMPLOYEE_PHONE_NUMBER;
}
public void setEMPLOYEE_PHONE_NUMBER(Number eMPLOYEE_PHONE_NUMBER) {
EMPLOYEE_PHONE_NUMBER = eMPLOYEE_PHONE_NUMBER;
}
public String getEMPLOYEE_CONTACT_INFORMATION() {
return EMPLOYEE_CONTACT_INFORMATION;
}
public void setEMPLOYEE_CONTACT_INFORMATION(String eMPLOYEE_CONTACT_INFORMATION) {
EMPLOYEE_CONTACT_INFORMATION = eMPLOYEE_CONTACT_INFORMATION;
}
public String getEMPLOYEE_EMERGENCY_CONTACT() {
return EMPLOYEE_EMERGENCY_CONTACT;
}
public void setEMPLOYEE_EMERGENCY_CONTACT(String eMPLOYEE_EMERGENCY_CONTACT) {
EMPLOYEE_EMERGENCY_CONTACT = eMPLOYEE_EMERGENCY_CONTACT;
}
}
|
package forkjoinV2;
import java.util.Deque;
import java.util.LinkedList;
/**
* Thread pool, based on the fork-join framework.
* Executes tasks that extend the abstract {@link Task} class.
* <p>
* To use this fork-join pool, instantiate a {@link Pool} object, call
* {@link Pool#start()} to start the worker threads, submit external tasks
* using {@link Pool#addExternalTask(Task)} method, and call
* {@link Pool#terminate()} to shut the pool down once the tasks are complete.
* <p>
* This implementation maintains a central task queue, with internal threads
* taking tasks from and adding tasks to the front, and with external threads
* submitting tasks to the back.
* <p>
* All synchronisation is managed by a single lock.
*/
public class Pool {
private final Deque<Task<?>> taskQueue = new LinkedList<>();
private final Worker[] workers;
private final Object lock = new Object();
private boolean isShutdown = false;
/**
* Fork-join pool
*
* @param numWorkers number of worker threads in pool
*/
public Pool(int numWorkers) {
workers = new Worker[numWorkers];
for (int workerId = 0; workerId < numWorkers; workerId++) {
workers[workerId] = new Worker(this);
}
}
Object getLock() {
return lock;
}
boolean hasTask() {
return !taskQueue.isEmpty();
}
void addTask(Task<?> task) {
taskQueue.offerFirst(task);
}
void addExternalTask(Task<?> task) {
taskQueue.offerLast(task);
}
Task<?> getTask() {
return taskQueue.pollFirst();
}
boolean isShutdown() {
return isShutdown;
}
/**
* Submits external {@link Task} to pool for execution.
* The thread that calls this method will hang until the task is complete,
* at which point it will return with the result of the task.
*
* @param task external task to submit
* @return result of completing task
*/
public <V> V invoke (Task<V> task) {
return task.externalInvoke(this);
}
/**
* Starts the worker threads, allowing the thread pool to execute tasks.
*/
public void start() {
for (Worker worker : workers) {
worker.start();
}
}
/**
* Terminates each worker thread once it has completed its current task.
*/
public void terminate() {
synchronized (lock) {
isShutdown = true;
lock.notifyAll();
}
for (Worker worker : workers) {
try {
worker.join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
}
}
|
package Lec_02_SimpleOperationsAndCalculations;
import java.util.Scanner;
public class Lab05_ProjectsCreation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведете име на архитект: ");
String name = scanner.nextLine();
System.out.print("Въведете брой на проекти: ");
int numberProjects = Integer.parseInt(scanner.nextLine());
int hourOfProjects = numberProjects * 3;
System.out.printf("The architect %s will need %d hours to complete %d project/s."
, name, hourOfProjects, numberProjects);
}
}
|
package generic;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest<Static> implements IAutoConstant {
WebDriver driver;
@BeforeMethod
public void setup() throws IOException {
Flib Flib = new Flib();
String browservalue = Flib.readPropertyData(PROP_PATH, "browser");
String baseurl = Flib.readPropertyData(PROP_PATH, "url");
if (browservalue.equalsIgnoreCase("chrome")) {
System.setProperty(CHROME_KEY, CHROME_PATH);
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(ITO, TimeUnit.SECONDS);
driver.get(baseurl);
} else if (browservalue.equalsIgnoreCase("firefox")) {
System.setProperty(GECKO_KEY, GECKO_PATH);
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(ITO, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(baseurl);
} else {
System.out.println("Invalid o/p");
}
}
@AfterMethod
public void closeBrowser() {
driver.quit();
}
}
|
package com.kwik.fixture.load;
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.Rule;
import com.kwik.fixture.ProdutoSpike;
import com.kwik.infra.security.Encryption;
import com.kwik.models.Address;
import com.kwik.models.Category;
import com.kwik.models.Client;
import com.kwik.models.Product;
import com.kwik.models.Specifics;
public class TemplateLoader {
public static void loadTemplatesForFixture() {
TemplateLoader.ProductTemplate.loadTemplates();
TemplateLoader.CategoryTemplate.loadTemplates();
TemplateLoader.SpecificsTemplate.loadTemplates();
TemplateLoader.ClientTemplate.loadTemplates();
TemplateLoader.AddressTemplate.loadTemplates();
}
public static class ProductTemplate {
public static final String CAMISETA_BRANCA_FOR_SPIKE = "camiseta-branca-for-spike";
public static final String CAMISETA_BRANCA = "camiseta-branca";
public static final String CAMISETA_BRANCA_JA_ASSOCIADA = "camiseta-branca-ja-associada";
public static final String CAMISETA_PRETA_JA_ASSOCIADA = "camiseta-branca-ja-associada";
public static void loadTemplates() {
Fixture.of(ProdutoSpike.class).addTemplate(CAMISETA_BRANCA_FOR_SPIKE,
new Rule() {{
add("id", 1L);
}});
Fixture.of(Product.class).addTemplate(CAMISETA_BRANCA,
new Rule() {{
add("name", "Camiseta");
add("description", "Uma camiseta branca marota");
add("value", 100.00);
add("specifics", one(Specifics.class, SpecificsTemplate.ESPECIFICACOES_CAMISETA));
}});
Fixture.of(Product.class).addTemplate(CAMISETA_BRANCA_JA_ASSOCIADA,
new Rule() {{
add("id", 1L);
add("name", "Camiseta");
add("description", "Camiseta StarWars - Darth Vader - Preta");
}});
Fixture.of(Product.class).addTemplate(CAMISETA_PRETA_JA_ASSOCIADA,
new Rule() {{
add("id", 2L);
add("name", "Camiseta");
add("description", "Camiseta StarWars - Darth Vader - Preta");
}});
}
}
public static class CategoryTemplate {
public static final String CATEGORIA_ROUPAS = "categoria-roupas";
public static void loadTemplates() {
Fixture.of(Category.class).addTemplate(CATEGORIA_ROUPAS,
new Rule() {{
add("id", 99L);
add("description", "Roupas");
}});
}
}
public static class SpecificsTemplate {
public static final String ESPECIFICACOES_CAMISETA = "especificacoes-camiseta";
public static void loadTemplates() {
Fixture.of(Specifics.class).addTemplate(ESPECIFICACOES_CAMISETA,
new Rule() {{
add("brand", "Hering");
add("size", "tamanho P");
}});
}
}
public static class ClientTemplate {
public static final String JOAO = "joao";
public static final String JOAO_COM_SENHA_CRIPTOGRAFADA = "joao-criptografada";
public static void loadTemplates() {
Fixture.of(Client.class).addTemplate(JOAO,
new Rule() {{
add("email", "joao@test.com");
add("password", "secret");
}});
Fixture.of(Client.class).addTemplate(JOAO_COM_SENHA_CRIPTOGRAFADA,
new Rule() {{
add("email", "joao@test.com");
add("password", new Encryption("secret").md5());
}});
}
}
public static class AddressTemplate {
public static final String ENDERECO = "endereco";
public static void loadTemplates() {
Fixture.of(Address.class).addTemplate(ENDERECO,
new Rule() {{
add("district", "Penha");
add("location", "Sao Paulo");
add("street", "Rua da Penha");
add("zipCode", "01478520");
}});
}
}
}
|
package com.dongann.app.cusers;
import com.dongann.app.TestBase;
import com.dongann.app.service.cuser.CusersService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* @FileName: CusersServiceTest
* @Author: <a href="dongann@aliyun.com">dongchang'an</a>.
* @CreateTime: 2018/7/10 下午5:58
* @Version: v1.0
* @description:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableCaching
public class CusersServiceTest extends TestBase {
@Resource
private CusersService cusersService;
@Test
public void testGetCuserByToken(){
print(cusersService.getCuserByToken("5719fae0842711e89fc376e92d243085"));
}
@Test
public void testGetCusersPageList(){
print(cusersService.getCusersPageList(0,10));
}
}
|
package com.transport.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import javax.sql.DataSource;
//import org.springframework.jdbc.core.JdbcTemplate;
import com.transport.config.ServerContext;
import com.transport.constant.MapConstant;
import com.transport.dao.LoginDao;
import com.transport.model.User;
import com.transport.util.EncryptUtil;
import com.transport.util.TransportUtils;
public class LoginDaoImpl implements LoginDao {
// private DataSource dataSource;
//
// public void setDataSource(DataSource dataSource) {
// this.dataSource = dataSource;
// }
@Override
public void init() {
System.out.println("init(): Initialization part here for LoginDaoImpl....");
}
@Override
public void destroy() {
System.out.println("destroy(): After calling the context.close() code here for LoginDaoImpl....");
}
@Override
public Map<String, Object> validateUserAccount(User user) throws Exception{
// TODO Auto-generated method stub
System.out.println("LoginDaoImpl validateUserAccount() - Entry");
//use DBCP JNDI
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Map<String, Object> returnMap = null;
List<User> rsList = new ArrayList<User>();
StringBuffer qry = new StringBuffer("select a.id");
qry.append(",b.firstname||' '||b.lastname as name ");
qry.append(",c.id as roleid ");
qry.append(",c.listvalue as role ");
qry.append(",a.username ");
qry.append(",b.id ");
qry.append(",a.password ");
qry.append(",a.createdby ");
qry.append(",a.createdon ");
qry.append(",a.modifiedby ");
qry.append(",a.modifiedon ");
qry.append(",a.version ");
qry.append(",a.active ");
qry.append(" from transport.file_user a, transport.file_employee b, transport.list_value c ");
qry.append(" where a.employeeid = b.id ");
qry.append(" and a.roleid = c.id ");
qry.append(" and a.active = true ");//both user account and employee is active
qry.append(" and b.active = true ");
qry.append(" and username = ? ");
qry.append(" and password = ? ");
try {
conn = ServerContext.getJDBCHandle();
pstmt = conn.prepareStatement(qry.toString());
pstmt.setString(1, user.getUserName());
pstmt.setString(2, EncryptUtil.encrypt(user.getPassword()));
rs = pstmt.executeQuery();
if(rs.next()) {
User dto = new User();
dto.setId(rs.getInt(1));
dto.setName(rs.getString(2));
dto.setRoleId(rs.getInt(3));
dto.setRole(rs.getString(4));
dto.setUserName(rs.getString(5));
dto.setEmployeeId(rs.getInt(6));
rsList.add(dto);
} else {
rsList = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
TransportUtils.closeObjects(rs);
TransportUtils.closeObjects(pstmt);
TransportUtils.closeObjects(conn);
}
if (rsList!=null && !rsList.isEmpty()) {
returnMap = new HashMap<String, Object>();
returnMap.put(MapConstant.CLASS_DATA, rsList.get(0));
}
//uses Spring JDBC
// String qry = "select * from pibs.file_user where username = ? and password = ? ";
//
// JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//
// List<Map<String, Object>> rsList = jdbcTemplate.queryForList(qry, new Object[] { user.getUserName(), user.getPassword()});
//
// Map<String, Object> returnMap = null;
//
// if (rsList!=null && !rsList.isEmpty()) {
// returnMap = new HashMap<String, Object>();
// returnMap.put(MapConstant.CLASS_DATA, rsList.get(0));
// }
System.out.println("LoginDaoImpl validateUserAccount() - Exit");
return returnMap;
}
}
|
package lavaplayer.source.local;
import java.io.File;
import lavaplayer.container.MediaContainerProbe;
import lavaplayer.source.AudioSourceManager;
import lavaplayer.track.AudioTrack;
import lavaplayer.track.AudioTrackInfo;
import lavaplayer.track.DelegatedAudioTrack;
import lavaplayer.track.InternalAudioTrack;
import lavaplayer.track.playback.LocalAudioTrackExecutor;
/**
* Audio track that handles processing local files as audio tracks.
*/
public class LocalAudioTrack extends DelegatedAudioTrack {
private final File file;
private final MediaContainerProbe probe;
private final LocalAudioSourceManager sourceManager;
/**
* @param trackInfo Track info
* @param probe Probe for the media container of this track
* @param sourceManager Source manager used to load this track
*/
public LocalAudioTrack(AudioTrackInfo trackInfo, MediaContainerProbe probe, LocalAudioSourceManager sourceManager) {
super(trackInfo);
this.file = new File(trackInfo.identifier);
this.probe = probe;
this.sourceManager = sourceManager;
}
/**
* @return The media probe which handles creating a container-specific delegated track for this track.
*/
public MediaContainerProbe getProbe() {
return probe;
}
@Override
public void process(LocalAudioTrackExecutor localExecutor) throws Exception {
try (LocalSeekableInputStream inputStream = new LocalSeekableInputStream(file)) {
processDelegate((InternalAudioTrack) probe.createTrack(trackInfo, inputStream), localExecutor);
}
}
@Override
public AudioTrack makeClone() {
return new LocalAudioTrack(trackInfo, probe, sourceManager);
}
@Override
public AudioSourceManager getSourceManager() {
return sourceManager;
}
} |
package com.gaoshin.cloud.web.vm.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class GaoVmEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(nullable=false)
private Long hostId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getHostId() {
return hostId;
}
public void setHostId(Long hostId) {
this.hostId = hostId;
}
}
|
Node mergeLists(Node l1, Node l2) {
// This is a "method-only" submission.
// You only need to complete this method
Node head = new Node();
Node p = head;
while(l1!=null||l2!=null){
if(l1!=null&&l2!=null){
if(l1.data < l2.data){
p.next = l1;
l1=l1.next;
}else{
p.next=l2;
l2=l2.next;
}
p = p.next;
}else if(l1==null){
p.next = l2;
break;
}else if(l2==null){
p.next = l1;
break;
}
}
return head.next;
}
|
package mod6AI.ai;
/**
* Created by Student on 25-11-2014.
*/
public enum ClassificationType {
C1("C1"),
C2("C2");
private String name;
private ClassificationType(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
|
package db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.*;
import java.io.Serializable;
/**
* 测试类——Word
* Created by 6gold on 2017/3/14.
*/
public class Word implements Serializable {
private static final long serialVersionUID = 1L;
public String spelling;//拼写
public String soundmark;//音标
public String meaning;//释义
public byte[] pronounce;//发音
public String example;//例子
public int familarity;//熟悉度
public Word(){
}
public int getFamilarity() {
return familarity;
}
public void setFamilarity(int familarity) {
this.familarity = familarity;
}
public String getMeaning() {
return meaning;
}
public void setMeaning(String meaning) {
this.meaning = meaning;
}
public Word(String spelling, String soundmark, String meaning, String example) {
this.spelling = spelling;
this.soundmark = soundmark;
this.meaning = meaning;
this.example = example;
}
public void setSpelling(String spelling) {
this.spelling = spelling;
}
public String getSpelling() {
return spelling;
}
public void setParaphrase(String meaning) {
this.meaning = meaning;
}
public String getParaphrase() {
return meaning;
}
public void setPronounce(byte[] pronounce) {
this.pronounce = pronounce;
}
public byte[] getPronounce() {
return pronounce;
}
public void setExample(String example) {
this.example = example;
}
public String getExample() {
return example;
}
public String getSoundmark() {
return soundmark;
}
public void setSoundmark(String soundmark) {
this.soundmark = soundmark;
}
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ut.healthelink.service;
import com.ut.healthelink.model.newsArticle;
import java.util.List;
/**
*
* @author chadmccue
*/
public interface newsArticleManager {
void createNewsArticle(newsArticle article) throws Exception;
void updateNewsArticle(newsArticle article) throws Exception;
void deleteNewsArticle(int id) throws Exception;
List<newsArticle> listAllNewsArticles() throws Exception;
List<newsArticle> listAllActiveNewsArticles() throws Exception;
newsArticle getNewsArticleById(int id) throws Exception;
List<newsArticle> getNewsArticleByTitle(String articleTitle) throws Exception;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.infiniteskills.mvc.controllers.rest;
import static com.infiniteskills.mvc.controllers.rest.RestControllerRabota._PATH9;
import com.infiniteskills.mvc.entity.Rabota;
import com.infiniteskills.mvc.repository.RabotaRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.RestController;
/**
*
* @author Îëåã
*/
@RestController
@RequestMapping(path = _PATH9,produces = MediaType.APPLICATION_JSON_VALUE)
public class RestControllerRabota {
public static final String _PATH9 = "/restrabota";
public static final String ITEM_PATH = "/item";
private RabotaRepository uService;
@Autowired(required = false)
public void setService(RabotaRepository uService) {
this.uService = uService;
}
@RequestMapping(method = RequestMethod.GET)
public List<Rabota> getUnitList() {
return uService.findAll();
}
@RequestMapping(method = RequestMethod.POST,
path = ITEM_PATH,
consumes = MediaType.APPLICATION_JSON_VALUE)
public Rabota createU(@RequestBody Rabota zav) {
return uService.create(zav);
}
@RequestMapping(method = RequestMethod.PUT,
path = ITEM_PATH,
consumes = MediaType.APPLICATION_JSON_VALUE)
public Rabota updateU(@RequestBody Rabota zav) {
return uService.update(zav);
}
@RequestMapping(method = RequestMethod.DELETE,
path = ITEM_PATH,
consumes = MediaType.APPLICATION_JSON_VALUE)
public void deleteU(@RequestBody Rabota zav) {
uService.delete(zav);
}
}
|
package edu.neu.ccs.cs5010;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class DetachedHouse implements House {
Candy detachedCandy;
List detachedList;
/**
*
* @return the candy list detached house can give to children
*/
public List getCandy(){
//detachedCandy = new Candy();
detachedList = new ArrayList();
detachedList.add(detachedCandy.createCandy("Super","Kit Kat"));
detachedList.add(detachedCandy.createCandy("Super","Whoopers"));
detachedList.add(detachedCandy.createCandy("Super","Milky Way"));
detachedList.add(detachedCandy.createCandy("Super","Crunch"));
detachedList.add(detachedCandy.createCandy("King","Toblerone"));
detachedList.add(detachedCandy.createCandy("Fun","Twix"));
detachedList.add(detachedCandy.createCandy("Fun","Snickers"));
detachedList.add(detachedCandy.createCandy("Fun","Mars"));
return detachedList;
}
/*Node detachedHouse = new Node<String>();
{
Node superSize = new Node();
Node kingSize = new Node();
Node funSize = new Node();
detachedHouse.children.add(superSize);
detachedHouse.children.add(kingSize);
detachedHouse.children.add(funSize);
superSize.children.add("Kit Kat");
superSize.children.add("Whoopers");
superSize.children.add("Milky Way");
superSize.children.add("Crunch");
kingSize.children.add("Toblerone");
funSize.children.add("Twix");
funSize.children.add("Snickers");
funSize.children.add("Mars");
}
*/
@Override
public void accept(Visitor visitor) throws FileNotFoundException {
visitor.visit(this);
}
@Override
public String getHouseName() {
return "Detached House";
}
}
|
package com.example.arthi.appendixxxvi;
import android.content.Context;
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.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by arthi on 11/27/2018.
*/
public class FamilyAddapter extends RecyclerView.Adapter<FamilyAddapter.MyViewHolder> {
private Context mainActivityUser;
private ArrayList<Family> FamilyList;
private OnItemClick onItemClick;
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView serialNo,
familyName,
relation;
LinearLayout parentLinear;
public MyViewHolder(View view){
super((view));
serialNo =(TextView) view.findViewById(R.id.serialNo);
familyName =(TextView) view.findViewById(R.id.familyName);
relation =(TextView) view.findViewById(R.id.relation);
parentLinear = (LinearLayout) view.findViewById(R.id.parentLinear);
}
}
public FamilyAddapter(Context mainActivityUser, ArrayList<Family> moviesList, OnItemClick onItemClick) {
this.FamilyList = moviesList;
this.mainActivityUser = mainActivityUser;
this.onItemClick = onItemClick;
}
public void notifyData(ArrayList<Family> myList) {
Log.d("notifyData ", myList.size() + "");
this.FamilyList = myList;
notifyDataSetChanged();
}
public FamilyAddapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.family_row, parent, false);
return new FamilyAddapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(FamilyAddapter.MyViewHolder holder, final int position) {
Family bean = FamilyList.get(position);
holder.serialNo.setText(bean.serialNo);
holder.familyName.setText(bean.familyName);
holder.relation.setText(bean.relation);
if (position % 2 == 0) {
holder.parentLinear.setBackgroundColor(mainActivityUser.getResources().getColor(R.color.viewBg));
} else {
holder.parentLinear.setBackgroundColor(mainActivityUser.getResources().getColor(R.color.white));
}
holder.parentLinear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClick.itemFamilyClick(position);
}
});
}
public int getItemCount(){
return FamilyList.size();
}
}
|
package bean.users;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="roles")
public class RolesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "role_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name="role")
private String role;
@OneToMany(mappedBy = "roles", fetch = FetchType.EAGER)
private Set<UserBean> users;
public RolesBean() {
}
public Set<UserBean> getUsers() {
return users;
}
public void setUsers(Set<UserBean> users) {
this.users = users;
}
/*public RolesBean(String role) {
super();
this.role = role;
}
public RolesBean(int id, String role) {
super();
this.id = id;
this.role = role;
}
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
package com.dian.diabetes.dto;
public class ReportDto {
public String name;
public String value;
}
|
package com.croquis.crary.restclient.gson;
import com.croquis.crary.util.CraryIso9601DateFormat;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class CraryDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final DateFormat mFormats[];
public CraryDateTypeAdapter() {
mFormats = new DateFormat[2];
mFormats[0] = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS", Locale.US);
mFormats[0].setTimeZone(TimeZone.getTimeZone("GMT"));
mFormats[1] = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);
mFormats[1].setTimeZone(TimeZone.getTimeZone("GMT"));
}
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(CraryIso9601DateFormat.format(src));
}
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!(json instanceof JsonPrimitive)) {
throw new JsonParseException("The date should be a string value");
}
Date date = parseDate(json.getAsString());
if (typeOfT == Date.class) {
return date;
} else if (typeOfT == Timestamp.class) {
return new Timestamp(date.getTime());
} else if (typeOfT == java.sql.Date.class) {
return new java.sql.Date(date.getTime());
} else {
throw new IllegalArgumentException(getClass() + " cannot deserialize to " + typeOfT);
}
}
private Date parseDate(String str) {
Date date = CraryIso9601DateFormat.parse(str);
if (date != null) {
return date;
}
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < mFormats.length; i++) {
synchronized (mFormats[i]) {
try {
return mFormats[i].parse(str);
} catch (ParseException ignored) {
}
}
}
throw new JsonSyntaxException(str);
}
}
|
package person;
import java.util.ArrayList;
import bomb.Bomb;
import types.AbstractItem;
import weapon.Weapon;
public class Person {
public Weapon m_Weapon;
public Bomb m_Bomb;
public void create(AbstractItem ai) {
ArrayList<Person> list = new ArrayList<Person>();
Weapon w;
m_Weapon = ai.createWeapon();
m_Bomb = ai.createBomb();
list.addAll(w.drawWeapon());
}
}
|
package decorator.developer;
/**
* Общий интерфейс
* */
public interface Developer {
String makeJob();
}
|
package com.github.chanming2015.springcloud.eureka.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
*
* Description:
* Create Date:2018年6月1日
* @author XuMaoSen
* Version:1.0.0
*/
@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication
{
public static void main(String[] args) throws Exception
{
SpringApplication.run(EurekaClientApplication.class, args);
}
}
|
package com.test;
import com.zaiou.common.support.CustomRestTemplate;
import com.zaiou.web.WebApplication;
import lombok.extern.slf4j.Slf4j;
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.test.context.junit4.SpringRunner;
/**
* @Description: 单例/多例测试
* @auther: LB 2019/1/17 16:42
* @modify: LB 2019/1/17 16:42
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class)
@Slf4j
public class ScopeTest {
@Autowired
protected CustomRestTemplate restfulClient;
@Test
public void test(){
restfulClient.post("web/test/scopeTest","",String.class);
}
}
|
package crescendo.base.profile;
import java.io.Serializable;
import java.util.ArrayList;
/**
* SongPreference
*
* This storage class represents the preferences associated with a song.
*
* Features include:
*
* filePath to the song numTracks of the song activeTrack for the user to play
*
* trackVolume for each track individually trackInstrument for each track
* individually
*
* @author groszc
*
*/
public class SongPreference implements Serializable {
private static final long serialVersionUID = 1L;
// The absolute path to the song file
private String filePath;
// The number of tracks this song has
private int numTracks;
// The default active track
private int activeTrack;
// The volume of each track
private ArrayList<Integer> trackVolume;
// The instrument for each track
private ArrayList<Integer> trackInstrument;
// The top 10 scores for this song
private ArrayList<Integer> songScores;
String name;
String creator;
/**
* SongPreference
*
* Default constructor, creates default values for instrument that should be
* overridden immediately after creation.
*
* @param filePath
* - The absolute path to the song file
* @param numTracks
* - The number of tracks this song has
* @param activeTrack
* - The default active track (Above 0 unless no tracks need to
* be played by the user)
*/
public SongPreference(String filePath, int numTracks, int activeTrack) {
// set filePath, numTracks, and activeTrack
this.filePath = filePath;
this.numTracks = numTracks;
this.activeTrack = activeTrack;
trackVolume = new ArrayList<Integer>();
trackInstrument = new ArrayList<Integer>();
// create defaults for volume and instrument
for (int i = 0; i < numTracks; i++) {
// default volume
trackVolume.add(50);
// this one should be overridden after creation
trackInstrument.add(50);
}
songScores = new ArrayList<Integer>();
name = "";
creator = "";
}
/** Returns the scores of the song **/
public ArrayList<Integer> getScores() {
return songScores;
}
/** Returns the absolute file path of the song **/
public String getFilePath() {
return filePath;
}
/** Sets the absolute file path of the song **/
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/** Returns the active track of the song **/
public int getActiveTrack() {
return activeTrack;
}
/** Sets the active track of the song **/
public void setActiveTrack(int activeTrack) {
this.activeTrack = activeTrack;
}
/** Returns the number of tracks in the song **/
public int getNumTracks() {
return numTracks;
}
/** Sets the number of tracks in the song **/
public void setNumTracks(int numTracks) {
this.numTracks = numTracks;
}
/** Returns the volume of a specified track **/
public int getTrackVolume(int track) {
return trackVolume.get(track);
}
/** Sets the volume of a specified track **/
public void setTrackVolume(int track, int volume) {
trackVolume.set(track, volume);
}
/** Returns the instrument of a specified track **/
public int getTrackInstrument(int track) {
return trackInstrument.get(track);
}
/** Sets the instrument of a specified track **/
public void setTrackInstrument(int track, int instrument) {
trackVolume.set(track, instrument);
}
/** Sets the name of the song **/
public void setSongName(String name) {
this.name = name;
}
/** returns the name of the song **/
public String getSongName() {
return name;
}
/** sets the artist for the song **/
public void setCreator(String creator) {
this.creator = creator;
}
/** returns the artist of the song **/
public String getCreator() {
return creator;
}
}
|
package com.amazon.bookstore;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepo extends PagingAndSortingRepository<User, Long>, JpaSpecificationExecutor<User> {
User findById(int id);
User findByName(String name);
}
|
package com.example.dam.recetario.receta;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.dam.recetario.Ayudante;
import com.example.dam.recetario.MainActivity;
import com.example.dam.recetario.Recetario;
import java.util.ArrayList;
import java.util.List;
public class GestorReceta {
private Ayudante adb;
private SQLiteDatabase db;
public GestorReceta(Context c){
adb = new Ayudante(c);
}
public void openWrite(){
db = adb.getWritableDatabase();
}
public void openRead(){
db = adb.getReadableDatabase();
}
public void close(){
adb.close();
}
public long insert(Receta r){
ContentValues cv = new ContentValues();
cv.put(Recetario.TablaReceta.NOMBRE, r.getNombre());
cv.put(Recetario.TablaReceta.FOTO, r.getFoto());
cv.put(Recetario.TablaReceta.INSTRUCCIONES, r.getInstrucciones());
return db.insert(Recetario.TablaReceta.TABLA, null, cv);
}
public void delete(Receta r){
String condicion = Recetario.TablaReceta._ID + " = ?";
String[] argumentos = { r.getId() + "" };
db.delete(Recetario.TablaReceta.TABLA, condicion, argumentos);
}
public void update(Receta r){
ContentValues cv = new ContentValues();
cv.put(Recetario.TablaReceta.NOMBRE, r.getNombre());
cv.put(Recetario.TablaReceta.FOTO, r.getFoto());
cv.put(Recetario.TablaReceta.INSTRUCCIONES, r.getInstrucciones());
String condicion = Recetario.TablaReceta._ID + " = ?";
String[] argumentos = { r.getId() + "" };
db.update(Recetario.TablaReceta.TABLA, cv, condicion, argumentos);
}
public Receta getRow(Cursor c) {
Receta r = new Receta();
r.setId(c.getLong(c.getColumnIndex(Recetario.TablaReceta._ID)));
r.setNombre(c.getString(c.getColumnIndex(Recetario.TablaReceta.NOMBRE)));
r.setFoto(c.getString(c.getColumnIndex(Recetario.TablaReceta.FOTO)));
r.setInstrucciones(c.getString(c.getColumnIndex(Recetario.TablaReceta.INSTRUCCIONES)));
return r;
}
public Cursor getCursor() {
return db.query(Recetario.TablaReceta.TABLA, null, null, null, null, null, null);
}
public List<Receta> selectRecetas(){
List<Receta> all = new ArrayList<Receta>();
Cursor cursor = getCursor();
cursor.moveToFirst();
Receta receta;
while (!cursor.isAfterLast()) {
receta = getRow(cursor);
all.add(receta);
cursor.moveToNext();
}
cursor.close();
return all;
}
}
|
package com.cs.player;
import com.cs.payment.Money;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
/**
* @author Omid Alaepour
*/
@Repository
public interface WalletRepository extends JpaRepository<Wallet, Long>, QueryDslPredicateExecutor<Wallet> {
@Modifying
@Query("update Wallet w set w.accumulatedMonthlyTurnover = ?1 where w.accumulatedMoneyTurnover > ?1")
Integer setAccumulatedMontyTurnoverToZero(final Money zero);
@Modifying
@Query("update Wallet w set w.accumulatedDailyBet = ?1, w.accumulatedDailyLoss = ?1 where w.accumulatedDailyBet > ?1 or w.accumulatedDailyLoss > ?1")
Integer resetAccumulateDailyBetsAndLosses(final Money zero);
@Modifying
@Query("update Wallet w set w.accumulatedWeeklyBet = ?1, w.accumulatedWeeklyLoss = ?1 where w.accumulatedWeeklyBet > ?1 or w.accumulatedWeeklyLoss > ?1")
Integer resetAccumulateWeeklyBetsAndLosses(final Money zero);
@Modifying
@Query("update Wallet w set w.accumulatedMonthlyBet = ?1, w.accumulatedMonthlyLoss = ?1 where w.accumulatedMonthlyBet > ?1 or w.accumulatedMonthlyLoss > ?1")
Integer resetAccumulateMonthlyBetsAndLosses(final Money zero);
}
|
package com.demo.common.emun;
public enum UserType {
NORMAL_USER(1), FORUM_ADMIN(2), SUPER_ADMIN(99);
private int i;
UserType(int type) {
i = type;
}
public int getValue() {
return i;
}
public static void main(String[] args) {
System.out.println(UserType.FORUM_ADMIN.getValue());
}
}
|
package mf.fssq.mf_part_one.entity;
import java.util.Calendar;
// 懒汉式创建当前时间对象
public class SingleCurrentTime {
// 年月日
private int year;
private int month;
private int date;
// 时分秒
private int hour;
private int minute;
private int second;
// 星期
private String week;
// 获取Calendar类实例对象
private static Calendar mCalendar=Calendar.getInstance();
// 私有化构造函数
private SingleCurrentTime() {
hour=mCalendar.get(Calendar.HOUR_OF_DAY);
minute=mCalendar.get(Calendar.MINUTE);
second=mCalendar.get(Calendar.SECOND);
year=mCalendar.get(Calendar.YEAR);
month=mCalendar.get(Calendar.MONTH)+1;
date=mCalendar.get(Calendar.DAY_OF_MONTH);
week=BackWeek(mCalendar.get(Calendar.DAY_OF_WEEK));
}
// 创建唯一实例对象,使用一个私有静态成员变量保存
private static SingleCurrentTime singleCurrentTime = null;
// 对外提供一个公开成员变量获取方法
public static synchronized SingleCurrentTime getInstance() {
if (singleCurrentTime == null) {
singleCurrentTime = new SingleCurrentTime();
}
return singleCurrentTime;
}
public int getYear(){
return year;
}
public int getMonth() {
return month;
}
public int getDate() {
return date;
}
public String getWeek() {
return week;
}
//获取时间
public String getTime() {
return hour+":"+minute+":"+second;
}
//旧格式的日期
public String oldFormatDate(){
return year+"."+month+"."+date;
}
//新格式的日期
public String newFormatDate(){
String newFormatMonth;
newFormatMonth=BackMonth(month);
return date+"."+newFormatMonth+"."+year;
}
//月份转换int->String
public String BackMonth(int i){
String str=null;
switch (i){
case 1:str= "January";break;
case 2:str= "February";break;
case 3:str= "March";break;
case 4:str= "April";break;
case 5:str= "May";break;
case 6:str= "June";break;
case 7:str= "July";break;
case 8:str= "August";break;
case 9:str= "September";break;
case 10:str= "October";break;
case 11:str= "November";break;
case 12:str= "December";break;
}
return str;
}
//星期转换int->String
private String BackWeek(int i){
String str=null;
switch (i){
case 1:str= "Sunday";break;
case 2:str= "Monday";break;
case 3:str= "Tuesday";break;
case 4:str= "Wednesday";break;
case 5:str= "Thursday";break;
case 6:str= "Friday";break;
case 7:str= "saturday";break;
}
return str;
}
public void saveToLatelyTime(){
LatelyTime.getInstance().setLately_year(year);
LatelyTime.getInstance().setLately_month(month);
LatelyTime.getInstance().setLately_date(date);
LatelyTime.getInstance().setLately_week(week);
}
public int transmonth(String month) {
int x=0;
switch (month){
case "January": x= 1;break;
case "February":x= 2;break;
case "March":x= 3;break;
case "April":x= 4;break;
case "May":x= 5;break;
case "June":x= 6;break;
case "July":x= 7;break;
case "August":x= 8;break;
case "September":x= 9;break;
case "October":x= 10;break;
case "November":x= 11;break;
case "December":x= 12;break;
}
return x;
}
}
|
package GUI;
import java.io.IOException;
import javax.swing.JFrame;
import jeu.Jeu;
/**
* Fenêtre affichée
* @author Dorian Opsommer, Rémy Voet
*
*/
public class Fenetre extends JFrame{
private Menu men;
public Fenetre(int tailleX, int tailleY){
this.setTitle("Casse-Brick");
this.setResizable(false);
this.setSize(tailleX, tailleY);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.affichageMenu();
}
public void affichageMenu(){
men = new Menu(this);
this.setContentPane(men);
}
public void ecranFin(int scoreJ1, int scoreJ2){
this.setContentPane(new PanelFin(this, scoreJ1, scoreJ2));
this.revalidate();
}
public void lancement(boolean isHote, String ipAutre){
this.validate();
Jeu jeuEnCours = new Jeu();
try {
jeuEnCours.lancementJeu(this, isHote, ipAutre);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.codecool.stampcollection.exception;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
import java.net.URI;
public class ItemNotFoundException extends AbstractThrowableProblem {
public ItemNotFoundException(Long id) {
super(
URI.create("/api/denomination/item-not-found"),
"not found",
Status.NOT_FOUND,
String.format("Item with id %d not found", id)
);
}
}
|
/*
* Copyright (C) 2012~2016 dinstone<dinstone@163.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.dinstone.beanstalkc.internal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.dinstone.beanstalkc.BeanstalkClient;
import com.dinstone.beanstalkc.Configuration;
import com.dinstone.beanstalkc.Job;
import com.dinstone.beanstalkc.internal.operation.AbstractOperation;
import com.dinstone.beanstalkc.internal.operation.BuryOperation;
import com.dinstone.beanstalkc.internal.operation.DeleteOperation;
import com.dinstone.beanstalkc.internal.operation.IgnoreOperation;
import com.dinstone.beanstalkc.internal.operation.KickOperation;
import com.dinstone.beanstalkc.internal.operation.ListTubeOperation;
import com.dinstone.beanstalkc.internal.operation.PeekOperation;
import com.dinstone.beanstalkc.internal.operation.PeekOperation.Type;
import com.dinstone.beanstalkc.internal.operation.PutOperation;
import com.dinstone.beanstalkc.internal.operation.QuitOperation;
import com.dinstone.beanstalkc.internal.operation.ReleaseOperation;
import com.dinstone.beanstalkc.internal.operation.ReserveOperation;
import com.dinstone.beanstalkc.internal.operation.StatsOperation;
import com.dinstone.beanstalkc.internal.operation.TouchOperation;
import com.dinstone.beanstalkc.internal.operation.UseOperation;
import com.dinstone.beanstalkc.internal.operation.WatchOperation;
/**
* This is the client implementation of the beanstalkd protocol.
*
* @author guojf
* @version 1.0.0.2013-4-11
*/
public class DefaultBeanstalkClient implements BeanstalkClient {
private Connection connection;
private long operationTimeout;
private Configuration config;
/**
* @param config
*/
public DefaultBeanstalkClient(Configuration config) {
this(config, null);
}
/**
* @param config
* @param initer
*/
public DefaultBeanstalkClient(Configuration config, ConnectionInitializer initer) {
if (config == null) {
throw new IllegalArgumentException("config is null");
}
this.config = config;
this.operationTimeout = config.getOperationTimeout();
this.connection = ConnectionFactory.getInstance().createConnection(config, initer);
}
// ************************************************************************
// Produce methods
// ************************************************************************
/**
* The "use" command is for producers. Subsequent put commands will put jobs
* into the tube specified by this command. If no use command has been issued,
* jobs will be put into the tube named "default".
*
* @param tube is a name at most 200 bytes. It specifies the tube to use. If the
* tube does not exist, it will be created.
* @return
*/
@Override
public boolean useTube(String tube) {
UseOperation operation = new UseOperation(tube);
return getBoolean(connection.handle(operation));
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.JobProducer#putJob(int, int, int, byte[])
*/
@Override
public long putJob(int priority, int delay, int ttr, byte[] data) {
int maxLength = config.getJobMaxSize();
if (data != null && data.length > maxLength) {
throw new IllegalArgumentException("data is too long than " + maxLength);
}
AbstractOperation<Long> operation = new PutOperation(priority, delay, ttr, data);
OperationFuture<Long> future = connection.handle(operation);
try {
return future.get(operationTimeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
// ************************************************************************
// Consumer methods
// ************************************************************************
@Override
public boolean ignoreTube(String tube) {
IgnoreOperation operation = new IgnoreOperation(tube);
return getBoolean(connection.handle(operation));
}
/**
* The "watch" command adds the named tube to the watch list for the current
* connection. A reserve command will take a job from any of the tubes in the
* watch list. For each new connection, the watch list initially consists of one
* tube, named "default".
*
* @param tube
* @return
*/
@Override
public boolean watchTube(String tube) {
WatchOperation operation = new WatchOperation(tube);
return getBoolean(connection.handle(operation));
}
@Override
public boolean deleteJob(long id) {
DeleteOperation operation = new DeleteOperation(id);
return getBoolean(connection.handle(operation));
}
/**
* The "touch" command allows a worker to request more time to work on a job.
* This is useful for jobs that potentially take a long time, but you still want
* the benefits of a TTR pulling a job away from an unresponsive worker. A
* worker may periodically tell the server that it's still alive and processing
* a job (e.g. it may do this on DEADLINE_SOON).
*
* @param id is the ID of a job reserved by the current connection.
* @return
*/
@Override
public boolean touchJob(long id) {
TouchOperation operation = new TouchOperation(id);
return getBoolean(connection.handle(operation));
}
@Override
public Job reserveJob(long timeout) {
ReserveOperation operation = new ReserveOperation(timeout);
OperationFuture<Job> future = connection.handle(operation);
try {
return future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
@Override
public boolean releaseJob(long id, int priority, int delay) {
ReleaseOperation operation = new ReleaseOperation(id, priority, delay);
return getBoolean(connection.handle(operation));
}
@Override
public boolean buryJob(long id, int priority) {
BuryOperation operation = new BuryOperation(id, priority);
return getBoolean(connection.handle(operation));
}
@Override
public void close() {
connection.close();
ConnectionFactory.getInstance().releaseConnection(config);
}
public void quit() {
QuitOperation operation = new QuitOperation();
getBoolean(connection.handle(operation));
}
private boolean getBoolean(OperationFuture<Boolean> future) {
try {
return future.get(operationTimeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
// ************************************************************************
// Other methods
// ************************************************************************
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#kick(long)
*/
@Override
public long kick(long bound) {
KickOperation operation = new KickOperation(bound);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#peek(long)
*/
@Override
public Job peek(long jobId) {
PeekOperation operation = new PeekOperation(jobId);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#peekReady()
*/
@Override
public Job peekReady() {
PeekOperation operation = new PeekOperation(Type.ready);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#peekDelayed()
*/
@Override
public Job peekDelayed() {
PeekOperation operation = new PeekOperation(Type.delayed);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#peekBuried()
*/
@Override
public Job peekBuried() {
PeekOperation operation = new PeekOperation(PeekOperation.Type.buried);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#statsJob(long)
*/
@Override
public Map<String, String> statsJob(long jobId) {
StatsOperation operation = new StatsOperation(jobId);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#statsTube(java.lang.String)
*/
@Override
public Map<String, String> statsTube(String tubeName) {
StatsOperation operation = new StatsOperation(tubeName);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#stats()
*/
@Override
public Map<String, String> stats() {
StatsOperation operation = new StatsOperation();
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#listTubes()
*/
@Override
public List<String> listTubes() {
ListTubeOperation operation = new ListTubeOperation(ListTubeOperation.Type.all);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#listTubeUsed()
*/
@Override
public String listTubeUsed() {
ListTubeOperation operation = new ListTubeOperation(ListTubeOperation.Type.used);
try {
return connection.handle(operation).get().get(0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* {@inheritDoc}
*
* @see com.dinstone.beanstalkc.BeanstalkClient#listTubeWatched()
*/
@Override
public List<String> listTubeWatched() {
ListTubeOperation operation = new ListTubeOperation(ListTubeOperation.Type.watched);
try {
return connection.handle(operation).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
|
package it.bibliotecaweb.servlet.libro;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.bibliotecaweb.model.Libro;
import it.bibliotecaweb.service.MyServiceFactory;
/**
* Servlet implementation class ConfermaDeleteLibroServlet
*/
@WebServlet("/ConfermaDeleteLibroServlet")
public class ConfermaDeleteLibroServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ConfermaDeleteLibroServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if (id != null && !id.equals("")) {
Libro libro = new Libro();
libro.setId(Integer.parseInt(id));
try {
MyServiceFactory.getLibroServiceInstance().delete(libro);
request.setAttribute("effettuato", "Eliminazione effettuata con successo!");
request.getRequestDispatcher("ListaLibriServlet").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
request.setAttribute("errore", "Nessun libro selezionato!");
request.getRequestDispatcher("ListaLibriServlet").forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.example.armstest.controller;
import com.example.armstest.Demand;
import com.example.armstest.StatusDemand;
import com.example.armstest.data.DemandRepo;
import com.example.armstest.data.JpaDemandRepo;
import com.example.armstest.data.StatusDemandRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("/demandForm")
public class DemandController {
private DemandRepo demandRepo;
private StatusDemandRepo statusDemandRepo;
private JpaDemandRepo jpaDemandRepo;
@Autowired
private DemandController(DemandRepo demandRepo,StatusDemandRepo statusDemandRepo) {
this.demandRepo = demandRepo;
this.statusDemandRepo = statusDemandRepo;
}
@GetMapping
public String demandForms(Model model){
model.addAttribute("demand",new Demand());
return "demandForm";
}
@ModelAttribute(name = "statusDemands")
public StatusDemand statusDemands(){
return new StatusDemand();
}
@PostMapping
public String sendMessage(@Valid Demand demand, @ModelAttribute StatusDemand statusDemands){
demand.setAccepted("принята");
Demand f = demandRepo.save(demand);
statusDemands.setDemand_id(f.getId());
statusDemands.setDemand_list_id(f.getId());
log.info("TESTING " + statusDemands);
statusDemandRepo.save(statusDemands);
return "redirect:/index";
}
}
|
package com.example.firstprogram.myAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.firstprogram.R;
import java.util.List;
import java.util.Map;
public class mymyAdapter extends BaseAdapter{
private Context context;
private List<Map<String, Object>> listitem;
private LayoutInflater listContainer;
public mymyAdapter(Context context, List<Map<String, Object>> listitem){
this.context = context;
this.listitem = listitem;
this.listContainer = LayoutInflater.from(context);
}
public final class ListItemView{
public ImageView imageView;
public TextView textView;
public Button assess;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListItemView listItemView = null;
if (convertView == null) {
listItemView = new ListItemView();
convertView = listContainer.inflate(R.layout.sos_me_list_item,null);
listItemView.imageView = (ImageView) convertView.findViewById(R.id.sos_me_list_item_imageview);
listItemView.textView = (TextView) convertView.findViewById(R.id.sos_me_list_item_textview);
listItemView.assess = (Button) convertView.findViewById(R.id.sos_me_list_item_button);
convertView.setTag(listItemView);
}else {
listItemView = (ListItemView) convertView.getTag();
}
listItemView.imageView.setBackgroundResource((Integer) listitem.get(position).get("image"));
listItemView.textView.setText(listitem.get(position).get("name").toString());
return convertView;
}
@Override
public int getCount() {
return listitem.size();
}
@Override
public Object getItem(int position) {
return listitem.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
|
package com.example.login.exception;
import org.springframework.security.core.AuthenticationException;
public class NotEnoughPermissionException extends AuthenticationException {
public NotEnoughPermissionException(String msg) {
super(msg);
}
}
|
package com.atguigu.exer;
/*
* 在前面定义的Person类中添加构造器,利用构造器设置所有人的age属性初始值都为18。
修改上题中类和构造器,增加name属性,使得每次创建Person对象的同时初始化对象的age属性值和name属性值。
*/
class Person{
int age;
String name;
//构造器 - 创建对象时会调用构造器
public Person(){
age = 18;
}
public Person(String n,int a){
name = n;
age = a;
}
public void info(){
System.out.println(name + " " + age);
}
}
public class PersonTest {
public static void main(String[] args) {
Person person = new Person();
person.info();
System.out.println("---------------------------");
Person p = new Person("志玲", 18);
p.info();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.