text
stringlengths 10
2.72M
|
|---|
package com.example.simpletodo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends AppCompatActivity {
EditText updateItem;
Button buttonSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
updateItem = findViewById(R.id.updateItem);
buttonSave = findViewById(R.id.buttonSave);
getSupportActionBar().setTitle("Edit Item");
updateItem.setText(getIntent().getStringExtra(MainActivity.KEY_ITEM_TEXT));
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = updateItem.getText().toString();
Intent mainIntent = new Intent();
mainIntent.putExtra(MainActivity.KEY_ITEM_TEXT, result);
mainIntent.putExtra(MainActivity.KEY_ITEM_POSITION, getIntent().getExtras().getInt(MainActivity.KEY_ITEM_POSITION));
setResult(RESULT_OK, mainIntent);
finish();
}
});
}
}
|
import java.util.Scanner;
public class Piaskownica {
public static void main(String[] args) {
Piaskownica piaskownica = new Piaskownica();
// piaskownica.pd();
Scanner in = new Scanner(System.in);
for (int i = 0 ; i <3; i++){
int linczba = in.nextInt();
}
}
public int [] pd() {
Scanner in = new Scanner(System.in);
int ileRazy = in.nextInt();
int liczba=0;
int licznik;
int tab[] = new int[ileRazy];
for ( licznik = 0 ; licznik<ileRazy;licznik++){
liczba = in.nextInt();
int tajne = liczba*1000;
tab[licznik]=tajne;
}
int b = 10;
for ( licznik = 0 ; licznik<ileRazy;licznik++){
System.out.println(tab[licznik]);
}
return tab ;
}
public int met(int d){
return d/2;
}
}
|
package com.ai.slp.order.api.orderDetailList.param;
public class OrderDetailListRequest {
/**
* 业务订单号
*/
public long orderId;
/**
* 父Id
*/
public long parentOrderId;
/**
* 订单类型
*/
public String orderType;
/**
* 用户Id
*/
public String userId;
/**
* 账户Id
*/
public String acctId;
/**
* 状态(已支付、未支付等)
*/
public String state;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public long getParentOrderId() {
return parentOrderId;
}
public void setParentOrderId(long parentOrderId) {
this.parentOrderId = parentOrderId;
}
}
|
package tc.fab.pdf.signer;
import java.io.File;
public interface IPDFSigner {
void sign(File file) throws Exception;
}
|
package com.designPattern.behavioral.strategy;
public class CreditCardStrategy implements PaymentStrategy {
private String cardHolderName;
private String cardNo;
private int cvvNo;
private String expiryDate;
public CreditCardStrategy(String cardHolderName, String cardNo, int cvvNo, String expiryDate) {
this.cardHolderName = cardHolderName;
this.cardNo = cardNo;
this.cvvNo = cvvNo;
this.expiryDate = expiryDate;
}
@Override
public void pay(int amount) {
System.out.println("Rs - " + amount + " Paid using Debit/Credit Card.");
}
}
|
package com.dzh.foodrs.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dzh.foodrs.po.UserInfo;
import com.dzh.foodrs.repository.UserInfoRepository;
@Service
public class UserInfoService {
@Autowired
private UserInfoRepository userInfoRepository;
public UserInfo findOneUserInfo(String id){
return userInfoRepository.findOneById(id);
}
public UserInfo saveUserInfo(UserInfo userInfo){
return userInfoRepository.save(userInfo);
}
}
|
package com.example.mayur.dairyapplication.Owner;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mayur.dairyapplication.R;
import com.example.mayur.dairyapplication.RestAPI;
import com.example.mayur.dairyapplication.SharePreferances.AlertDialogManager;
import com.example.mayur.dairyapplication.SharePreferances.SessionManager;
import com.example.mayur.dairyapplication.UpdateMilkDetails;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Fragment_MilkPurchase extends AppCompatActivity {
TextView tv_date;
EditText et_fid,et_quantity,et_fat,et_deg,et_snf,et_rate,et_total;
Button btn_save;
SessionManager session;
AlertDialogManager alert = new AlertDialogManager();
Calendar cal = Calendar.getInstance();
final String today = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_fragment__milk_purchase);
session = new SessionManager(getApplicationContext());
tv_date = (TextView) findViewById(R.id.datepicker);
tv_date.setText(today);
et_fid = (EditText) findViewById(R.id.et_Fid);
et_quantity = (EditText) findViewById(R.id.et_quantity);
et_snf = (EditText) findViewById(R.id.et_snf);
et_deg = (EditText) findViewById(R.id.et_deg);
et_rate = (EditText) findViewById(R.id.et_rate);
et_total = (EditText) findViewById(R.id.et_total);
et_fat = (EditText) findViewById(R.id.et_fat);
btn_save = (Button) findViewById(R.id.btn_save);
et_deg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
try {
float deg = Float.valueOf(et_deg.getText().toString());
float fat = Float.valueOf(et_fat.getText().toString());
double snf = (deg / 4) + 0.21 * fat + 0.36;
String str = (snf + "").substring(1, 4);
// et_snf.setText("" + snf);
et_snf.setText(new DecimalFormat("##.#").format(snf));
et_rate.setText(getRate(fat,snf));
et_total.setText("" + (Float.parseFloat(et_quantity.getText().toString()) * Float.parseFloat(et_rate.getText().toString())));
}
catch (Exception e)
{
}
}
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//EditText et_fid,et_quantity,et_fat,et_deg,et_snf,et_rate,et_total;
if (et_fid.getText().toString().length() == 0) {
et_fid.setError("Please Enter Farmer ID");
} else if (et_quantity.getText().toString().length() == 0) {
et_quantity.setError("Please Enter Quantity ");
}else if(et_fat.getText().toString().length()==0)
{
et_fat.setError("Please Enter Fat value");
}else if(et_deg.getText().toString().length()==0)
{
et_deg.setError("Please Enter Degree value");
}else {
Date date1= null;
try {
date1 = new SimpleDateFormat("yyyy-mm-dd").parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
PurchaseMilk_Cons purchaseMilk_cons = new PurchaseMilk_Cons(session.getID(), Integer.parseInt(et_fid.getText().toString()), date1, Float.parseFloat(et_quantity.getText().toString()),
Float.parseFloat(et_fat.getText().toString()), Float.parseFloat(et_deg.getText().toString()), Float.parseFloat(et_snf.getText().toString()),
Float.parseFloat(et_rate.getText().toString()), Float.parseFloat(et_total.getText().toString()));
new AsyncPurchase().execute(purchaseMilk_cons);
}
}
});
}
public String getRate(float fat, double snf) {
snf = Math.round(snf * 10);
snf = snf/10;
float rate=session.getMilkRate();
String cal_rate=""+rate;
for(double i=2;i<=fat;i= (i+0.1))
{
i = Math.round(i * 10);
i = i/10;
float rate1 = rate;
for(double j=5;j<=snf;j= (j+0.1))
{
j = Math.round(j * 10);
j = j/10;
rate1= (float) (rate1+0.20);
rate1 = Math.round(rate1 * 100);
rate1 = rate1/100;
cal_rate=rate1+"";
}
rate= (float) (rate+0.30);
rate = Math.round(rate * 100);
rate = rate/100;
}
return cal_rate;
}
private class AsyncPurchase extends AsyncTask<PurchaseMilk_Cons,Void,Void> {
String result;
JSONObject jsonObject=null;
RestAPI api=new RestAPI();
ProgressDialog progress;
@Override
protected void onPreExecute() {
progress= new ProgressDialog(Fragment_MilkPurchase.this);
progress.setIndeterminate(true);
progress.setMessage("Inserting Records...");
progress.show();
}
@Override
protected Void doInBackground(PurchaseMilk_Cons... params) {
RestAPI api=new RestAPI();
try
{
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(today);
jsonObject=api.MilkPurchase(params[0].getOid(),params[0].getFid(),date1,params[0].getQuantity(),params[0].getFat(),params[0].getDeg(),params[0].getSnf(),params[0].getRate(),params[0].getTotal());
result=jsonObject.getString("Value");
}
catch (Exception e)
{
Log.d("Purchase Milk",e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progress.hide();
if(result.contains("Already exists")==true)
{
alert.showAlertDialog1(Fragment_MilkPurchase.this,"Failed..!","Milk Already Collected....!",false);
et_fid.setText("");
et_quantity.setText("");
et_snf.setText("");
et_deg.setText("");
et_rate.setText("");
et_fat.setText("");
et_total.setText("");
}
else {
if (result.contains("success") == true) {
Toast.makeText(getApplicationContext(), "Milk Collected", Toast.LENGTH_LONG).show();
et_fid.setText("");
et_quantity.setText("");
et_snf.setText("");
et_deg.setText("");
et_rate.setText("");
et_fat.setText("");
et_total.setText("");
} else {
Toast.makeText(getApplicationContext(), " Error Occoured plz try again", Toast.LENGTH_LONG).show();
}
}
}
}
}
|
package game;
import java.util.*;
import _aux.Options;
import board.Board;
import board.Cell;
import card.Card;
import card.CityCard;
import city.City;
import dis.Disease;
import player.Player;
public final class Distance {
public final int UP = 0;
public final int RIGHT = 1;
public final int DOWN = 2;
public final int LEFT = 3;
public static int[] manhattanDistanceTorus(int[] initialPosition, int[] finalPosition, int nRows, int nCols) {
int movH, movV;
// Calculo numero de casillas movimiento horizontal
int hor = initialPosition[1] - finalPosition[1];
if (hor < 0) {
movH = 1;
hor = hor * (-1);
} else
movH = 3;
int finalHor = Math.min(hor, nCols - hor);
// Calculo numero de casillas movimiento vertical
int ver = initialPosition[0] - finalPosition[0];
if (ver < 0) {
movV = 2;
ver = ver * (-1);
} else
movV = 0;
int finalVer = Math.min(ver, nRows - ver);
// Calculo direccion inicial del movimiento
int mov = movH;
if (finalHor == 0) {
if (ver != finalVer) {
movV = (movV + 2) % 4;
}
mov = movV;
} else if (hor != finalHor) {
mov = (movH + 2) % 4;
}
return new int[] { finalHor + finalVer, mov };
}
public static String[] routeChoice(Game game, String name, int[] finalPosition) {
int[] initialPosition = null;
ArrayList<CityCard> hand = null;
for (Player player : game.players.values()) {
if (name.equals(player.alias)) {
hand = (ArrayList<CityCard>) player.getHand().values();
City playerCity = player.getCity();
Cell playerCell = playerCity.getCell();
initialPosition = playerCell.getCoordinates();
}
}
Disease diseaseIAmFollowing = null; // Acceder a las creencias y sacar la enfermedad que estoy persiguiendo
// Calculo el coste de caminar entre los puntos
int[] walkDistance = manhattanDistanceTorus(initialPosition, finalPosition, game.gs.board.n_rows,
game.gs.board.n_cols);
int minimumCostRoute = walkDistance[0];
String nextAction = "" + walkDistance[1];
boolean usoCarta = false;
// Calculo el coste de utilizar un vuelo directo(Puedo volar hasta esa ciudad)
for (Card card : hand) {
Disease diseaseCard = card.getDisease();
if (!diseaseIAmFollowing.equals(diseaseCard)) {
City city = card.getCity();
Cell cell = city.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] position = cell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
int[] totalDistanceDirectFlight = manhattanDistanceTorus(position, finalPosition, game.gs.board.n_rows,
game.gs.board.n_cols);
int aux = totalDistanceDirectFlight[0] + 1;
if (aux < minimumCostRoute) {
minimumCostRoute = aux;
nextAction = 4 + "----" + city.alias;
usoCarta = true;
}
}
}
// Calculo el coste de utilizar un vuelo charter(Puedo volar a cualquier parte
// desde esa ciudad)
for (Card card : hand) {
Disease diseaseCard = card.getDisease();
if (!diseaseIAmFollowing.equals(diseaseCard)) {
City city = card.getCity();
Cell cell = city.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] position = cell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
int[] totalDistanceDirectFlight = manhattanDistanceTorus(initialPosition, position,
game.gs.board.n_rows, game.gs.board.n_cols);
int aux = totalDistanceDirectFlight[0] + 1;
if (aux < minimumCostRoute) {
minimumCostRoute = aux;
if (aux == 1) {
for (City ciudad : game.cities.values()) {
Cell cellCiudad = ciudad.getCell();
int[] posicionesCoordenadas = cellCiudad.getCoordinates();
if (posicionesCoordenadas[0] == position[0] && posicionesCoordenadas[1] == position[1]) {
nextAction = 5 + "----" + ciudad.alias;
}
}
} else {
nextAction = "" + totalDistanceDirectFlight[1];
}
usoCarta = true;
}
}
}
// Calculo el coste de utilizar un air bridge(Puedo volar entre centros de
// investigacion)
ArrayList<City> cityList = new ArrayList<City>();
for (City city : game.cities.values()) { // ESTA FUNCION SE DEBE IMPLEMENTAR EN LA CLASE GAME
if (city.canResearch()) {
cityList.add(city);
}
}
for (City cityF : cityList) {
boolean usoCartaCIF = false;
Cell cellF = cityF.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] positionF = cellF.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
int[] totalDistanceToResearchCentreF = manhattanDistanceTorus(positionF, finalPosition,
game.gs.board.n_rows, game.gs.board.n_cols);
int distanceToResearchCentreF = totalDistanceToResearchCentreF[0];
for (Card card : hand) {
Disease diseaseCard = card.getDisease();
if (!diseaseIAmFollowing.equals(diseaseCard)) {
City city = card.getCity();
Cell cell = city.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] position = cell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
int[] totalDistanceDirectFlight = manhattanDistanceTorus(positionF, position, game.gs.board.n_rows,
game.gs.board.n_cols);
int aux = totalDistanceDirectFlight[0] + 1;
if (aux < distanceToResearchCentreF) {
distanceToResearchCentreF = aux;
usoCartaCIF = true;
}
}
}
for (City cityI : cityList) {
boolean usoCartaCII = false;
if (!cityI.equals(cityF)) {
Cell cellI = cityI.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] positionI = cellI.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
int[] totalDistanceToResearchCentreI = manhattanDistanceTorus(initialPosition, positionI,
game.gs.board.n_rows, game.gs.board.n_cols);
int distanceToResearchCentreI = totalDistanceToResearchCentreI[0];
if (distanceToResearchCentreI == 0) {
// totalDistanceToResearchCentreI[1] = 6 + "----" + cityF.alias;
totalDistanceToResearchCentreI[1] = 6;
break;
}
for (Card card : hand) {
Disease diseaseCard = card.getDisease();
if (!diseaseIAmFollowing.equals(diseaseCard)) {
City city = card.getCity();
Cell cell = city.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] position = cell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE
// CELL
int[] totalDistanceDirectFlight = manhattanDistanceTorus(positionI, position,
game.gs.board.n_rows, game.gs.board.n_cols);
int aux = totalDistanceDirectFlight[0] + 1;
if (aux < distanceToResearchCentreI) {
distanceToResearchCentreI = aux;
// totalDistanceToResearchCentreI[1] = 4 + "----" + city.alias;
totalDistanceToResearchCentreI[1] = 4;
usoCartaCII = true;
}
}
}
int costeTotalVuelosEntreCI = distanceToResearchCentreI + 1 + distanceToResearchCentreF;
if (costeTotalVuelosEntreCI < minimumCostRoute) {
minimumCostRoute = costeTotalVuelosEntreCI;
nextAction = "" + totalDistanceToResearchCentreI[1];
} else if (costeTotalVuelosEntreCI == minimumCostRoute && usoCarta && !usoCartaCII
&& !usoCartaCIF) {
minimumCostRoute = costeTotalVuelosEntreCI;
nextAction = "" + totalDistanceToResearchCentreI[1];
usoCarta = false;
}
}
}
}
return new String[] { "" + minimumCostRoute, nextAction };
}
public static String mostRepeatedDisease(Player agent, Game game) {
Hashtable<Disease, Integer> tableDiseasesCounter = new Hashtable<Disease, Integer>();
ArrayList<Disease> diseases = (ArrayList<Disease>) game.diseases.values();
for (Disease disease : diseases) {
if (disease.getCure()) {
tableDiseasesCounter.put(disease, -1);
} else {
tableDiseasesCounter.put(disease, 0);
}
}
ArrayList<CityCard> hand = (ArrayList<CityCard>) agent.getHand().values();
for (Card card : hand) {
int aux = tableDiseasesCounter.get(card.getDisease());
if (aux != -1)
tableDiseasesCounter.put(card.getDisease(), ++aux);
}
Enumeration e = tableDiseasesCounter.keys();
Disease clave;
int valor;
int maxValue = -1;
Disease maxDisease = null;
while (e.hasMoreElements()) {
clave = (Disease) e.nextElement();
valor = tableDiseasesCounter.get(clave);
if (valor > maxValue) {
maxValue = valor;
maxDisease = clave;
}
}
return maxDisease.alias;
} // AÑADIR COMO CREENCIA PERSEGUIR ESTA ENFERMEDAD AL AGENTE QUE INVOCA LA
// FUNCION
public static void findPlayerToAsk(String name, Game game, ArrayList<CityCard> cartasYaPreguntadas) {
// En la inicializacion del juego es necesario crear un ArrayList vacio llamado
// CartasYaPreguntadas
// Al cambiar de turno el ArrayList CartasYaPreguntadas se vacia de nuevo
Disease desiredDisease = null; // Acceder a las creencias y sacar la enfermedad deseada
Player desiredPlayer = null;
CityCard desiredCard = null;
int minimumDistanceToCard = Integer.MAX_VALUE;
for (Player player : game.players.values()) {
ArrayList<CityCard> hand = (ArrayList<CityCard>) player.getHand().values();
for (CityCard card : hand) {
boolean ignorada = false;
for (CityCard cardYaPreguntada : cartasYaPreguntadas) {
if (cardYaPreguntada.equals(card)) {
ignorada = true;
}
}
if (!ignorada) {
Disease diseaseCard = card.getDisease();
String diseaseAlias = diseaseCard.alias;
if (diseaseAlias.equals(desiredDisease.alias)) {
City cityCard = card.getCity();
Cell cityCell = cityCard.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] cardPosition = cityCell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA
// CLASE CELL
String[] calculusDistanceToCard = routeChoice(game, name, cardPosition);
int distanceToCard = Integer.parseInt(calculusDistanceToCard[0]);
Player possibleDesiredPlayer = player;
if (distanceToCard < minimumDistanceToCard) {
desiredPlayer = possibleDesiredPlayer;
desiredCard = card;
}
}
}
}
}
cartasYaPreguntadas.add(desiredCard);
} // Añadir como creencia que hay que preguntar a desiredPlayer que te facilite la
// carta desiredCard
public static void findCIToReach(Game game, String name) {
int costNearestCI = Integer.MAX_VALUE;
City nearestCI = null;
for (City city : game.cities.values()) { // ESTA FUNCION SE DEBE IMPLEMENTAR EN LA CLASE GAME
if (city.canResearch()) {
Cell cell = city.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
int[] positionCI = cell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
String[] aux = routeChoice(game, name, positionCI);
if (costNearestCI > Integer.parseInt(aux[0])) {
costNearestCI = Integer.parseInt(aux[0]);
nearestCI = city;
}
}
}
// Añadir la creencia de que tengo que ir al centro de investigación nearestCI
}
public static String[] shortRouteChoice(Game game, String name, int[] finalPosition) {
int[] initialPosition = null;
for (Player player : game.players.values()) { // ESTA FUNCION SE DEBE IMPLEMENTAR EN LA CLASE GAME
if (name.equals(player.alias)) {
City playerCity = player.getCity();
Cell playerCell = playerCity.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
initialPosition = playerCell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
break;
}
}
// Calculo el coste de caminar entre los puntos
int[] walkDistance = manhattanDistanceTorus(initialPosition, finalPosition, game.gs.board.n_rows,
game.gs.board.n_cols);
int minimumCostRoute = walkDistance[0];
String nextAction = "" + walkDistance[1];
return new String[] { "" + minimumCostRoute, nextAction };
}
public static void adjacentCube(Game game, String name) {
boolean existAdjacentCube = false;
City initialCity = null;
for (Player player : game.players.values()) { // ESTA FUNCION SE DEBE IMPLEMENTAR EN LA CLASE GAME
if (name.equals(player.alias)) {
initialCity = player.getCity();
break;
}
}
for (City city : initialCity.getNeighbors().values()) {
if (city.getInfections() != null) {
existAdjacentCube = true;
break;
}
}
if (existAdjacentCube) {
// Añadir la creencia de que tengo al menos un cubo en una posición adyacente.
} else {
// Añadir la creencia de que tengo no tengo en una posición adyacente.
}
}
public static void findNearestCube(Game game, String name) {
int nearestCubeDistance = Integer.MAX_VALUE;
City cityNearestCube = null;
for (City city : game.cities.values()) {
if (city.getInfections() != null) {
Cell cell = city.getCell();
int[] finalPosition = cell.getCoordinates();
String[] aux = shortRouteChoice(game, name, finalPosition);
if (Integer.parseInt(aux[0]) < nearestCubeDistance) {
nearestCubeDistance = Integer.parseInt(aux[0]);
cityNearestCube = city;
}
}
}
// Añadir la creencia de que tengo que ir a la ciudad cityNearestCube a limpiar
// cubos.
}
public static void moveToFarObjective(Game game, String name, int[] finalPosition) {
String[] route = routeChoice(game, name, finalPosition);
String nextAction = route[1];
String[] partsAction = nextAction.split("----");
switch (partsAction[0]) {
case "0":
// mover el agente "name" hacia arriba
break;
case "1":
// mover el agente "name" hacia la derecha
break;
case "2":
// mover el agente "name" hacia abajo
break;
case "3":
// mover el agente "name" hacia la izquierda
break;
case "4":
// mover el agente "name" hacia la ciudad con alias partsAction[1] con vuelo
// normal
break;
case "5":
// mover el agente "name" hacia la ciudad con alias partsAction[1] con vuelo
// charter
break;
case "6":
// mover el agente "name" hacia la ciudad con alias partsAction[1] con vuelo
// entre CI
break;
}
}
public static void moveToNearObjective(Game game, String name, int[] finalPosition) {
String[] nextAction = shortRouteChoice(game, name, finalPosition);
switch (nextAction[1]) {
case "0":
// mover el agente "name" hacia arriba
break;
case "1":
// mover el agente "name" hacia la derecha
break;
case "2":
// mover el agente "name" hacia abajo
break;
case "3":
// mover el agente "name" hacia la izquierda
break;
}
}
public void pass(String name) {
// Poner a 0 el número de acciones que me quedan por realizar y pasar el turno.
}
public void smartDiscard(Game game, String name) {
int savedCardsNumber = 0;
Disease diseaseIAmFollowing = null; // Acceder a las creencias y sacar la enfermedad que estoy persiguiendo
int[] initialPosition = null;
ArrayList<CityCard> hand = null;
for (Player player : game.players.values()) {
if (name.equals(player.alias)) {
hand = (ArrayList<CityCard>) player.getHand().values();
City playerCity = player.getCity();
Cell playerCell = playerCity.getCell(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CITY
initialPosition = playerCell.getCoordinates(); // ESTA FUNCION SE TIENE QUE IMPLEMENTAR EN LA CLASE CELL
}
}
for (Card card : hand) {
Disease diseaseCard = card.getDisease();
if (!diseaseIAmFollowing.equals(diseaseCard)) {
hand.remove(card);
++savedCardsNumber;
if (savedCardsNumber == Options.PLAYER_MAX_CARDS) {
for (Card eliminatedCard : hand) {
// Descartar carta eliminatedCard
}
return;
}
}
}
/*
* Errores de compilacion aqui if (/*tengo creencia de quiero ir a una posición
*//*
* ){ //Obtengo las coordenadas de la posición que quiero alcanzar. //En un
* bucle hasta que la posición inicial sea igual a la final: //Llamo a
* routeChoice. //Si routeChoice me da como acción 4-x significa que va a usar
* la carta parteneciente a la posición x para volar /*hand.remove(/* card
* perteneciente a x
*//*
* ); ++savedCardsNumber; if (savedCardsNumber == Options.PLAYER_MAX_CARDS) {
* for (Card eliminatedCard : hand){ // Descartar carta eliminatedCard } return;
* } //Si routeChoice me da como acción 5-x significa que va a usar la carta
* parteneciente a la posición actual para volar hand.remove(/* card
* perteneciente a la posición actual
*//*
* ); ++savedCardsNumber; if (savedCardsNumber == Options.PLAYER_MAX_CARDS{ for
* (Card eliminatedCard : hand){ // Descartar carta eliminatedCard } return; }
* //Actualizo las coordenadas posición actual dependiendo de la acción
* realizada }
*/
for (Card card : hand) {
hand.remove(card);
++savedCardsNumber;
if (savedCardsNumber == Options.PLAYER_MAX_CARDS) {
for (Card eliminatedCard : hand) {
// Descartar carta eliminatedCard
}
return;
}
}
}
public static void main(String[] args) {
}
}
|
package com.example.gayashan.limbcare;
public class ServiceCard {
private String topic;
private String description;
private String type;
private String price;
private byte[] imgservicesA;
public ServiceCard(String topic, String description,byte[] imgservicesA, String type, String price) {
this.type = type;
this.price = price;
this.topic = topic;
this.description = description;
this.imgservicesA=imgservicesA;
}
public String getTopic() {
return topic;
}
public String getPrice() {
return price;
}
public String getType() {
return type;
}
public String getDescription() {
return description;
}
public byte[] getImage() {
return imgservicesA;
}
}
|
package com.suncity.pay.model;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import com.suncity.pay.utils.ToolKit;
import sun.misc.BASE64Encoder;
public class RemitQueryModel {
/**
* 订单号
*/
private String orderNum;
/**
* 代付时间
*/
private String remitDate;
/**
* 商户号
*/
private String merNo;
/**
* 金额
*/
private String amount;
/**
* 编码方式
*/
private String charset;
/**
* 密钥
*/
private String key;
/**
* 版本号
*/
private String version;
public RemitQueryModel(HttpServletRequest request) {
super();
this.orderNum = request.getParameter("orderNum");
this.remitDate = request.getParameter("remitDate");
this.merNo = request.getParameter("merNo");
this.amount = request.getParameter("amount");
this.charset = request.getParameter("charset");
this.key = request.getParameter("key");
this.version = request.getParameter("version");
}
public String getData() throws IOException {
// 订单号、订单发起日期、赏花后、金额(分)
Map<String, String> metaSignMap = new TreeMap<String, String>();
metaSignMap.put("orderNum",orderNum);
metaSignMap.put("remitDate", remitDate);
metaSignMap.put("merNo", merNo);
metaSignMap.put("amount",amount);
// 签名
String metaSignJsonStr = ToolKit.mapToJson(metaSignMap);
String sign = ToolKit.MD5(metaSignJsonStr + key,charset);
System.out.println("sign=" + sign);
metaSignMap.put("sign", sign);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("config.properties");
// 加载属性列表
Properties prop = new Properties();
prop.load(inputStream);
String remitPublicKey = prop.getProperty("REMIT_PUBLIC_KEY");
// 数据公钥加密
byte[] dataStr = ToolKit.encryptByPublicKey(ToolKit.mapToJson(metaSignMap).getBytes(charset),remitPublicKey);
String param = new BASE64Encoder().encode(dataStr);
return URLEncoder.encode(param,charset);
}
public String getParamString() throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("data=").append(getData());
sb.append("&merchNo=").append(merNo);
sb.append("&version=").append(version);
return sb.toString();
}
}
|
package com.myproject.lab1.character;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CharacterRepository extends MongoRepository<Character, String> {
List<Character> findByUserId(String userId);
}
|
package itzshmulik.survivelist.survivelistantiswear.Commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class AdminCommands implements CommandExecutor {
private final JavaPlugin plugin = JavaPlugin.getProvidingPlugin(getClass());
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
Player player = (Player) sender;
List SwearList = plugin.getConfig().getList("SwearList");
String reloadMsg = plugin.getConfig().getString("reloadMsg");
String NoPermMsg = plugin.getConfig().getString("NoPermMsg");
String Prefix = plugin.getConfig().getString("Prefix");
if (args.length >= 1) {
if (args[0].toLowerCase().equals("reload")) {
if (player.hasPermission("sw.reload") || player.hasPermission("sw.admin")) {
plugin.reloadConfig();
player.sendMessage(ChatColor.translateAlternateColorCodes('&', reloadMsg));
}
}
}if(args.length == 1){
if(args[0].toLowerCase().equals("add")){
if(player.hasPermission("sw.add") || player.hasPermission("sw.admin")){
player.sendMessage(ChatColor.translateAlternateColorCodes('&', Prefix + "&6Command usage: /sw add {swear}"));
}else{
player.sendMessage(ChatColor.translateAlternateColorCodes('&', NoPermMsg));
}
}
}if(args.length > 1){
if(args[0].toLowerCase().equals("add")){
if(player.hasPermission("sw.add") || player.hasPermission("sw.admin")){
SwearList.add(args[1]);
plugin.getConfig().set("SwearList", SwearList);
player.sendMessage(ChatColor.translateAlternateColorCodes('&', Prefix + "&6Added swear: " + args[1] + " to the list!"));
plugin.saveConfig();
}else{
player.sendMessage(ChatColor.translateAlternateColorCodes('&', NoPermMsg));
}
}
}
return false;
}
}
|
package testUtil;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import util.DBUtil;
public class DBUtilTest {
@Test
public void test(){
try {
Connection Conn = DBUtil.getSqliteConnection();
String sql = "select count(*) from inventory";
PreparedStatement pstmt = Conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
rs.next();
assertEquals(rs.getInt(0), 4);
Conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.failurehandler;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class HtmlSection {
protected final HtmlSection rootSection;
protected final String id;
protected final String name;
public PrintWriter getWriter() {
return textWriter;
}
protected final PrintWriter pw;
protected final PrintWriter textWriter;
protected boolean closed;
private HtmlSection child;
public HtmlSection(PrintWriter pw) {
this(pw, "", null, null);
}
private HtmlSection(PrintWriter pw, String id, String name, HtmlSection rootSection) {
this.pw = pw;
textWriter = new PrintWriter(new HtmlFilterWriter(pw), true);
this.id = id;
this.name = name;
child = null;
// main
if (rootSection == null) {
this.rootSection = this;
this.pw.println("<html>");
this.pw.println("<style>\n"
+ "div { display:none;}\n"
+ "</style>\n"
+ "\n"
+ "<script>\n"
+ "function show(e) {\n"
+ " while (e != null) {\n"
+ " if (e.tagName == 'DIV') {\n"
+ " e.style.display = 'block';\n"
+ " }\n"
+ " e = e.parentNode;\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "function toggle(id) {\n"
+ " e = document.getElementById(id);\n"
+ " d = e.style.display;\n"
+ " if (d == 'block') {\n"
+ " e.style.display = 'none';\n"
+ " } else {\n"
+ " show(e);\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "function main() {\n"
+ " index = location.href.indexOf(\"#\");"
+ " if (index != -1) {\n"
+ " show(document.getElementById(location.href.substring(index + 1)));\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "</script>\n"
+ "</head>");
this.pw.println("<body onload='main()'>");
} else {
this.rootSection = rootSection;
this.pw.print("<ul>");
}
}
public HtmlSection createChildren(String section) {
if (child != null) {
if (child.name.equals(section)) {
return child;
}
child.close();
}
child = new SubSection(this, section, rootSection);
return child;
}
protected final void removeChild(HtmlSection child) {
if (this.child == child) {
this.child = null;
}
}
public void close() {
closeChild();
if (closed) {
return;
}
closed = true;
if (rootSection == this) {
pw.println("</body>");
pw.println("</html>");
pw.close();
} else {
pw.println("</ul>");
}
}
protected final void closeChild() {
if (child != null) {
child.close();
child = null;
}
}
public void link(HtmlSection section, String child, String name) {
String path = section.id;
if (path.isEmpty()) {
path = child;
} else if (child != null) {
path = String.format("%s.%s", path, child);
}
pw.printf("<a href=\"#%1$s\" onclick=\"show(document.getElementById('%1$s')); return true;\">%2$s</a>%n",
path, name);
}
public HtmlSection createChildren(String[] sections) {
int i = 0;
int n = sections.length;
HtmlSection current = this;
for (; i < n && current.child != null;
++i, current = current.child) {
if (!sections[i].equals(current.child.name)) {
break;
}
}
for (; i < n; ++i) {
current = current.createChildren(sections[i]);
}
return current;
}
private static class SubSection extends HtmlSection {
private final HtmlSection parent;
public SubSection(HtmlSection parent, String name,
HtmlSection rootSection) {
super(parent.pw,
parent.id.isEmpty()
? name
: String.format("%s.%s", parent.id, name),
name, rootSection);
this.parent = parent;
pw.printf("<li><a name='%1$s'/><a href='#%1$s' onclick=\"toggle('%1$s'); return false;\">%2$s</a><div id='%1$s'><code><pre>",
id, name);
}
@Override
public void close() {
closeChild();
if (closed) {
return;
}
pw.print("</pre></code></div></li><!-- " + id + "-->");
parent.removeChild(this);
super.close();
}
}
private static class HtmlFilterWriter extends FilterWriter {
public HtmlFilterWriter(PrintWriter pw) {
super(pw);
}
@Override
public void write(int c) throws IOException {
switch (c) {
case '<':
super.write("<", 0, 4);
break;
case '>':
super.write(">", 0, 4);
break;
case '"':
super.write(""", 0, 5);
break;
case '&':
super.write("&", 0, 4);
break;
default:
super.write(c);
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
for (int i = off; i < len; ++i){
write(cbuf[i]);
}
}
@Override
public void write(String str, int off, int len) throws IOException {
for (int i = off; i < len; ++i){
write(str.charAt(i));
}
}
}
}
|
package com.bw.myaccess.entity;
import java.io.Serializable;
import java.util.Date;
public class Group implements Serializable{
private Long tgId;
private String groupName;
private Long parentTgId;
private Date genTime;
private String description;
public Long getTgId() {
return tgId;
}
public void setTgId(Long tgId) {
this.tgId = tgId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
}
public Long getParentTgId() {
return parentTgId;
}
public void setParentTgId(Long parentTgId) {
this.parentTgId = parentTgId;
}
public Date getGenTime() {
return genTime;
}
public void setGenTime(Date genTime) {
this.genTime = genTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
}
|
package final_project; // later need to make up the emf
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Map.Entry;
public class FinalProject {
static String usr ="postgres";
static String pwd ="123";
static String url ="jdbc:postgresql://localhost:5432/postgres";
Connection con;
HashMap<String, outputInfo> finalResult; // key group attribute,
HashMap<Integer, groupvaInfo> groupVari; // key number of iterator
String[] groupAttri; // the grouping attribute's title
static int scanTime = 0;
// groupvaInfo b;
String[] Output; // just for the reference of output
String havingClause;
public FinalProject(){
finalResult = new HashMap<>();
groupVari = new HashMap<>();
}
public class outputInfo{ // all the grouping variable function including the output one
HashMap<String, functionClass> funclass; // detail info of f vect compare to the having condition, if satisfy, output
public outputInfo(){
funclass = new HashMap<>();
}
public class functionClass{
public functionClass(String a){
String[] subPart = a.split("_");
if(subPart[1] == "sum" && subPart[2] == "quant"){
int sum = 0;
}
else if(subPart[1] == "avg" && subPart[2] == "quant"){
int sum = 0, count = 0;
}
else if(subPart[1] == "count"){ int count = 0;}
}
}
}
public class prehand{
// for the selection part, hashmap to determine the 1. key is several attributes(customer, product, day....)
// value is ( corresponding 2. index in the data base, 3. operator, 4.condition value, 5.date type)
HashMap<String, selectioncondition> selectCon;
byte flag;
public prehand(groupvaInfo grvaInfo){
selectCon = new HashMap<>();
flag=0; // sum 01 avg 10 count 100
for(Entry<String , String> entryCondi : grvaInfo.condition.entrySet())
selectCon.put(entryCondi.getKey(), new selectioncondition(entryCondi.getKey(), entryCondi.getValue()));
for(int i = 0; i < grvaInfo.function.size(); i++){
String[] part = grvaInfo.function.get(i).split("_");
if(part[1].equals("sum") && part[2].equals("quant")) flag |= 1;
else if(part[1].equals("count") && part[2].equals("quant")) flag |= 10;
else if(part[1].equals("avg") && part[2].equals("quant")) flag |= 100;
}
}
class selectioncondition{ // we need to consider && ||
int index; String operator, conditionValue; int type; //data type 0 for int 1 for string
public selectioncondition(String key, String value){
if(key.equals("cust")) index = 1;
else if(key.equals("prod")) index = 2;
else if(key.equals("day")) index = 3;
else if(key.equals("month")) index = 4;
else if(key.equals("year")) index = 5;
else if(key.equals("state")) index = 6;
else index = 7;
operator = (value.charAt(1) == '=' ? value.substring(0, 2) : value.charAt(0) + "");
conditionValue = value.charAt(1) == '=' ? value.substring(2) : value.substring(1);
if(index >= 3 && index <=5 || index == 7) type = 0;
else type = 1;
}
}
}
public class groupvaInfo{
HashMap<String, String> condition; // state (key), 'NJ'(value) Month
ArrayList<String> function;
public groupvaInfo(){
condition = new HashMap<>();
function = new ArrayList<>();
}
}
public void readFile(Scanner s, FinalProject dbmsass1){
String temp = s.nextLine();
dbmsass1.Output = temp.split(", "); // for the output, select attribute
scanTime = s.nextInt(); // number of grouping variable
s.nextLine();
temp = s.nextLine();
dbmsass1.groupAttri = temp.split(", "); // grouping attribute
temp = s.nextLine();
String[] calfunction = temp.split(", "); // just split the F-vect and assignto the divide for later grouping variable assignment
for(int i = 0; i < calfunction.length; i++){
int a = calfunction[i].charAt(0)-'0';
if(!dbmsass1.groupVari.containsKey(a)){
groupvaInfo b = new groupvaInfo();
b.function.add(calfunction[i]);
dbmsass1.groupVari.put(a, b);
}
else
dbmsass1.groupVari.get(a).function.add(calfunction[i]);
}
temp = s.nextLine();
String[] selectCondition = temp.split(" , "); // SELECT CONDITION-VECT([σ]): get each iteration info
for(int i = 0; i < selectCondition.length; i++){
String[] iteratePart = selectCondition[i].split(" && "); // split each part in certan iteration
for(int j = 0; j < iteratePart.length; j++){
String[] split = iteratePart[j].split("_"); // get the limitation info: key value
if(!dbmsass1.groupVari.containsKey(split[0].charAt(0) -'0' )){
groupvaInfo b = new groupvaInfo();
b.condition.put(split[1], split[2]);
dbmsass1.groupVari.put(split[0].charAt(0) - '0', b);
}
else
dbmsass1.groupVari.get(split[0].charAt(0) -'0').condition.put(split[1], split[2]);
}
}
temp = s.nextLine();
havingClause= temp;
}
public static void main(String[] args) {
connect();
FinalProject dbmsass1 = new FinalProject();
try {
dbmsass1.con = DriverManager.getConnection(url, usr, pwd);
} catch (SQLException e1) {
e1.printStackTrace();
} //connect to the database using the password and username
System.out.println("Success connecting server!");
File file = new File("input.txt");
try {
dbmsass1.readFile(new Scanner(file), dbmsass1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for(int i = 0; i <= scanTime; i++ ){ // 0 is reserved for initial arrange
if(i == 0){}
else dbmsass1.retreive(dbmsass1.con, dbmsass1.prehandle(dbmsass1.groupVari.get(i)));
}
}
public prehand prehandle(groupvaInfo gvInfo){
return new prehand(gvInfo);
}
public void output(){
// having clause to select
}
public static void connect(){
try {
Class.forName("org.postgresql.Driver"); //Loads the required driver
System.out.println("Success loading Driver!");
} catch(Exception exception) {
System.out.println("Fail loading Driver!");
exception.printStackTrace();
}
}
void retreive(Connection con, prehand gvInfo){
try {
ResultSet rs; //resultset object gets the set of values retreived from the database
boolean more;
Statement st = con.createStatement(); //statement created to execute the query
String ret = "select * from sales";
rs = st.executeQuery(ret); //executing the query
more=rs.next(); //checking if more rows available
while(more)
{
// System.out.printf("%-8s ",rs.getString(1)); //left aligned
// System.out.printf("%-7s ",rs.getString(2)); //left aligned
// System.out.printf("%5s ",rs.getInt(3)); //right aligned
// System.out.printf("%8s ",rs.getInt(4)); //right aligned
// System.out.printf("%5s ",rs.getInt(5)); //right aligned
// System.out.printf("%-8s ",rs.getString(6)); //right aligned
// System.out.printf("%5s%n",rs.getInt(7)); //right aligned
more=rs.next();
}
} catch(SQLException e) {
System.out.println("Connection URL or username or password errors!");
e.printStackTrace();
}
}
}
|
package Chapter4.TreesAndGraphs.Exercise7Symmetric;
import ElementsOfProgrammingInterview.BinaryTreeChapter.BinaryTreeNode;
public class Solution {
public static void main(String[] args) {
}
public static boolean isSymmetric(BinaryTreeNode<Integer> tree) {
return tree == null || checkSymmetric(tree.left, tree.right);
}
private static boolean checkSymmetric(BinaryTreeNode<Integer> subtree0, BinaryTreeNode<Integer> subtree1) {
if (subtree0 == null || subtree1 == null) return true;
else if (subtree0 != null && subtree1 != null) {
return subtree0.data == subtree1.data && checkSymmetric(subtree0.left, subtree1.right) && checkSymmetric(subtree0.right, subtree1.left);
}
return false;
}
}
|
package com.geekhelp.dao.role;
import com.geekhelp.entity.Role;
/**
* Created by Вова on 02.10.14.
*/
public interface RoleDao {
/**
* Get role by id
* @param id of role
* @return role if exist or null
*/
public Role getRoleById(Integer id);
/**
* Get role by role name
* @param roleName of role
* @return role or null
*/
public Role getRoleByName(String roleName);
}
|
package com.tencent.mm.ui.chatting;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import com.tencent.mm.R;
import com.tencent.mm.ui.chatting.m.4;
class m$4$7 implements OnCreateContextMenuListener {
final /* synthetic */ 4 tIT;
m$4$7(4 4) {
this.tIT = 4;
}
public final void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo contextMenuInfo) {
contextMenu.add(0, 0, 0, R.l.multi_select_send_normal);
contextMenu.add(0, 1, 1, R.l.multi_select_send_record);
}
}
|
import javax.swing.JFrame;
public class Principal{
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setTitle("Principal");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
import javax.swing.JOptionPane;
public class Ex33For
{
public static void main(String[] args)
{
String s = JOptionPane.showInputDialog("Antal rader?");
int n = Integer.parseInt(s);
String txt = "";
for (int i = 1; i <=n; i++)
{
for (int j = 1; j<=i; j++)
txt = txt + '+';
txt = txt + '\n';
}
JOptionPane.showMessageDialog(null, txt);
}
}
|
package jpa.project.service;
import jpa.project.advide.exception.COrderNotFoundException;
import jpa.project.advide.exception.CResourceNotExistException;
import jpa.project.advide.exception.CUserNotFoundException;
import jpa.project.cache.CacheKey;
import jpa.project.entity.*;
import jpa.project.model.dto.delivery.DeliveryRegisterRequestDto;
import jpa.project.model.dto.order.OrderDto;
import jpa.project.model.dto.order.OrderSimpleDto;
import jpa.project.repository.member.MemberRepository;
import jpa.project.repository.order.OrderRepository;
import jpa.project.repository.registedShoes.RegistedShoesRepository;
import jpa.project.repository.search.OrderSearch;
import jpa.project.repository.search.ShoesSizeSearch;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final MemberRepository memberRepository;
private final RegistedShoesRepository registedShoesRepository;
private final CacheService cacheService;
@Transactional
public OrderDto save(String username,Long registedShoesId){
Member member = getMember(username);
RegistedShoes registedShoes = getRegistedShoes(registedShoesId);
Order order = Order.createOrder(member, registedShoes);
changeShoesPrice(registedShoes);
orderRepository.save(order);
cacheService.deleteOrderCache(order.getBuyer().getId(),order.getSeller().getId(),order.getRegistedShoes().getShoesInSize().getShoes().getId(),order.getId());
return OrderDto.createOrderDto(order);
}
private void changeShoesPrice(RegistedShoes registedShoes) {
Optional<RegistedShoes>optionalRegistedShoes=registedShoesRepository.findLowestPriceInShoes(registedShoes.getShoesInSize().getShoes().getId());
if(!optionalRegistedShoes.isEmpty())
registedShoes.getShoesInSize().getShoes().changePrice(optionalRegistedShoes.orElseThrow(CResourceNotExistException::new).getPrice());
}
private RegistedShoes getRegistedShoes(Long registedShoesId) {
Optional<RegistedShoes> findRegistedShoes = registedShoesRepository.findById(registedShoesId);
RegistedShoes registedShoes = findRegistedShoes.orElseThrow(CResourceNotExistException::new);
return registedShoes;
}
private Member getMember(String username) {
Optional<Member> findMember = memberRepository.findByUsername(username);
Member member = findMember.orElseThrow(CUserNotFoundException::new);
return member;
}
// public OrderSimpleDto findOrder(String username){
// Optional<Member> findMember = memberRepository.findByUsername(username);
// Member member = findMember.orElseThrow(CUserNotFoundException::new);
//
// member.
//
// }
@Cacheable(value = CacheKey.ORDER, key = "#orderId",unless ="#result==null")
public OrderDto detail(Long orderId){
Order order = getOrder(orderId);
return OrderDto.createOrderDto(order);
}
//판매자 배송정보 입력
@Transactional
public void addDeliveryInfo(Long orderId, DeliveryRegisterRequestDto registerRequestDto){
Order order = getOrder(orderId);
cacheService.deleteOrderCache(order.getBuyer().getId(),order.getSeller().getId(),order.getRegistedShoes().getShoesInSize().getShoes().getId(),orderId);
order.addDeliveryInfo(registerRequestDto.getTrackingNumber(),registerRequestDto.getCompany());
}
//관리자 주문상태 변경
@Transactional
public void updateOrder(Long orderId,DeliveryStatus deliveryStatus){
Order order = getOrder(orderId);
cacheService.deleteOrderCache(order.getBuyer().getId(),order.getSeller().getId(),order.getRegistedShoes().getShoesInSize().getShoes().getId(),orderId);
order.updateDelivery(deliveryStatus);
}
private Order getOrder(Long orderId) {
Optional<Order> findOrder = orderRepository.findById(orderId);
Order order = findOrder.orElseThrow(COrderNotFoundException::new);
return order;
}
public Page<OrderDto> findAllOrder(OrderSearch orderSearch, Pageable pageable){
return orderRepository.findAllOrder(pageable,orderSearch);
}
@Cacheable(value = CacheKey.ORDERS_PURCHASE, key = "{#memberId, #limit, #lastOrderId}",unless ="#result==null")
public Slice<OrderSimpleDto> findPurchasedOrder(Long memberId,Long lastOrderId,int limit){
return orderRepository.findPurChasOrderOrderByCreatedDate(memberId,lastOrderId!=null?lastOrderId:Long.MAX_VALUE, PageRequest.of(0, limit)).map(c -> OrderSimpleDto.createOrderSimpleDto(c));
}
@Cacheable(value = CacheKey.ORDERS_SALES, key = "{#memberId, #limit, #lastOrderId}",unless ="#result==null")
public Slice<OrderSimpleDto>findSoldOrder(Long memberId,Long lastOrderId,int limit){
return orderRepository.findSalesOrderOrderByCreatedDate(memberId,lastOrderId!=null?lastOrderId:Long.MAX_VALUE, PageRequest.of(0, limit)).map(c -> OrderSimpleDto.createOrderSimpleDto(c));
}
/**캐시**/
// public void deleteOrder(Long orderId){
// orderRepository.delete(
// }
//신발 거래된 주문표시
@Cacheable(value = CacheKey.ORDERS, key = "#shoesId",unless ="#result==null")
public Slice<OrderSimpleDto>findOrdersByShoesSize(Long shoesId,Long lastOrderId,ShoesSizeSearch shoesSizeSearch,int limit){
return orderRepository.findOrdersByShoesSize(shoesId, lastOrderId != null ? lastOrderId : Long.MAX_VALUE, shoesSizeSearch, PageRequest.of(0, limit));
}
//주문취소
@Transactional
public void deleteOrder(Long id) {
Order order = getOrder(id);
order.deleteOrder();
cacheService.deleteOrderCache(order.getBuyer().getId(),order.getSeller().getId(),order.getRegistedShoes().getShoesInSize().getShoes().getId(),order.getId());
changeShoesPrice(order.getRegistedShoes());
}
}
|
package mx.com.alex.crazycards.models;
import android.content.Context;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.Date;
import mx.com.alex.crazycards.database.DatabaseAdapter;
/**
* Created by mobilestudio06 on 11/08/15.
*/
public class Verb {
public static final String TABLE_NAME = "Verb";
public static final String ID_VERB = "idVerb";
public static final String VERB_ENGLISH = "verbEnglish";
public static final String VERB_SPANISH = "verbSpanish";
public static final String URL_IMAGE = "urlImgTrue";
private int idVerb;
private String verbEnglish;
private String verbSpanish;
private String urlImgTrue;
public int getIdVerb() {
return idVerb;
}
public void setIdVerb(int idVerb) {
this.idVerb = idVerb;
}
public String getVerbEnglish() {
return verbEnglish;
}
public void setVerbEnglish(String verbEnglish) {
this.verbEnglish = verbEnglish;
}
public String getVerbSpanish() {
return verbSpanish;
}
public void setVerbSpanish(String verbSpanish) {
this.verbSpanish = verbSpanish;
}
public String getUrlImgTrue() {
return urlImgTrue;
}
public void setUrlImgTrue(String urlImgTrue) {
this.urlImgTrue = urlImgTrue;
}
public Verb(int idVerb,String verbEnglish, String verbSpanish, String urlImgTrue) {
this.idVerb = idVerb;
this.verbEnglish = verbEnglish;
this.verbSpanish = verbSpanish;
this.urlImgTrue = urlImgTrue;
}
public static ArrayList<Verb> getVerbs(Context context) {
ArrayList<Verb> verbs= new ArrayList<Verb>();
try {
Cursor cursor = DatabaseAdapter.getDB(context).query(TABLE_NAME,null,null,null,null,null,null,null);
if (cursor!=null){
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
int idVerb = cursor.getInt(cursor.getColumnIndexOrThrow(ID_VERB));
String verbEnglish = cursor.getString(cursor.getColumnIndexOrThrow(VERB_ENGLISH));
String verbSpanish = cursor.getString(cursor.getColumnIndexOrThrow(VERB_SPANISH));
String urlImgTrue = cursor.getString(cursor.getColumnIndexOrThrow(URL_IMAGE));
verbs.add(new Verb(idVerb, verbEnglish,verbSpanish,urlImgTrue));
}
}
} catch (Exception e){
e.printStackTrace();
}
return verbs;
}
}
|
package ac.kr.ajou.dirt;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class DirtySampleTest {
@Test
public void updateQuality_item의_name이_Aged와_Backstage와_Sulfuras가_모두_아니고_quality_0초과이면_quality_1_감소() {
Item[] items = new Item[] { new Item("foo", 2, 2) };
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(1));
}
@Test
public void updateQuality_item의_name이_Aged이고_quality가_50미만이면_quality_1_증가() {
Item[] items = new Item[] { new Item("Aged Brie", 2, 2), new Item("Aged Brie", 2, 3) };
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(3));
assertThat(items[1].quality, is(4));
}
@Test
public void updateQuality_item의_name이_Backstage이고_sellIn이_6이상_11미만이고_quality가_50미만이면_quality_2_증가() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 7, 3) };
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(5));
}
@Test
public void updateQuality_item의_name이_Backstage이고_sellIn이_6미만이고_quality가_50미만이면_quality_3_증가() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 5, 3) };
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(6));
}
@Test
public void updateQuality_item의_name이_Sulfuras가_아니면_sellIn_1_감소() {
Item[] items = new Item[]{new Item("foo", 2, 2)};
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertTrue(items[0].sellIn == 1);
}
@Test
public void updateQuality_item의_sellIn이_0미만이고_name이_Aged와_Backstage와_Sulfuras가_아니고_quality가_0보다_크면_quality_2_감소() {
Item[] items = new Item[]{new Item("foo", -2, 3)};
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(1));
}
@Test
public void updateQuality_item의_sellIn이_0미만이고_name이_Aged가_아니고_Backstage이면_quality_0 () {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", -2, 3) };
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(0));
}
@Test
public void updateQuality_item의_sellIn이_0미만이고_name이_Aged이고_quality가_50_미만이면_quality_2_증가 () {
Item[] items = new Item[] { new Item("Aged Brie", -2, 3) };
DirtySample dirtySample = new DirtySample(items);
dirtySample.updateQuality();
assertThat(items[0].quality, is(5));
}
}
|
package com.cnk.travelogix.supplier.mappings.services;
import com.cnk.travelogix.supplier.mappings.product.model.SupplierAccommodationMappingModel;
/**
* The Interface SupplierCountryMappingService.
*/
public interface SupplierAccommodationMappingService extends SupplierMappingService<SupplierAccommodationMappingModel>
{
}
|
package demo.service;
import demo.entity.IlJugMember;
public interface IIlJugMemberService {
public IlJugMember createIlJugMember(String lastName, String firstName);
public IlJugMember getIlJugMember(Long id);
public Iterable<IlJugMember> getAllIlJugMembers();
public Iterable<IlJugMember> findIlJugMemberByLastName(String lastName);
public void deleteIlJugMember(Long id);
public void updateIlJugMember(Long id, String lastName, String firstName);
}
|
package com.libedi.demo.domain;
/**
* TestEnum
*
* @author Sang-jun, Park
* @since 2019. 04. 02
*/
public enum TestEnum {
TEST1,
TEST2
}
|
package Exceptions;
public class StQu1 {
/*
http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html
*/
public int tryCatchFinally() {
try {
try {
System.out.println("Inner TRY");
int i = 1/0;
System.out.println("Inner TRY after 1/0");
return 1;
} catch (Exception e) {
System.out.println("Inner CATCH");
int i = 1/0;
System.out.println("Inner CATCH after 1/0");
return 2;
} finally {
System.out.println("Inner FINALLY!");
//int i = 1/0;
// System.exit(1);
//return 3; // what will happen if we comment this line out?
}
} catch (Exception e) {
System.out.println("Outer Catch");
return 4;
} finally {
System.out.println("Outer FINALLY");
//System.exit(1); // hat will happen if we comment this line out?
return 6; // what will happen if we comment this line out?
}
}
public static void main(String[] args ) {
// return value is?
System.out.println("new StQu1().tryCatchFinally(); = " +
new StQu1().tryCatchFinally() );
//finally>return>catch
//even if a return is called, it will come out of the function only after going to finally
}
}
|
/*
* 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 Shapes;
import Tools.Resizer;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
public class Line extends Shapes {
private Line2D line = new Line2D.Double();
public Line() {
setThisShape(line);
}
@Override
public void drawShape(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getColor());
g2.setStroke(new BasicStroke(getPenSize()));
line.setLine(getxPos(), getyPos(), getWidths(), getLengths());
g2.draw(line);
g2.setPaint(getFillColor());
g2.fill(line);
if (isSelected()) {
drawBound(g);
}
}
@Override
public void move(Point p, Point o) {
int baseX = (int) o.getX();
int baseY = (int) o.getY();
int dx = (int) (p.getX() - baseX);
int dy = (int) (p.getY() - baseY);
setxPos(getxPos() + dx);
setyPos(getyPos() + dy);
setWidths(getWidths() + dx);
setLengths(getLengths() + dy);
}
@Override
public void drawBound(Graphics g) {
drawBoundPoint(getxPos(), getyPos(), g);
drawBoundPoint((int) getWidths(), (int) getLengths(), g);
}
@Override
public void resize(Point p, Resizer r) {
setxPos((int) p.getX());
setyPos((int) p.getY());
}
}
|
package com.originspark.drp.controllers.projects.inventories;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
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.originspark.drp.controllers.BaseController;
import com.originspark.drp.util.FileUtil;
import com.originspark.drp.util.poi.exporter.CurrentInventoriesGenerator;
import com.originspark.drp.web.models.projects.inventories.CurrentInventoryUI;
@Controller
@RequestMapping("inventories")
public class InventoryController extends BaseController {
private Logger logger = Logger.getLogger(InventoryController.class);
@RequestMapping(value = "/current", method = RequestMethod.GET)
@ResponseBody
public String currentInventories(@RequestParam int start, @RequestParam int limit) {
List<CurrentInventoryUI> data = inventoryService.pagedCurrentInventories(start, limit);
Long count = inventoryService.pagedCurrentInventoriesCount();
return ok(data, count);
}
/*
@ResponseBody
@RequestMapping(value = "/{id}/inventories/monthend", method = RequestMethod.GET)
@AuthRoleGroup(type={RoleEnum.PROJECTMANAGER,RoleEnum.LEADER})
public String menthendInventories(@PathVariable Long id,@RequestParam String formonth){
Project project = projectService.findById(id);
if(project == null){
return failure("你所查询的项目不存在");
}
List<Ware> inventories = new ArrayList<Ware>();
//如果是项目
if(project.getProject() == null){
for(Project system : project.getSystems()){
inventories.addAll(projectService.getMonthEndInventories(system.getId(),formonth));
}
return ok(inventories);
}
inventories.addAll(projectService.getMonthEndInventories(id,formonth));
return ok(inventories);
}
@RequestMapping(value = "/{id}/inventories/monthend/export", method = RequestMethod.GET)
public void exportMonthendInventory(@PathVariable Long id,@RequestParam String formonth,HttpServletRequest request, HttpServletResponse response){
Project system = projectService.findById(id);
List<Ware> inventories = projectService.getMonthEndInventories(system.getId(),formonth);
//因为使用createTempFile(),所以会生成默认的名称后缀,所以加下划线分割
String fileName = formonth +"_";
File file = MonthendInventoryGenerator.generate(fileName, inventories, FileUtil.getResourcesPath(request));
if (file != null) {
try {
response.setContentType("application/x-excel;charset=UTF-8");
response.setHeader("content-Disposition", "attachment;filename=" + file.getName());// "attachment;filename=test.xls"
InputStream is = new FileInputStream(file);
IOUtils.copyLarge(is, response.getOutputStream());
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
}*/
@RequestMapping(value = "/{type}/export", method = RequestMethod.GET)
public void exportExcel(@PathVariable String type, @RequestParam(required = false) String ids, HttpServletResponse response) {
if (type == null || "".equals(type)) {
logger.error("库存导出错误");
return;
}
if ("current".equals(type)) {
// 实时库存的导出
List<CurrentInventoryUI> inventories = inventoryService.pagedCurrentInventories(-1, 0);
String fileName = "currentInventories_";
File file = CurrentInventoriesGenerator.generate(fileName, inventories, FileUtil.getResourcesPath(request()));
if (file != null) {
try {
response.setContentType("application/x-excel;charset=UTF-8");
response.setHeader("content-Disposition", "attachment;filename=" + file.getName());// "attachment;filename=test.xls"
InputStream is = new FileInputStream(file);
IOUtils.copyLarge(is, response.getOutputStream());
} catch (IOException ex) {
logger.error("商品导出错误");
}
}
} else if ("monthend".equals(type)) {
}
}
}
|
package com.andysierra.culebrita.consts;
public class Consts
{
// Tablero y Lógica
public static final int FILAS = 15;
public static final int COLS = 10;
public static final int SIGUIENTE_NIVEL = 200; // default 200
public static final int DIFICULTAD_BOMBAS = 3; // default 3
// Medidas de tiempo y FPS
public static final int TIEMPO_SERPIENTE = 350; // Velocidad de serpiente, defaults 150, 250, 350
public static final int SEGUNDO = 1000; // segundero
public static final int TIEMPO_MANZANA = 1000; // aparición de manzanas
public static final int EJECUTE_ACTUALIZAR_TABLERO = 1001; // id serpiente
public static final int EJECUTE_ACTUALIZAR_PUNTAJE = 1002; // id puntaje
public static final int EJECUTE_ACTUALIZAR_TXFTIEMPO = 1003; // id reloj
public static final int EJECUTE_ACTUALIZAR_HINT = 1004; // id hint
public static final int EJECUTE_ACTUALIZAR_MENSAJE = 1005; // id mensaje
public static final int EJECUTE_TEMPORIZADOR = 1006; // id temporizador
public static final int EJECUTE_SPAWN_MANZANA = 1007; // id spawn manzanas
public static final int EJECUTE_SPAWN_BOMBA = 1008; // id spawn bomba
public static final int EJECUTE_UP = 1009; // id up
// Serpiente
public static enum direccion{
ARRIBA(1), ABAJO(-1), DERECHA(2), IZQUIERDA(-2);
private int orden;
private direccion(int orden) { this.orden = orden; }
public int toInt() { return this.orden; }
public static Consts.direccion toDireccion(int orden) {
if(orden==1) return direccion.ARRIBA;
else if(orden==-1) return direccion.ABAJO;
else if(orden==2) return direccion.DERECHA;
else if(orden==-2) return direccion.IZQUIERDA;
else return null;
}
}
public static final int POSICION_INICIAL_I = Consts.FILAS/2;
public static final int POSICION_INICIAL_J = Consts.COLS-4;
public static final int LONGITUD_INICIAL = 4;
public static final Consts.direccion ORIENTACION_INICIAL = direccion.IZQUIERDA;
// Hints
public static final String BOMBA_BUENA = "Bomba: No te quitará puntos por ahora :)";
public static final String BOMBA_MALA = "Bomba: -10 puntos";
public static final String GAME_OVER = "Game Over ¯\\_(ツ)_/¯";
// Mensajes
public static final int MSG_SPAWN_BOMBA = 2001;
// Objetos del juego
public static final int VACIO1 = 10;
public static final int VACIO2 = 20;
public static final int SERPIENTE = 30;
public static final int SERPIENTE_CABEZA = 31;
public static final int SERPIENTE_CABEZA_CRASH = 32;
public static final int SERPIENTE_COLA = 33;
public static final int MANZANA = 40;
public static final int MANZANA_VERDE = 41;
public static final int MANZANA_DORADA = 42;
public static final int BOMBA = 43;
public static final int VENENO = 44;
public static final int AREA_SEGURA = 45;
public static final int MAPACHE = 50; // Primer jefe
public static final int ZORRO = 51; // Segundo Jefe
public static final int COYOTE = 52; // Tercer Jefe
public static final int MANGOSTA = 53; // Último Jefe
}
|
package com.qgbase.app.services;
/**
* @author : shl
* @name :
* @date : 2019/8/2
* @desc :
*/
public class AppAuthServices {
}
|
package com.github.adambots.steamworks2017.smartDash;
import org.usfirst.frc.team245.robot.Constants;
import com.ctre.CANTalon;
public class TalonDio {
//Will return if current is going to drive motors
public static boolean driveEncodDio(CANTalon CANTalon1, CANTalon CANTalon2){
double outputCurrent1 = CANTalon1.getOutputCurrent();
double outputCurrent2 = CANTalon2.getOutputCurrent();
if(outputCurrent1 != 0 || outputCurrent2 != 0){
return true;
}else{
return false;
}
}
//Will return if current is going to Climbing motor
public static boolean climbEncodDio(CANTalon CANTalon){
double outputCurrent = CANTalon.getOutputCurrent();
if (outputCurrent > 0){
return true;
}else{
return false;
}
}
//Will return true if motor is about to stall
public static boolean CIMStall(CANTalon CANTalon3){
double outputCurrent = CANTalon3.getOutputCurrent();
if (outputCurrent >= Constants.MOTOR_CIM_STALL_CURRENT){
return true;
}else{
return false;
}
}
}
|
package listaJava4Classes;
public class ContaBancaria
{
String nomeCliente;
String agencia;
String conta;
private double saldo;
public ContaBancaria(String nomeCliente, String agencia, String conta) {
super();
this.nomeCliente = nomeCliente;
this.agencia = agencia;
this.conta = conta;
}
public void depositar(double valor)
{
this.saldo+= valor;
System.out.println("O saldo apůs o depůsito ť de: R$" +Math.round( this.saldo)+" reais");
}
public void sacar(double valor)
{
this.saldo -= valor;
System.out.println("O saldo apůs o saque ť de: R$" +Math.round( this.saldo)+" reais");
}
public double extrato()
{
System.out.println("O seu saldo ť de: R$" +Math.round( this.saldo)+" reais");
return this.saldo;
}
@Override
public String toString() {
return "ContaBancaria [nomeCliente=" + nomeCliente + ", agencia=" + agencia + ", conta=" + conta + ", saldo="
+ saldo + "]";
}
}
|
/*
* 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 View.Atendimento;
import Model.Anexo;
import Model.Atendimento;
import Util.Classes.PropertiesManager;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Frm_Anexo extends javax.swing.JFrame {
String diretorio = null;
List<Anexo> lista;
PropertiesManager prop;
int codigo;
Anexo anexo;
Atendimento atendimento;
public Frm_Anexo(Atendimento att) {
initComponents();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
atendimento = att;
setVisible(true);
limpaAnexos();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
btn_gravar = new javax.swing.JButton();
btn_buscar = new javax.swing.JButton();
btn_limpar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txt_qtdeAnexos = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
foto = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Anexar Imagens");
setResizable(false);
btn_gravar.setText("Gravar");
btn_gravar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_gravarActionPerformed(evt);
}
});
btn_buscar.setText("Adicionar");
btn_buscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_buscarActionPerformed(evt);
}
});
btn_limpar.setText("Limpar");
btn_limpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_limparActionPerformed(evt);
}
});
jLabel1.setText("Anexos:");
txt_qtdeAnexos.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
txt_qtdeAnexos.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
txt_qtdeAnexos.setText("0");
foto.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jScrollPane1.setViewportView(foto);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btn_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_limpar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_qtdeAnexos, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE)
.addComponent(btn_gravar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_gravar)
.addComponent(btn_buscar)
.addComponent(btn_limpar)
.addComponent(jLabel1)
.addComponent(txt_qtdeAnexos))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btn_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_buscarActionPerformed
buscaImagem();
}//GEN-LAST:event_btn_buscarActionPerformed
private void btn_limparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_limparActionPerformed
lista = new ArrayList<>();
txt_qtdeAnexos.setText("0");
foto.setIcon(null);
}//GEN-LAST:event_btn_limparActionPerformed
private void btn_gravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_gravarActionPerformed
gravarAnexos();
}//GEN-LAST:event_btn_gravarActionPerformed
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_Anexo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_Anexo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_Anexo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_Anexo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new Frm_Anexo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_buscar;
private javax.swing.JButton btn_gravar;
private javax.swing.JButton btn_limpar;
private javax.swing.JLabel foto;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel txt_qtdeAnexos;
// End of variables declaration//GEN-END:variables
private void buscaImagem() {
JFileChooser c = new JFileChooser();
c.showOpenDialog(this);//abre o arquivo
File file = c.getSelectedFile();//abre o arquivo selecionado
Path path = Paths.get(file.getAbsolutePath());
diretorio = path.toString();
if (diretorio.endsWith("png") || diretorio.endsWith("jpg")) {
byte[] bFile = new byte[(int) file.length()];
if (bFile.length <= 1048576) {
try {
anexo = new Anexo();
anexo.setCodatendimento(atendimento);
FileInputStream fis = new FileInputStream(file);
fis.read(bFile);
fis.close();
anexo.setImagem(bFile);
lista.add(anexo);
carregaImagem(diretorio);
txt_qtdeAnexos.setText(Integer.parseInt(txt_qtdeAnexos.getText()) + 1 + "");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao inserir imagem na lista!\n" + e.getMessage());
}
} else {
JOptionPane.showMessageDialog(null, "Imagem muito grande!\n");
}
} else {
JOptionPane.showMessageDialog(this, "Extenção do arquivo selecionado inválido!\n "
+ "Tente imagens com extenção: PNG ou JPG");
}
}
private ImageIcon getImagemByCaminho(String caminho) {
ImageIcon imagem = new ImageIcon(caminho);
if (imagem != null) {
return imagem;
} else {
System.err.println("Não foi possível encontrar o arquivo: " + caminho);
return null;
}
}
private void carregaImagem(String caminho) {
try {
foto.setIcon(new ImageIcon(alteraTamanhoImagem(getImagemByCaminho(caminho.replace("\\", "/")).getImage(), this.getWidth() - 50)));
foto.revalidate();
foto.repaint();
} catch (Exception e) {
System.out.println(e);
}
}
public Image alteraTamanhoImagem(Image img, int largura) {
//Calcula a proporção para descobrir a nova altura
double proportion = largura / (double) img.getWidth(null);
int newHeight = (int) (img.getHeight(null) * proportion);
//Cria a imagem de destino
BufferedImage newImage = new BufferedImage(largura, newHeight, BufferedImage.TYPE_INT_ARGB);
//Desenha sobre ela usando filtro Bilinear (o java não possui trinilear ou anisotrópica).
Graphics2D g2d = newImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(img, 0, 0, largura, newHeight, null);
g2d.dispose();
return newImage;
}
private void limpaAnexos() {
try {
lista = new ArrayList<>();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao limpar os anexos!\n" + e.getMessage());
}
}
private void gravarAnexos() {
try {
atendimento.setAnexoList(lista);
dispose();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao anexar as imagens!\n" + e.getMessage());
}
dispose();
}
}
|
package com.cg.javafullstack.object;
public class TestB {
public static void main(String[] args) {
Bike b=new Bike();
b.cost=10;
b.name="Hayabusa";
b.weight=10;
System.out.println(b);
}
}
|
package com.model;
import java.util.Date;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Typecv;
public class UserDTO {
private int user_ID;
private String address;
private Date birthday;
private String email;
private String facebook;
private String imageUrl;
private String name;
private String career;
private String maxim;
private String password;
private String confirmPassword;
private String phone;
private String username;
private MultipartFile file;
private long likes;
private List<SkillDTO> skills;
private Typecv typecv;
private byte state;
public UserDTO() {
}
public UserDTO(int id) {
this.user_ID = id;
}
public int getUser_ID() {
return user_ID;
}
public void setUser_ID(int user_ID) {
this.user_ID = user_ID;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFacebook() {
return facebook;
}
public void setFacebook(String facebook) {
this.facebook = facebook;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getCareer() {
return career;
}
public void setCareer(String career) {
this.career = career;
}
public String getMaxim() {
return maxim;
}
public void setMaxim(String maxim) {
this.maxim = maxim;
}
public List<SkillDTO> getSkills() {
return skills;
}
public void setSkills(List<SkillDTO> skills) {
this.skills = skills;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
public long getLikes() {
return likes;
}
public void setLikes(long likes) {
this.likes = likes;
}
public Typecv getTypecv() {
return typecv;
}
public void setTypecv(Typecv typecv) {
this.typecv = typecv;
}
public byte getState() {
return state;
}
public void setState(byte state) {
this.state = state;
}
}
|
package com.tencent.mm.plugin.subapp.ui.pluginapp;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.ac.m;
import com.tencent.mm.ac.m.a.a;
import com.tencent.mm.ac.z;
import com.tencent.mm.model.au;
class ContactSearchResultUI$d implements a, Runnable {
public ImageView eCl;
public TextView eMf;
public View hod;
public TextView hoe;
private View hoh;
public String iconUrl;
ContactSearchResultUI.a otu = new 1(this);
public String username;
public ContactSearchResultUI$d() {
z.Ni().a(this);
}
public final void run() {
Bitmap kV = m.kV(this.username);
if (kV != null) {
ContactSearchResultUI.bGz().post(new 2(this, kV));
} else {
ContactSearchResultUI.bGz().post(new 3(this));
}
}
public final void kX(String str) {
if (str != null && str.equals(this.username)) {
this.otu.eR(this.username, this.iconUrl);
au.Em().h(this.otu, 200);
}
}
}
|
package com.cse.sportsplus.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.cse.sportsplus.models.Athlete;
public interface AthleteRepository extends JpaRepository<Athlete, Long> {
Optional<Athlete> findById(Long id);
Athlete findByFirstName(String s);
}
|
import java.util.*;
public class Main {
public static void main(String[] args) {
LinkedList <String> arr = new LinkedList <String> ();
arr.add("Red");
arr.add("Green");
arr.add("Black");
arr.add("White");
arr.add("Pink");
System.out.println("Original linked list: " + arr);
System.out.println("Removed element: "+arr.pop());
System.out.println("Linked list after pop operation: "+arr);
}
}
|
package m3103.tp1;
public class Counter {
private int comp;
private int perm;
public void incComp() {
this.comp++;
}
public void incComp(int n) {
this.comp = this.comp + n;
}
public void incPerm() {
this.perm++;
}
public void incPerm(int n) {
this.perm = this.perm + n;
}
public String toString() {
String res = ("\nnombre comparaison : "+this.comp+"\nnombre permutation : "+this.perm+"\n");
System.out.println(res);
return res;
}
public void reset() {
comp = 0;
perm = 0;
}
}
|
package com.sunteam.library.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.sunteam.common.menu.MenuActivity;
import com.sunteam.common.menu.MenuConstant;
import com.sunteam.common.utils.SharedPrefUtils;
import com.sunteam.common.utils.dialog.PromptListener;
import com.sunteam.library.R;
import com.sunteam.library.utils.EbookConstants;
import com.sunteam.library.utils.MediaPlayerUtils;
import com.sunteam.library.utils.PublicUtils;
/**
* @Destryption 音乐开关设置界面
* @Author Jerry
* @Date 2017-2-8 上午9:08:29
* @Note
*/
public class MusicSwitch extends MenuActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
selectItem = getMusicSwitch();
}
@SuppressLint("HandlerLeak")
private Handler mTtsCompletedHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 8:
setResult(Activity.RESULT_OK);
finish();
break;
default:
break;
}
}
};
@Override
public void setResultCode(int resultCode, int selectItem, String menuItem) {
if (0 == selectItem || 1 == selectItem) {
Intent intent = new Intent();
intent.putExtra(MenuConstant.INTENT_KEY_SELECTEDITEM, selectItem);
intent.putExtra("selectStr", menuItem);
saveMusicSwitch(selectItem);
setResult(Activity.RESULT_OK, intent);
}
}
private void saveMusicSwitch(int index) {
Intent intent = new Intent(EbookConstants.MENU_PAGE_EDIT);
intent.putExtra("result_flag", 1);
SharedPrefUtils.saveSettings(this, EbookConstants.SETTINGS_TABLE, EbookConstants.MUSICE_STATE, index);
sendBroadcast(intent);
// 提示设定成功
String tips = getResources().getString(R.string.library_setting_success);
PublicUtils.showToast(this, tips, new PromptListener() {
@Override
public void onComplete() {
MediaPlayerUtils.getInstance().stop();
setResult(Activity.RESULT_OK);
finish();
}
});
}
@SuppressWarnings("deprecation")
private int getMusicSwitch() {
int mode = Context.MODE_WORLD_READABLE + Context.MODE_MULTI_PROCESS;
return SharedPrefUtils.getSharedPrefInt(this, EbookConstants.SETTINGS_TABLE, mode, EbookConstants.MUSICE_STATE, 0);
}
}
|
package com.lxy.debug;
import java.util.Arrays;
public class Demo1 {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = new int[]{11, 22, 33, 44, 55};
int index = Arrays.binarySearch(arr, 55);
// System.out.println(arr);
System.out.println(index);
}
}
|
package View.GUISistemaDeAutenticacion;
import Model.SistemaDeUsuario.*;
import java.util.Scanner;
import java.io.*;
import java.io.FileOutputStream;
public class GUISistemaDeAutenticacion{
Usuarios logIn = null;
public GUISistemaDeAutenticacion(){
}
/*public Boolean acceder() throws IOException, FileNotFoundException, ClassNotFoundException {
int selector;
System.out.println("Que tipo de usuario eres \n1 Cliente\n2.Gerente\n3.Chef\n");
selector = ingresoDatosInt();
switch (selector) {
case 1:
return menuCliente();
case 2:
return menuGerente();
case 3:
return menuChef();
default:
return false;
}
}*/
public Usuarios menuCliente() throws IOException, FileNotFoundException, ClassNotFoundException{
long numerodetarjeta;
int mesDeExpiracion;
int year;
String cuenta;
String contrasena;
GestorDeUsuarios Ges = new GestorDeUsuarios();
while (true) {
System.out.println("\nQuieres: \n\t1.Crear Nuevo Usuario\n\t2.Acceder\n\t0.Salir");
int seleccion = ingresoDatosInt();
clearScreen(); // Limpia la Pantalla
switch (seleccion){
case 1:
System.out.println("\t= = Crear Usuario = =\n");
System.out.println("Cual es tu nombre de usuario:\n");
cuenta = ingresoDatosString();
System.out.println("Cual es tu contrasena:\n");
contrasena = ingresoDatosString();
System.out.println("Cual es tu numero de tarjeta:\n");
numerodetarjeta = ingresoDatoslong();
System.out.println("Cual es tu mes De Expiracion:\n");
mesDeExpiracion = ingresoDatosInt();
System.out.println("Cual es tu año de experacion:\n");
year = ingresoDatosInt();
Ges.addUsuarioCliente(cuenta,contrasena,new TarjetaBancaria(numerodetarjeta,mesDeExpiracion,year));
break;
case 2:
if (accederSistema(Ges,3)) {
return logIn;
}
case 0:
return null;
default:
System.out.println("Ingrese una opcion correcta");
break;
}
clearScreen();
}
}
public Boolean menuChef() throws IOException, FileNotFoundException, ClassNotFoundException{
GestorDeUsuarios Ges = new GestorDeUsuarios();
System.out.println("Ingresa la clave para poder ingresar a un usuario de tipo Chef");
String pass = ingresoDatosString();
if (Ges.autorizarChef(pass))
return accederSistema(Ges,2);
else {
System.out.println("Contraseña Incorrecta");
return false;
}
}
public Boolean menuGerente() throws IOException, FileNotFoundException, ClassNotFoundException{
GestorDeUsuarios Ges = new GestorDeUsuarios();
int selector;
System.out.println("Ingresa la clave para poder ingresar a un usuario de tipo Admin");
String pass = ingresoDatosString();
if (Ges.autorizarGerente(pass)) {
while (true) {
System.out.println("Que Quieres hacer\n\t1.Ingresar al sistema \n\t2.Agregar Usuario Chef o Gerente \n\t3.Borrar Usuario\n\t0.Salir");
selector = ingresoDatosInt();
switch (selector) {
case 0:
return false;
case 1:
return accederSistema(Ges,1);
case 2:
agregarUsuarioStaff(Ges);
break;
case 3:
borrarUsuario(Ges);
break;
default:
System.out.println("Ingresa una opcion correcta");
}
clearScreen(); // Limpia pantalla
}
}else{
return false;
}
}
private Boolean accederSistema(GestorDeUsuarios Ges,int tipoUsuario) throws IOException, FileNotFoundException, ClassNotFoundException{
String cuenta;
String contrasena;
System.out.println("\t = = Acceder al Sistema = =");
System.out.println("Cual es tu nombre de usuario:\n");
cuenta = ingresoDatosString();
System.out.println("Cual es tu contrasena:\n");
contrasena = ingresoDatosString();
logIn = Ges.getUsuario(tipoUsuario,cuenta,contrasena);
return Ges.ingresar(tipoUsuario,cuenta,contrasena);
}
private Boolean agregarUsuarioStaff(GestorDeUsuarios ges) throws IOException, FileNotFoundException, ClassNotFoundException {
int id;
String contrasena;
String cuenta;
int selector;
System.out.println("\t + + Agregar Staff + +");
System.out.println("Que tipo de usuario quieres agregar \n1.Gerente\n2.Chef");
selector = ingresoDatosInt();
switch (selector) {
case 1:
System.out.println("Cual es tu nombre de usuario:\n");
cuenta = ingresoDatosString();
System.out.println("Cual es tu contrasena:\n");
contrasena = ingresoDatosString();
System.out.println("Cual es el numero de gerente:\n");
id = ingresoDatosInt();
return ges.addUsuarioStaff(selector,cuenta,contrasena,id);
case 2:
System.out.println("Cual es tu nombre de usuario:\n");
cuenta = ingresoDatosString();
System.out.println("Cual es tu contrasena:\n");
contrasena = ingresoDatosString();
System.out.println("Cual es el numero de chef:\n");
id = ingresoDatosInt();
return ges.addUsuarioStaff(selector,cuenta,contrasena,id);
default:
System.out.println("No se ingreso una opcion correcta");
return false;
}
}
private Boolean borrarUsuario(GestorDeUsuarios ges) throws IOException, FileNotFoundException, ClassNotFoundException{
int selector;
String contrasena;
String cuenta;
int i;
System.out.println("\t + + Borrar Staff + +");
System.out.println("Que tipo de usuario quieres Borrar \n\t1. Cliente\n\t2.Gerente\n\t3.Chef\n");
selector = ingresoDatosInt();
System.out.println("Cual es tu nombre de usuario:\n");
cuenta = ingresoDatosString();
System.out.println("Cual es tu contrasena:\n");
contrasena = ingresoDatosString();
System.out.println("Estas seguro que quieres borrar el usuario :\n1.si \n2.no \n");
i = ingresoDatosInt();
if(i==1){
return ges.removeUser(selector,cuenta,contrasena);
}
else {
System.out.println("No se borro el usuario");
return false;
}
}
// U T I L I D A D E S
private int ingresoDatosInt() {
Scanner scan = new Scanner(System.in);
while (true) {
try {
return scan.nextInt();
} catch (Exception e) {
System.out.println("Ingresa un Numero");
scan.nextLine();
}
}
}
private long ingresoDatoslong() {
Scanner scan = new Scanner(System.in);
while (true) {
try {
return scan.nextLong();
} catch (Exception e) {
System.out.println("Ingresa un Numero");
scan.nextLine();
}
}
}
private String ingresoDatosString() {
Scanner scan = new Scanner(System.in);
while (true) {
try {
return scan.next();
} catch (Exception e) {
System.out.println("Ingresa un valor valido");
scan.nextLine();
}
}
}
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
}
|
package com.project.linkedindatabase.domain.chat;
import com.project.linkedindatabase.annotations.Table;
import com.project.linkedindatabase.domain.BaseEntity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Table(tableName = "chat")
public class Chat extends BaseEntity {
private Boolean isArchive;
private Boolean markUnread;
private Long profileId1;// foreign key to profile table.
private Long profileId2;// foreign key to profile table.
// profileId1 and profileId2 indicate user that have chat with each other
}
|
package com.samples;
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 10,b=20;
swap(a,b);
}
private static void swap(int a, int b) {
int c = a;
a = b;
b=c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
|
/*
*
*/
package com.library.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.library.exception.ResourceNotFoundException;
import com.library.model.ParameterMst;
import com.library.repository.ParamRepository;
import com.library.service.ParamService;
/**
* The Class ParamServiceimpl.
*/
@Service
public class ParamServiceimpl implements ParamService {
/** The param repository. */
private ParamRepository paramRepository;
/**
* Instantiates a new param serviceimpl.
*
* @param paramRepository the param repository
*/
@Autowired
public ParamServiceimpl(ParamRepository paramRepository) {
this.paramRepository = paramRepository;
}
/**
* Creates the param.
*
* @param param the param
* @return the parameter mst
*/
@Override
public ParameterMst createParam(ParameterMst param) {
return paramRepository.save(param);
}
/**
* Find by id.
*
* @param i the i
* @return the parameter mst
* @throws ResourceNotFoundException the resource not found exception
*/
@Override
public ParameterMst findById(Long i) throws ResourceNotFoundException {
return paramRepository.findById(i)
.orElseThrow(() -> new ResourceNotFoundException("Parameter not found for this id :: " + i));
}
/**
* Gets the params.
*
* @return the params
*/
@Override
public List<ParameterMst> getParams() {
return paramRepository.findAll();
}
}
|
package bojSolution;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class 게리맨더링_17471 {
static int N;
static int[] peopleCount;
static int[][] map;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int[] B = {5,4,4};
List<int[]> list = new ArrayList<>(Arrays.asList(B));
System.out.println(list.get(0)[0]);
N=Integer.parseInt(br.readLine());
st=new StringTokenizer(br.readLine());
peopleCount=new int[N];
for(int i=0;i<N;i++)
peopleCount[i]=Integer.parseInt(st.nextToken());
map=new int[N][N];
for(int i=0;i<N;i++) {
st=new StringTokenizer(br.readLine());
int num=Integer.parseInt(st.nextToken());
for(int j=0;j<num;j++) {
int t=Integer.parseInt(st.nextToken());
map[i][t-1]=1;
}
}
int size = 1<<N;
int result=Integer.MAX_VALUE;
for(int i=1;i<size-1;i++) {
ArrayList<Integer> teamA = new ArrayList<>();
ArrayList<Integer> teamB = new ArrayList<>();
for(int j=0;j<N;j++) {
int reg = (1<<j)&i;
if(reg>0) {
teamA.add(j);
}else {
teamB.add(j);
}
}
// printMap(teamA);
// printMap(teamB);
int resultA=checkEdge(teamA);
int resultB=checkEdge(teamB);
// System.out.println(resultA+" "+resultB);
if(resultA!=-1 && resultB!=-1)
result=Math.min(result,Math.abs(resultA-resultB));
}
if(result==Integer.MAX_VALUE)
result=-1;
System.out.println(result);
}
static void printMap(ArrayList<Integer> temp) {
for(int i: temp)
System.out.print(i+" ");
System.out.println();
}
static int checkEdge(ArrayList<Integer> temp) {
boolean[] visit=new boolean[N];
int line=0;
if(temp.size()==1)
return peopleCount[temp.get(0)];
for(int i=0;i<temp.size();i++) {
int[] arr=map[temp.get(i)];
// for(int j=0;j<N;j++) {
// if(temp.contains(j) && arr[j]==1) {
// visit[j]=true;
// }
// }
for(int j=0;j<temp.size();j++) {
if(i==j)
continue;
if(arr[temp.get(j)]==1) {
visit[temp.get(j)]=true;
line++;
}
}
}
if(line<(temp.size()-1)*2)
return -1;
// System.out.println(Arrays.toString(visit));
int count=0;
for(int i=0;i<temp.size();i++) {
if(!visit[temp.get(i)])
return -1;
count+=peopleCount[temp.get(i)];
}
return count;
}
class Node implements Comparable<Node>{
@Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return 0;
}
}
}
|
package HuaWei;
import java.util.ArrayList;
import java.util.Scanner;
public class 组成偶数最接近的两个素数 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int even = in.nextInt();
if (even%2==0&&even>2) {
int[] result = getOddS(even);
System.out.println(result[0]);
System.out.println(result[1]);
}
else {
System.out.println("输入错误");
}
}
in.close();
}
public static int[] getOddS(int data){
int[] result = new int[2];
int other =0;
int minDiffer=-1;
for (int i = 3; i < data/2+1; i++) {
if (isOdd(i)) {
other=data-i;
if (isOdd(other)) {
int differ = Math.abs(i-other);
if (minDiffer==-1||differ<minDiffer) {
result[0]=i;
result[1]=other;
minDiffer=differ;
}
}
}
}
return result;
}
public static boolean isOdd(int data){
boolean flag = true;
if (data<=1) {
return false;
}
for (int i = 2; i <= Math.sqrt(data); i++) {
if (data%i==0) {
flag=false;
break;
}
}
return flag;
}
}
|
package com.tencent.mm.pluginsdk.ui.tools;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.compatible.util.h;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.storage.x;
import com.tencent.mm.ui.MMActivity;
import java.io.File;
public class FileExplorerUI extends MMActivity {
private int qRR = 0;
private ListView qRS;
private a qRT;
private TextView qRU;
private TextView qRV;
private View qRW;
private View qRX;
private String qRY;
private String qRZ;
private File qSa;
private File qSb;
static /* synthetic */ int L(File file) {
return file.isDirectory() ? R.g.qqmail_attach_folder : TY(file.getName());
}
static /* synthetic */ void cfm() {
}
protected final int getLayoutId() {
return R.i.mail_file_explorer;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
String stringExtra = getIntent().getStringExtra("key_title");
if (bi.oW(stringExtra)) {
setMMTitle(R.l.plugin_qqmail_file_explorer_ui_title);
} else {
setMMTitle(stringExtra);
}
initView();
}
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
}
public void onDestroy() {
super.onDestroy();
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (i != 4 || a.a(this.qRT) == null) {
if (this.qSb != null) {
au.HU();
c.DT().set(131074, this.qSb.getAbsolutePath());
}
if (this.qSa != null) {
au.HU();
c.DT().set(131073, this.qSa.getAbsolutePath());
}
return super.onKeyDown(i, keyEvent);
}
if (1 == this.qRR) {
this.qSb = a.a(this.qRT);
} else if (this.qRR == 0) {
this.qSa = a.a(this.qRT);
}
this.qRT.g(a.a(this.qRT).getParentFile(), a.a(this.qRT));
this.qRT.notifyDataSetChanged();
this.qRS.setSelection(0);
return true;
}
protected final void initView() {
File file;
File externalStorageDirectory;
x DT;
File file2;
TextView textView;
boolean z;
TextView textView2;
boolean z2 = true;
Object obj = null;
this.qRS = (ListView) findViewById(R.h.qqmail_file_explorer_list_lv);
this.qRU = (TextView) findViewById(R.h.root_tab);
this.qRW = findViewById(R.h.root_tab_selector);
this.qRV = (TextView) findViewById(R.h.sdcard_tab);
this.qRX = findViewById(R.h.sdcard_tab_selector);
setBackBtn(new 1(this));
this.qRY = getString(R.l.plugin_qqmail_file_explorer_root_tag);
this.qRZ = getString(R.l.plugin_qqmail_file_explorer_sdcard_tag);
File rootDirectory = h.getRootDirectory();
if (rootDirectory.canRead()) {
file = rootDirectory;
} else {
rootDirectory = h.getDataDirectory();
if (rootDirectory.canRead()) {
this.qRY = rootDirectory.getName();
file = rootDirectory;
} else {
file = null;
}
}
au.HU();
if (c.isSDCardAvailable()) {
externalStorageDirectory = h.getExternalStorageDirectory();
} else {
rootDirectory = h.getDownloadCacheDirectory();
if (rootDirectory.canRead()) {
this.qRZ = rootDirectory.getName();
externalStorageDirectory = rootDirectory;
} else {
externalStorageDirectory = null;
}
}
au.HU();
String str = (String) c.DT().get(131073, file == null ? null : file.getAbsolutePath());
if (!(str == null || file == null || file.getAbsolutePath().equals(str))) {
File file3 = new File(str);
if (file3.exists()) {
rootDirectory = file3;
this.qSa = rootDirectory;
au.HU();
DT = c.DT();
if (externalStorageDirectory != null) {
obj = externalStorageDirectory.getAbsolutePath();
}
str = (String) DT.get(131074, obj);
if (!(str == null || externalStorageDirectory == null || externalStorageDirectory.getAbsolutePath().equals(str))) {
file2 = new File(str);
if (file2.exists()) {
rootDirectory = file2;
this.qSb = rootDirectory;
this.qRT = new a(this, (byte) 0);
if (externalStorageDirectory == null) {
Cv(1);
this.qRT.elx = externalStorageDirectory.getPath();
this.qRT.g(this.qSb.getParentFile(), this.qSb);
} else if (file != null) {
Cv(0);
this.qRT.elx = file.getPath();
this.qRT.g(this.qSa.getParentFile(), this.qSa);
} else {
com.tencent.mm.sdk.platformtools.x.d("MicroMsg.FileExplorerUI", "left and right tag disabled in the same time.");
return;
}
textView = this.qRU;
if (file != null) {
z = true;
} else {
z = false;
}
textView.setEnabled(z);
textView2 = this.qRV;
if (externalStorageDirectory == null) {
z2 = false;
}
textView2.setEnabled(z2);
this.qRS.setAdapter(this.qRT);
this.qRT.notifyDataSetChanged();
this.qRS.setOnItemClickListener(new 2(this));
this.qRU.setOnClickListener(new 3(this, file));
this.qRV.setOnClickListener(new OnClickListener() {
public final void onClick(View view) {
FileExplorerUI.this.Cv(1);
FileExplorerUI.this.qRT.elx = externalStorageDirectory.getPath();
FileExplorerUI.this.qRT.g(FileExplorerUI.this.qSb.getParentFile(), FileExplorerUI.this.qSb);
FileExplorerUI.this.qRT.notifyDataSetInvalidated();
FileExplorerUI.this.qRT.notifyDataSetChanged();
FileExplorerUI.this.qRS.setSelection(0);
}
});
}
}
rootDirectory = externalStorageDirectory;
this.qSb = rootDirectory;
this.qRT = new a(this, (byte) 0);
if (externalStorageDirectory == null) {
Cv(1);
this.qRT.elx = externalStorageDirectory.getPath();
this.qRT.g(this.qSb.getParentFile(), this.qSb);
} else if (file != null) {
Cv(0);
this.qRT.elx = file.getPath();
this.qRT.g(this.qSa.getParentFile(), this.qSa);
} else {
com.tencent.mm.sdk.platformtools.x.d("MicroMsg.FileExplorerUI", "left and right tag disabled in the same time.");
return;
}
textView = this.qRU;
if (file != null) {
z = false;
} else {
z = true;
}
textView.setEnabled(z);
textView2 = this.qRV;
if (externalStorageDirectory == null) {
z2 = false;
}
textView2.setEnabled(z2);
this.qRS.setAdapter(this.qRT);
this.qRT.notifyDataSetChanged();
this.qRS.setOnItemClickListener(new 2(this));
this.qRU.setOnClickListener(new 3(this, file));
this.qRV.setOnClickListener(/* anonymous class already generated */);
}
}
rootDirectory = file;
this.qSa = rootDirectory;
au.HU();
DT = c.DT();
if (externalStorageDirectory != null) {
obj = externalStorageDirectory.getAbsolutePath();
}
str = (String) DT.get(131074, obj);
file2 = new File(str);
if (file2.exists()) {
rootDirectory = file2;
this.qSb = rootDirectory;
this.qRT = new a(this, (byte) 0);
if (externalStorageDirectory == null) {
Cv(1);
this.qRT.elx = externalStorageDirectory.getPath();
this.qRT.g(this.qSb.getParentFile(), this.qSb);
} else if (file != null) {
Cv(0);
this.qRT.elx = file.getPath();
this.qRT.g(this.qSa.getParentFile(), this.qSa);
} else {
com.tencent.mm.sdk.platformtools.x.d("MicroMsg.FileExplorerUI", "left and right tag disabled in the same time.");
return;
}
textView = this.qRU;
if (file != null) {
z = true;
} else {
z = false;
}
textView.setEnabled(z);
textView2 = this.qRV;
if (externalStorageDirectory == null) {
z2 = false;
}
textView2.setEnabled(z2);
this.qRS.setAdapter(this.qRT);
this.qRT.notifyDataSetChanged();
this.qRS.setOnItemClickListener(new 2(this));
this.qRU.setOnClickListener(new 3(this, file));
this.qRV.setOnClickListener(/* anonymous class already generated */);
}
rootDirectory = externalStorageDirectory;
this.qSb = rootDirectory;
this.qRT = new a(this, (byte) 0);
if (externalStorageDirectory == null) {
Cv(1);
this.qRT.elx = externalStorageDirectory.getPath();
this.qRT.g(this.qSb.getParentFile(), this.qSb);
} else if (file != null) {
Cv(0);
this.qRT.elx = file.getPath();
this.qRT.g(this.qSa.getParentFile(), this.qSa);
} else {
com.tencent.mm.sdk.platformtools.x.d("MicroMsg.FileExplorerUI", "left and right tag disabled in the same time.");
return;
}
textView = this.qRU;
if (file != null) {
z = true;
} else {
z = false;
}
textView.setEnabled(z);
textView2 = this.qRV;
if (externalStorageDirectory == null) {
z2 = false;
}
textView2.setEnabled(z2);
this.qRS.setAdapter(this.qRT);
this.qRT.notifyDataSetChanged();
this.qRS.setOnItemClickListener(new 2(this));
this.qRU.setOnClickListener(new 3(this, file));
this.qRV.setOnClickListener(/* anonymous class already generated */);
}
private void Cv(int i) {
if (1 == i) {
this.qRR = 1;
this.qRV.setTextColor(getResources().getColor(R.e.wechat_green));
this.qRU.setTextColor(getResources().getColor(R.e.normal_text_color));
this.qRW.setVisibility(4);
this.qRX.setVisibility(0);
return;
}
this.qRR = 0;
this.qRU.setTextColor(getResources().getColor(R.e.wechat_green));
this.qRV.setTextColor(getResources().getColor(R.e.normal_text_color));
this.qRW.setVisibility(0);
this.qRX.setVisibility(4);
}
public static int TY(String str) {
Object obj = null;
String toLowerCase = str.toLowerCase();
String toLowerCase2 = bi.oV(toLowerCase).toLowerCase();
Object obj2 = (toLowerCase2.endsWith(".doc") || toLowerCase2.endsWith(".docx") || toLowerCase2.endsWith("wps")) ? 1 : null;
if (obj2 != null) {
return R.k.app_attach_file_icon_word;
}
if (TZ(toLowerCase)) {
return R.g.qqmail_attach_img;
}
toLowerCase2 = bi.oV(toLowerCase).toLowerCase();
if (toLowerCase2.endsWith(".rar") || toLowerCase2.endsWith(".zip") || toLowerCase2.endsWith(".7z") || toLowerCase2.endsWith("tar") || toLowerCase2.endsWith(".iso")) {
obj2 = 1;
} else {
obj2 = null;
}
if (obj2 != null) {
return R.k.app_attach_file_icon_rar;
}
toLowerCase2 = bi.oV(toLowerCase).toLowerCase();
if (toLowerCase2.endsWith(".txt") || toLowerCase2.endsWith(".rtf")) {
obj2 = 1;
} else {
obj2 = null;
}
if (obj2 != null) {
return R.k.app_attach_file_icon_txt;
}
if (bi.oV(toLowerCase).toLowerCase().endsWith(".pdf")) {
return R.k.app_attach_file_icon_pdf;
}
toLowerCase2 = bi.oV(toLowerCase).toLowerCase();
if (toLowerCase2.endsWith(".ppt") || toLowerCase2.endsWith(".pptx")) {
obj2 = 1;
} else {
obj2 = null;
}
if (obj2 != null) {
return R.k.app_attach_file_icon_ppt;
}
toLowerCase2 = bi.oV(toLowerCase).toLowerCase();
if (toLowerCase2.endsWith(".xls") || toLowerCase2.endsWith(".xlsx")) {
obj = 1;
}
if (obj != null) {
return R.k.app_attach_file_icon_excel;
}
return R.k.app_attach_file_icon_unknow;
}
public static boolean TZ(String str) {
String toLowerCase = bi.oV(str).toLowerCase();
return toLowerCase.endsWith(".bmp") || toLowerCase.endsWith(".png") || toLowerCase.endsWith(".jpg") || toLowerCase.endsWith(".jpeg") || toLowerCase.endsWith(".gif");
}
public static boolean Ua(String str) {
String toLowerCase = bi.oV(str).toLowerCase();
return toLowerCase.endsWith(".mp3") || toLowerCase.endsWith(".wma") || toLowerCase.endsWith(".mp4") || toLowerCase.endsWith(".rm");
}
}
|
package com.s24.redjob.mockito;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.internal.junit.JUnitRule;
import org.mockito.junit.MockitoRule;
/**
* JUnit 5 extension for Mockito.
* Replacement for {@link MockitoRule} / {@link JUnitRule}.
*/
public class MockitoExtension implements Extension, TestInstancePostProcessor, AfterEachCallback {
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
MockitoAnnotations.initMocks(testInstance);
}
@Override
public void afterEach(ExtensionContext extensionContext) {
Mockito.validateMockitoUsage();
}
}
|
package project.requestDetailsWebapp.dao;
public interface RequestDetailsDAO {
}
|
/**
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.dao.manager.bean;
import java.io.Serializable;
/**
* @ClassName: AreaBean
* @Description: 区域
* @author cy
* @date 2016-04-18 10:24:31
*/
public class AreaBean implements Serializable {
private static final long serialVersionUID = -7378006392269371711L;
/**
* 编号
**/
private Long areaId;
/**
* 区域名称
**/
private String areaName;
/**
* 序号
**/
private Integer sortNo;
/**
* 商务负责人
**/
private String businessPrincipal;
/**
* 联系电话
**/
private String contactPhone;
public AreaBean() {
super();
}
public AreaBean(Long areaId, String areaName, Integer sortNo, String businessPrincipal, String contactPhone) {
this.areaId = areaId;
this.areaName = areaName;
this.sortNo = sortNo;
this.businessPrincipal = businessPrincipal;
this.contactPhone = contactPhone;
}
public Long getAreaId() {
return areaId;
}
public void setAreaId(Long areaId) {
this.areaId = areaId;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName == null ? null : areaName.trim();
}
public Integer getSortNo() {
return sortNo;
}
public void setSortNo(Integer sortNo) {
this.sortNo = sortNo == null ? null : sortNo;
}
public String getBusinessPrincipal() {
return businessPrincipal;
}
public void setBusinessPrincipal(String businessPrincipal) {
this.businessPrincipal = businessPrincipal == null ? null : businessPrincipal.trim();
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone == null ? null : contactPhone.trim();
}
}
|
/**
* Copyright (c) 2019 Amarone- zjlgd.cn , All rights reserved.
*/
package cn.amarone.model.sys.main.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.amarone.model.sys.common.BizConst.CommonConst;
import cn.amarone.model.sys.common.response.CommRsp;
import cn.amarone.model.sys.common.util.ShiroUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
/**
* @Description:
* @Author: Amarone
* @Created Date: 2019年03月28日
* @LastModifyDate:
* @LastModifyBy:
* @Version:
*/
@Controller
public class LoginController {
@GetMapping("/login")
public String goLogin() {
return "login";
}
@PostMapping("/login")
@ResponseBody
public CommRsp login(String username, String password, String vercode) throws Exception {
if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password) || StrUtil.isEmpty(vercode)) {
return CommRsp.error("用户名/密码/验证码不能为空!");
}
Object vCode = SecurityUtils.getSubject().getSession().getAttribute(CommonConst.KAPTCHA_SESSION_KEY);
if (!vCode.equals(vercode)) {
return CommRsp.error("验证码错误!");
}
// //构建
// SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, username.getBytes());
//
// //加密为16进制表示
// String encryptHex = aes.encryptHex(password);
AuthenticationToken token = new UsernamePasswordToken(username, SecureUtil.md5(password));
try {
//尝试登陆,将会调用realm的认证方法
SecurityUtils.getSubject().login(token);
} catch (AuthenticationException e) {
if (e instanceof UnknownAccountException) {
return CommRsp.error("用户不存在");
} else if (e instanceof LockedAccountException) {
return CommRsp.error("用户被禁用");
} else if (e instanceof IncorrectCredentialsException) {
return CommRsp.error("密码错误");
} else {
return CommRsp.error("用户认证失败");
}
}
return CommRsp.success("登录成功");
}
@GetMapping("/logout")
public String logOut() {
ShiroUtil.clearCachedAuthorizationInfo();
return "index";
}
}
|
/**
* Copyright (c) 2000-2009, Jasig, Inc.
* See license distributed with this file and available online at
* https://www.ja-sig.org/svn/jasig-parent/tags/rel-10/license-header.txt
*/
package edu.wisc.jmeter.dao;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import edu.wisc.jmeter.HostStatus;
import edu.wisc.jmeter.Notification;
import edu.wisc.jmeter.Status;
/**
* @author Eric Dalquist
* @version $Revision: 1.8 $
*/
public class JdbcMonitorDao implements InitializingBean, DisposableBean, MonitorDao {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final Map<String, String> TABLE_CONFIG;
static {
final Map<String, String> tableConfigBuilder = new HashMap<String, String>();
tableConfigBuilder.put("MONITOR_HOST_STATUS",
"CREATE TABLE MONITOR_HOST_STATUS (\n" +
" HOST_NAME VARCHAR2(500),\n" +
" STATUS VARCHAR2(50) NOT NULL,\n" +
" FAILURE_COUNT NUMBER,\n" +
" MESSAGE_COUNT NUMBER,\n" +
" LAST_NOTIFICATION TIMESTAMP,\n" +
" LAST_UPDATED TIMESTAMP,\n" +
" CONSTRAINT PK_MONITOR_HOST_STATUS PRIMARY KEY (HOST_NAME)\n" +
")");
tableConfigBuilder.put("MONITOR_LOG",
"CREATE TABLE MONITOR_LOG (\n" +
" HOST_NAME VARCHAR2(500),\n" +
" LABEL VARCHAR2(2000),\n" +
" LAST_SAMPLE TIMESTAMP,\n" +
" DURATION NUMBER,\n" +
" SUCCESS VARCHAR2(10),\n" +
" CONSTRAINT PK_MONITOR_LOG PRIMARY KEY (HOST_NAME, LABEL)\n" +
")");
tableConfigBuilder.put("MONITOR_ERRORS",
"CREATE TABLE MONITOR_ERRORS (\n" +
" HOST_NAME VARCHAR2(500),\n" +
" LABEL VARCHAR2(2000),\n" +
" FAILURE_DATE TIMESTAMP,\n" +
" STATUS VARCHAR2(50),\n" +
" EMAIL_SUBJECT VARCHAR2(1000),\n" +
" EMAIL_BODY VARCHAR2(4000),\n" +
" EMAIL_SENT VARCHAR2(10)\n" +
")");
TABLE_CONFIG = Collections.unmodifiableMap(tableConfigBuilder);
}
private final ConcurrentMap<String, Object> hostMutexMap = new ConcurrentHashMap<String, Object>();
private final Map<String, HostStatus> hostStatusCache = new ConcurrentHashMap<String, HostStatus>();
private Timer purgingTimer;
//Purge times are in milliseconds
private final long purgeStatusCache = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES);
private final long purgeOldFailure;
private final long purgeOldStatus;
private final NamedParameterJdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
public JdbcMonitorDao(DataSource dataSource, int purgeOldFailures, int purgeOldStatus) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
final DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
dataSourceTransactionManager.afterPropertiesSet();
this.transactionTemplate = new TransactionTemplate(dataSourceTransactionManager);
this.transactionTemplate.afterPropertiesSet();
this.purgeOldFailure = TimeUnit.MILLISECONDS.convert(purgeOldFailures, TimeUnit.MINUTES);
this.purgeOldStatus = TimeUnit.MILLISECONDS.convert(purgeOldStatus, TimeUnit.MINUTES);
}
public JdbcMonitorDao(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager, int purgeOldFailures, int purgeOldStatus) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.purgeOldFailure = TimeUnit.MILLISECONDS.convert(purgeOldFailures, TimeUnit.MINUTES);
this.purgeOldStatus = TimeUnit.MILLISECONDS.convert(purgeOldStatus, TimeUnit.MINUTES);
}
@Override
public void afterPropertiesSet() throws Exception {
this.setupTables();
this.purgingTimer = new Timer("JdbcMonitorDao_PurgingTimer", true);
this.purgingTimer.schedule(new TimerTask() {
@Override
public void run() {
purgeFailureLog(new Date(System.currentTimeMillis() - purgeOldFailure));
purgeRequestLog(new Date(System.currentTimeMillis() - purgeOldStatus));
purgeStatusCache(new Date(System.currentTimeMillis() - purgeStatusCache)); //HostStatus objects can be rebuilt, don't hold stuff older than 5 minutes
}
},
1000 * 60, //Run 1 minute after starting
1000 * 60 * 5); //Repeat every 5 minutes
}
private void setupTables() {
final JdbcOperations jdbcOperations = this.jdbcTemplate.getJdbcOperations();
for (final Map.Entry<String, String> tableConfigEntry : TABLE_CONFIG.entrySet()) {
jdbcOperations.execute(new ConnectionCallback<Object>() {
@Override
public Object doInConnection(Connection con) throws SQLException, DataAccessException {
final DatabaseMetaData metaData = con.getMetaData();
final String tableName = tableConfigEntry.getKey();
final ResultSet tables = metaData.getTables(null, null, tableName, null);
try {
if (!tables.next()) {
log.warn("'" + tableName + "' table does not exist, creating.");
jdbcOperations.update(tableConfigEntry.getValue());
}
else {
log.info("'" + tableName + "' table already exists, skipping.");
}
}
finally {
tables.close();
}
return null;
}
});
}
}
@Override
public void destroy() throws Exception {
this.purgingTimer.cancel();
this.purgingTimer = null;
}
@Override
public void purgeStatusCache(final Date before) {
int removedStatuses = 0;
for (final Iterator<Map.Entry<String, HostStatus>> hostStatusIterator = hostStatusCache.entrySet().iterator(); hostStatusIterator.hasNext();) {
final Entry<String, HostStatus> hostStatusEntry = hostStatusIterator.next();
final HostStatus hostStatus = hostStatusEntry.getValue();
if (hostStatus.getLastUpdated().before(before)) {
hostMutexMap.remove(hostStatusEntry.getKey());
hostStatusIterator.remove();
removedStatuses++;
}
}
if (removedStatuses > 0) {
log.info("Purged " + removedStatuses + " HostStatus objects older than " + before + " from memory");
}
}
@Override
public void purgeRequestLog(final String host, final Date before) {
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("before", before);
params.put("host", host);
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
final int purgedRequests = jdbcTemplate.update(
"DELETE FROM MONITOR_LOG " +
"WHERE HOST_NAME = :host AND LAST_SAMPLE < :before",
params);
if (purgedRequests > 0) {
log.info("Purged " + purgedRequests + " requests for " + host + " older than " + before + " from database");
}
}
});
}
@Override
public void purgeRequestLog(final Date before) {
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("before", before);
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
final int purgedRequests = jdbcTemplate.update(
"DELETE FROM MONITOR_LOG " +
"WHERE LAST_SAMPLE < :before",
params);
if (purgedRequests > 0) {
log.info("Purged " + purgedRequests + " requests older than " + before + " from database");
}
final int purgedStatuses = jdbcTemplate.update(
"DELETE FROM MONITOR_HOST_STATUS " +
"WHERE LAST_UPDATED < :before",
params);
if (purgedStatuses > 0) {
log.info("Purged " + purgedStatuses + " statuses older than " + before + " from database");
}
}
});
}
@Override
public void purgeFailureLog(final Date before) {
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("before", before);
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
final int purged = jdbcTemplate.update(
"DELETE FROM MONITOR_ERRORS " +
"WHERE FAILURE_DATE < :before",
params);
if (purged > 0) {
log.info("Purged " + purged + " failures older than " + before + " from database");
}
}
});
}
@Override
public HostStatus getHostStatus(final String hostName) {
final Object lock = this.getHostLock(hostName);
synchronized (lock) {
HostStatus hostStatus = this.hostStatusCache.get(hostName);
if (hostStatus != null) {
return hostStatus;
}
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("hostName", hostName);
try {
hostStatus = this.transactionTemplate.execute(new TransactionCallback<HostStatus>() {
@Override
public HostStatus doInTransaction(TransactionStatus transactionStatus) {
final List<HostStatus> results = jdbcTemplate.query(
"SELECT STATUS, FAILURE_COUNT, MESSAGE_COUNT, LAST_NOTIFICATION, LAST_UPDATED " +
"FROM MONITOR_HOST_STATUS " +
"WHERE HOST_NAME = :hostName",
params,
new RowMapper<HostStatus>() {
@Override
public HostStatus mapRow(ResultSet rs, int row) throws SQLException {
final HostStatus hostStatus = new HostStatus();
hostStatus.setHost(hostName);
hostStatus.setStatus(Status.valueOf(rs.getString("STATUS")));
hostStatus.setFailureCount(rs.getInt("FAILURE_COUNT"));
hostStatus.setMessageCount(rs.getInt("MESSAGE_COUNT"));
hostStatus.setLastMessageSent(rs.getTimestamp("LAST_NOTIFICATION"));
hostStatus.setLastUpdated(rs.getTimestamp("LAST_UPDATED"));
return hostStatus;
}
});
HostStatus hostStatus = DataAccessUtils.singleResult(results);
if (hostStatus != null) {
return hostStatus;
}
hostStatus = new HostStatus();
hostStatus.setHost(hostName);
hostStatus.setLastUpdated(new Date());
params.put("status", hostStatus.getStatus().toString());
params.put("failureCount", hostStatus.getFailureCount());
params.put("messageCount", hostStatus.getMessageCount());
params.put("lastNotification", hostStatus.getLastMessageSent());
params.put("lastUpdated", hostStatus.getLastUpdated());
jdbcTemplate.update(
"INSERT INTO MONITOR_HOST_STATUS (HOST_NAME, STATUS, FAILURE_COUNT, MESSAGE_COUNT, LAST_NOTIFICATION, LAST_UPDATED) " +
"VALUES (:hostName, :status, :failureCount, :messageCount, :lastNotification, :lastUpdated)", params);
return hostStatus;
}
});
}
catch (RuntimeException re) {
//Want things to still work if the database is broken so create an empty HostStatus to work with in memory only
if (hostStatus == null) {
hostStatus = new HostStatus();
hostStatus.setHost(hostName);
hostStatus.setLastUpdated(new Date());
}
log.warn("Failed to retrieve/create HostStatus via database, using memory storage only", re);
}
this.hostStatusCache.put(hostName, hostStatus);
return hostStatus;
}
}
@Override
public void storeHostStatus(HostStatus hostStatus) {
hostStatus.setLastUpdated(new Date());
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("hostName", hostStatus.getHost());
params.put("status", hostStatus.getStatus().toString());
params.put("failureCount", hostStatus.getFailureCount());
params.put("messageCount", hostStatus.getMessageCount());
params.put("lastNotification", hostStatus.getLastMessageSent());
params.put("lastUpdated", hostStatus.getLastUpdated());
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
jdbcTemplate.update(
"UPDATE MONITOR_HOST_STATUS " +
"SET " +
"STATUS = :status, " +
"FAILURE_COUNT = :failureCount, " +
"MESSAGE_COUNT = :messageCount, " +
"LAST_NOTIFICATION = :lastNotification," +
"LAST_UPDATED = :lastUpdated " +
"WHERE HOST_NAME = :hostName",
params);
}
});
}
@Override
public void logFailure(String hostName, String label, Date requestTimestamp, Status status, String subject, String body, Notification sentEmail) {
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("hostName", hostName);
params.put("label", label);
params.put("failureDate", requestTimestamp);
params.put("status", status.toString());
params.put("emailSubject", subject);
params.put("emailBody", body);
params.put("emailSent", sentEmail.toString());
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
jdbcTemplate.update(
"INSERT INTO MONITOR_ERRORS (HOST_NAME, LABEL, FAILURE_DATE, STATUS, EMAIL_SUBJECT, EMAIL_BODY, EMAIL_SENT) " +
"VALUES (:hostName, :label, :failureDate, :status, :emailSubject, :emailBody, :emailSent)", params);
}
});
}
@Override
public void logRequest(String hostName, String label, Date requestTimestamp, long duration, boolean successful) {
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("hostName", hostName);
params.put("label", label);
params.put("lastSample", requestTimestamp);
params.put("successful", Boolean.toString(successful));
params.put("duration", duration);
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
final int affected = jdbcTemplate.update(
"UPDATE MONITOR_LOG " +
"SET " +
"LAST_SAMPLE = :lastSample, " +
"DURATION = :duration, " +
"SUCCESS = :successful " +
"WHERE HOST_NAME = :hostName AND LABEL = :label",
params);
if (affected == 0) {
jdbcTemplate.update(
"INSERT INTO MONITOR_LOG (HOST_NAME, LABEL, LAST_SAMPLE, DURATION, SUCCESS) " +
"VALUES (:hostName, :label, :lastSample, :duration, :successful)", params);
}
}
});
}
@Override
public void logRequestAndStatus(final HostStatus hostStatus, final String label, final Date requestTimestamp, final long duration, final boolean successful) {
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
storeHostStatus(hostStatus);
logRequest(hostStatus.getHost(), label, requestTimestamp, duration, successful);
}
});
}
@Override
public void logFailureAndStatus(final HostStatus hostStatus, final String label, final Date requestTimestamp, final Status status, final String subject, final String body, final Notification sentEmail) {
try {
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
storeHostStatus(hostStatus);
logFailure(hostStatus.getHost(), label, requestTimestamp, status, subject, body, sentEmail);
}
});
}
catch (RuntimeException re) {
log.warn("Failed to log failure and status to database", re);
}
}
protected Object getHostLock(String hostName) {
Object lock = this.hostMutexMap.get(hostName);
if (lock == null) {
lock = new Object();
final Object existingLock = this.hostMutexMap.putIfAbsent(hostName, lock);
if (existingLock != null) {
//Another thread created the lock before us, use the _one_ instance from the Map
return existingLock;
}
}
return lock;
}
protected final void clearHostStatusCache() {
this.hostStatusCache.clear();
}
}
|
package com.jincarry.request;
/**
* Created by jincarry on 16-9-21.
*/
public class Address {
public static String FIRST_LOGIN = "http://sso.njcedu.com/handleTrans.cdo?strServiceName=UserService&strTransName=SSOLogin";
//需要指定学校名称比如贵财是gzife 贵师范是gznu
public static String DO_LOGIN = "http://%s.njcedu.com/teacher/Servlet/doLogin.svl?key=%s&jsonpCallback=callback&_=%s";
public static String WATCH_VIDEO = "http://course.njcedu.com/newcourse/course.htm?courseId=%s";
public static String BEFORE_RECORD = "http://course.njcedu.com/newcourse/handleTrans.cdo?strServiceName=ViewDataService&strTransName=modifyRecentView";
public static String SAVE_RECORD = "http://course.njcedu.com/Servlet/recordStudy.svl?lCourseId=%s&lSchoolId=%s&strStartTime=%s";
public static String GET_QUESTION = "http://v.polyv.net/uc/exam/get?vid=%s";
public static String ANSWER_QUESTION = "http://v.polyv.net/uc/examlog/save";
public static String SURE_ANSWER = "http://course.njcedu.com/newcourse/handleTrans.cdo?strServiceName=StudentCourseExerciseService&strTransName=addExerciseAnswerPolyv";
//课后习题--请求题目地址
public static String QUESTION_BEFORE = "http://course.njcedu.com/questionbefore.htm?courseId=%s";
//课后习题--提交答案地址
public static String ANSWER_BEFORE_QUESTION = "http://course.njcedu.com/handleTrans.cdo?strServiceName=StudentCourseExerciseService&strTransName=addExerciseAfterAnswer";
public static String GET_VIS_LIST_DETAIL_ID = "http://%s.njcedu.com/student/prese/teachplan/list.htm";
public static String GET_VIS_FROM_TEACHPLAN = "http://%s.njcedu.com/student/prese/teachplan/listdetail.htm?id=%s";
public static String MAKESUREANSWER = "http://stat.polyv.net/log/analysis.html?pid=%s&vid=%s&movenum=1";
}
|
package org.fhcrc.honeycomb.metapop.environment;
import org.fhcrc.honeycomb.metapop.RandomNumberUser;
/**
* An unchanging environment.
*
* Created on 26 Apr, 2013
* @author Adam Waite
* @version $Rev: 2300 $, $Date: 2013-08-16 12:21:32 -0700 (Fri, 16 Aug 2013) $, $Author: ajwaite $
*/
public class StaticEnvironment implements EnvironmentChanger {
public StaticEnvironment() { super(); }
@Override
public boolean environmentChanged() { return false; }
@Override
public RandomNumberUser getRNG() { return null; }
@Override
public double getProb() { return 0.0; }
@Override
public String toString() { return "StaticEnvironment"; }
}
|
package com.pcms.controller;
import com.alibaba.fastjson.JSONObject;
import com.pcms.domain.Pageable;
import com.pcms.domain.Userinfo;
import com.pcms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user/getUser")
public String getUserInfo(Model model) throws Exception {
Map param = new HashMap();
param.put("userName", "hf");
Userinfo user = userService.getUserByParam(param);
model.addAttribute("user", user);
//构造模板引擎
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");//模板所在目录,相对于当前classloader的classpath。
resolver.setSuffix(".html");//模板文件后缀
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
//构造上下文(Model)
Context context = new Context();
context.setVariable("name", "蔬菜列表");
context.setVariable("array", new String[]{"土豆", "番茄", "白菜", "芹菜"});
//渲染模板
FileWriter write = new FileWriter("result.html");
templateEngine.process("example", context, write);
return "login";
}
@RequestMapping("/user/listView")
public ModelAndView requestListView(Model model, HttpSession session, ModelAndView mav) {
String s = (String) session.getAttribute("user");
mav.addObject("username", s);
mav.setViewName("user/list");
return mav;
}
@ResponseBody
@RequestMapping(value = "/user/list")
public JSONObject searchRequestListByParam(HttpServletRequest request, HttpServletResponse response) {
Integer draw = Integer.parseInt(request.getParameter("draw"));
Integer length = Integer.parseInt(request.getParameter("length"));
Integer start = Integer.parseInt(request.getParameter("start"));
int pageSize = length;
Map param = new HashMap();
param.put("currentPage", start);
param.put("pageSize", pageSize);
int count = userService.getUserCountByParam(param);
List<Userinfo> userinfos = userService.searchUserByParam(param);
Pageable<Userinfo> pageable = new Pageable<>();
pageable.setData(userinfos);
pageable.setDraw(draw);
pageable.setTotal(Long.parseLong(count + ""));
return JSONObject.parseObject(JSONObject.toJSONString(pageable));
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* BLookupTableDetail generated by hbm2java
*/
public class BLookupTableDetail implements java.io.Serializable {
private String uniqueid;
private String headeruid;
private String parameter1Value;
private String parameter2Value;
private String parameter3Value;
private String parameter4Value;
private String parameter5Value;
private String parameter6Value;
private String parameter7Value;
private String parameter8Value;
private String parameter9Value;
private String parameter10Value;
private String value;
public BLookupTableDetail() {
}
public BLookupTableDetail(String uniqueid, String headeruid) {
this.uniqueid = uniqueid;
this.headeruid = headeruid;
}
public BLookupTableDetail(String uniqueid, String headeruid, String parameter1Value, String parameter2Value,
String parameter3Value, String parameter4Value, String parameter5Value, String parameter6Value,
String parameter7Value, String parameter8Value, String parameter9Value, String parameter10Value,
String value) {
this.uniqueid = uniqueid;
this.headeruid = headeruid;
this.parameter1Value = parameter1Value;
this.parameter2Value = parameter2Value;
this.parameter3Value = parameter3Value;
this.parameter4Value = parameter4Value;
this.parameter5Value = parameter5Value;
this.parameter6Value = parameter6Value;
this.parameter7Value = parameter7Value;
this.parameter8Value = parameter8Value;
this.parameter9Value = parameter9Value;
this.parameter10Value = parameter10Value;
this.value = value;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public String getHeaderuid() {
return this.headeruid;
}
public void setHeaderuid(String headeruid) {
this.headeruid = headeruid;
}
public String getParameter1Value() {
return this.parameter1Value;
}
public void setParameter1Value(String parameter1Value) {
this.parameter1Value = parameter1Value;
}
public String getParameter2Value() {
return this.parameter2Value;
}
public void setParameter2Value(String parameter2Value) {
this.parameter2Value = parameter2Value;
}
public String getParameter3Value() {
return this.parameter3Value;
}
public void setParameter3Value(String parameter3Value) {
this.parameter3Value = parameter3Value;
}
public String getParameter4Value() {
return this.parameter4Value;
}
public void setParameter4Value(String parameter4Value) {
this.parameter4Value = parameter4Value;
}
public String getParameter5Value() {
return this.parameter5Value;
}
public void setParameter5Value(String parameter5Value) {
this.parameter5Value = parameter5Value;
}
public String getParameter6Value() {
return this.parameter6Value;
}
public void setParameter6Value(String parameter6Value) {
this.parameter6Value = parameter6Value;
}
public String getParameter7Value() {
return this.parameter7Value;
}
public void setParameter7Value(String parameter7Value) {
this.parameter7Value = parameter7Value;
}
public String getParameter8Value() {
return this.parameter8Value;
}
public void setParameter8Value(String parameter8Value) {
this.parameter8Value = parameter8Value;
}
public String getParameter9Value() {
return this.parameter9Value;
}
public void setParameter9Value(String parameter9Value) {
this.parameter9Value = parameter9Value;
}
public String getParameter10Value() {
return this.parameter10Value;
}
public void setParameter10Value(String parameter10Value) {
this.parameter10Value = parameter10Value;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
|
package org.zx.common.security;
import org.springframework.data.repository.CrudRepository;
public interface SessionTokenRepo extends CrudRepository<SessionToken,String> {
}
|
package com.atguigu.gmall.order.service.impl;
import com.alibaba.fastjson.JSON;
import com.atguigu.core.bean.Resp;
import com.atguigu.core.exception.OrderExeption;
import com.atguigu.gamll.cart.entity.Cart;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.vo.OrderItemVO;
import com.atguigu.gmall.oms.vo.OrderSubmitVO;
import com.atguigu.gmall.order.entity.UserInfo;
import com.atguigu.gmall.order.feign.*;
import com.atguigu.gmall.order.interceptor.LoginInterceptor;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.order.vo.OrderConfirmVO;
import com.atguigu.gmall.pms.entity.SkuInfoEntity;
import com.atguigu.gmall.pms.entity.SkuSaleAttrValueEntity;;
import com.atguigu.gmall.sms.vo.ItemSaleVO;
import com.atguigu.gmall.ums.entity.MemberEntity;
import com.atguigu.gmall.ums.entity.MemberReceiveAddressEntity;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.atguigu.gmall.wms.vo.SkuLockVO;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private GmallWmsFeign gmallWmsFeign;
@Autowired
private GmallPmsFeign gmallPmsFeign;
@Autowired
private GmallSmsFeign gmallSmsFeign;
@Autowired
private GmallUmsFeign gmallUmsFeign;
@Autowired
private GmallCartFeign gmallCartFeign;
@Autowired
private GmallOmsFeign gmallOmsFeign;
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final String ORDERKEY_PREFIX = "order:token:";
//private static final String CART_PREFIX = "cart:uid:"; //用户key的前缀
@Autowired
private ThreadPoolExecutor threadPoolExecutor;
@Autowired
private AmqpTemplate amqpTemplate;
/**
* 查询需要从购物车到结算页面的数据
*
* @return
*/
@Override
public OrderConfirmVO confirm() {
OrderConfirmVO orderConfirmVO=new OrderConfirmVO();
//1、先获取用户登入的信息。只有用户登入了,才有趣结算功能
UserInfo userInfo = LoginInterceptor.getUserInfo();
Long userId = userInfo.getUserId();
if (userId == null) { //记住如果判断一个null。自定义异常
throw new OrderExeption("用户登入已经过期");
}
//2、订单详细的查询
CompletableFuture<Void> cartFuture = CompletableFuture.supplyAsync(() -> {
// 远程调用,查询购物车好选中的状态所以商品
Resp<List<Cart>> listResp = this.gmallCartFeign.queryCarts(userId);
List<Cart> carts = listResp.getData();
return carts;
},threadPoolExecutor).thenAcceptAsync(carts -> {
//2.2 获取销售信息items
List<OrderItemVO> items = carts.stream().map(cart -> {
//创建商品详细VO
OrderItemVO orderItemVO = new OrderItemVO();
CompletableFuture<SkuInfoEntity> skuFuture = CompletableFuture.supplyAsync(() -> {
//通过通过获取到的商品
Resp<SkuInfoEntity> skuInfoEntityResp = this.gmallPmsFeign.querysSkuById(cart.getSkuId());
SkuInfoEntity skuInfoEntity = skuInfoEntityResp.getData();
if (skuInfoEntity != null) {
orderItemVO.setSkuId(skuInfoEntity.getSkuId());
orderItemVO.setTitle(skuInfoEntity.getSkuTitle());
orderItemVO.setImgae(skuInfoEntity.getSkuDefaultImg());
orderItemVO.setPrice(skuInfoEntity.getPrice());
orderItemVO.setWeight(skuInfoEntity.getWeight());
orderItemVO.setCount(cart.getCount());
}
return skuInfoEntity;
},threadPoolExecutor);
//查询sku销售信息,cart的 的skuId查询
CompletableFuture<Void> saleAttrFuture = skuFuture.thenAcceptAsync(skuInfoEntity -> {
if (skuInfoEntity != null) {
Resp<List<SkuSaleAttrValueEntity>> listResp = this.gmallPmsFeign.querySkuBySkuId(cart.getSkuId());
List<SkuSaleAttrValueEntity> skuSaleAttrValueEntitys = listResp.getData();
orderItemVO.setSaleAttrs(skuSaleAttrValueEntitys);
}
},threadPoolExecutor);
//查询营销信息通过
// private List<ItemSaleVO> sales; //营销属性
CompletableFuture<Void> itemSaleVOFuture = skuFuture.thenAcceptAsync(skuInfoEntity -> {
if (skuInfoEntity != null) {
Resp<List<ItemSaleVO>> listResp = this.gmallSmsFeign.queryItemSaleBySkuId(cart.getSkuId());
List<ItemSaleVO> itemSaleVO = listResp.getData();
orderItemVO.setSales(itemSaleVO);
}
},threadPoolExecutor);
//是否有货
CompletableFuture<Void> stockFuture = skuFuture.thenAcceptAsync(skuInfoEntity -> {
if (skuInfoEntity != null) {
Resp<List<WareSkuEntity>> listResp = this.gmallWmsFeign.queryWareSkusBySkuId(cart.getSkuId());
List<WareSkuEntity> wareSkuEntity = listResp.getData();
if (!CollectionUtils.isEmpty(wareSkuEntity)) {
boolean flag = wareSkuEntity.stream().anyMatch(ware -> ware.getStock() > 0);
orderItemVO.setStore(flag);
}
}
},threadPoolExecutor);
//执行
CompletableFuture.allOf(saleAttrFuture,itemSaleVOFuture,stockFuture).join();
return orderItemVO;
}).collect(Collectors.toList());
orderConfirmVO.setItems(items);
},threadPoolExecutor);
//2、获取收货地址
CompletableFuture<Void> meAddressFuture = CompletableFuture.runAsync(() -> {
Resp<List<MemberReceiveAddressEntity>> listResp = this.gmallUmsFeign.queryAddressesByUserId(userId);
List<MemberReceiveAddressEntity> memberReceiveAddressEntity = listResp.getData();
orderConfirmVO.setAddress(memberReceiveAddressEntity);
},threadPoolExecutor);
//3、获取到积分
CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
Resp<MemberEntity> memberEntityResp = this.gmallUmsFeign.queryMemberById(userId);
MemberEntity memberEntity = memberEntityResp.getData();
if (memberEntity != null) {
orderConfirmVO.setBounds(memberEntity.getIntegration());
}
},threadPoolExecutor);
//4、防止重复防止重复提交 生成唯一的token
//把提交的token保存到redis。如果
CompletableFuture<Void> tokenFuture = CompletableFuture.runAsync(() -> {
String orderToken = IdWorker.getTimeId();
orderConfirmVO.setOrderToken(orderToken);
this.stringRedisTemplate.opsForValue().set(ORDERKEY_PREFIX + orderToken, orderToken, 3, TimeUnit.HOURS);
},threadPoolExecutor);
CompletableFuture.allOf(cartFuture,meAddressFuture,memberFuture,tokenFuture).join();
return orderConfirmVO;
}
//提交
@Override
public void toSubmit(OrderSubmitVO submitVO) {
//1、校验是否重复提交、原子性
String orderToken = submitVO.getOrderToken();
String script = "if redis.call('get', KEYS[1]) == ARGV[1] " +
"then return redis.call('del', KEYS[1]) " +
"else return 0 end";
Boolean flag = this.stringRedisTemplate
.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(ORDERKEY_PREFIX + orderToken), orderToken);
System.out.println("flag = " + flag);
//获取到的redis中的orderToken和我提交的一样
if(!flag){
throw new OrderExeption("您多次提交,请重新提交");
}
//2、校验商品的价格
BigDecimal totalPrice = submitVO.getTotalPrice(); //商品总价
List<OrderItemVO> items = submitVO.getItems();//获取确认页面商品详情
if(CollectionUtils.isEmpty(items)){
throw new OrderExeption("您还没选中商品,请选中需要购买的商品!");
}
//遍历商品的订单详情,获取数据库的价格,计算实时价格
BigDecimal currentPrice = items.stream().map(item -> {
//远程调用查询skuInfo
Resp<SkuInfoEntity> skuInfoEntityResp = this.gmallPmsFeign.querysSkuById(item.getSkuId());
SkuInfoEntity skuInfoEntity = skuInfoEntityResp.getData();
if (skuInfoEntity != null) {
//计算价格所有商品的的总价格
return skuInfoEntity.getPrice().multiply(item.getCount());
}
return new BigDecimal(0);
}).reduce((t1, t2) -> t1.add(t2)).get();
//-1 0 1
if (totalPrice.compareTo(currentPrice) !=0){
throw new OrderExeption("页面已经过期,请刷新页面!");
}
//3、校验商品的库存并锁定库存
List<SkuLockVO> skuLockVOS = items.stream().map(orderItemVO -> {
SkuLockVO skuLockVO = new SkuLockVO();
skuLockVO.setSkuId(orderItemVO.getSkuId());
skuLockVO.setCount(orderItemVO.getCount().intValue());
skuLockVO.setOrderToken(submitVO.getOrderToken());
return skuLockVO;
}).collect(Collectors.toList());
Resp<List<SkuLockVO>> listResp = this.gmallWmsFeign.checkAndLock(skuLockVOS);
List<SkuLockVO> skuLockVO = listResp.getData();
if (!CollectionUtils.isEmpty(skuLockVO)){
throw new OrderExeption("商品库存不足!"+ JSON.toJSONString(skuLockVO));
}
//4下单操作远程调用
UserInfo userInfo = LoginInterceptor.getUserInfo();
Long userId = userInfo.getUserId();
submitVO.setUserId(userId);
//保存订单
try {
Resp<OrderEntity> orderEntityResp = this.gmallOmsFeign.saveOrder(submitVO);
} catch (Exception e) {
e.printStackTrace();
//如果订单创建失败。立即释放库存 todo
this.amqpTemplate.convertAndSend("ORDER-EXCHANGE","wms.unlock",orderToken);
}
//5、下单成功后,使用消息队列删除购物车对应的商品信息.(userId,skuIds)
HashMap<Object, Object> map = new HashMap<>();
map.put("userId",userId);
// items是订单详情。可以通过订单详情获取每个skuId
List<Long> skuIds = items.stream().map(OrderItemVO::getSkuId).collect(Collectors.toList());
map.put("skuIds", JSON.toJSONString(skuIds) );
this.amqpTemplate.convertAndSend("ORDER-EXCHANGE","cart.delete",map);
//TODO 需要返回下单的信息,需要从保存订单获取需要用户支付多少内容。
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.grinder.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Collection Utility class.
*
* @author JunHo Yoon
* @since 1.0
*/
public abstract class CollectionUtils {
/**
* Convenient method to create {@link ArrayList} instance.
*
* @param <T>
* type
* @return new {@link ArrayList}
*/
public static <T> ArrayList<T> newArrayList() {
return new ArrayList<T>();
}
/**
* Convenient method to create {@link HashSet} instance.
*
* @param <T>
* type
* @return new {@link HashSet}
*/
public static <T> Set<T> newHashSet() {
return new HashSet<T>();
}
/**
* Convenient method to create {@link HashMap} instance.
*
* @param <K>
* key type
* @param <V>
* value type
* @return new {@link HashMap}
*/
public static <K, V> Map<K, V> newHashMap() {
return new HashMap<K, V>();
}
/**
* Convenient method to create {@link ConcurrentHashMap} instance.
*
* @param <K>
* key type
* @param <V>
* value type
* @return new {@link HashMap}
*/
public static <K, V> Map<K, V> newConcurrentHashMap() {
return new ConcurrentHashMap<K, V>();
}
/**
* Convenient method to create {@link IdentityHashMap} instance.
*
* @param <K>
* key type
* @param <V>
* value type
* @return created {@link IdentityHashMap}
*/
public static <K, V> Map<K, V> newIdentityHashMap() {
return new IdentityHashMap<K, V>();
}
}
|
/*
* 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 WhateverPaint;
import Shapes.Shapes;
import Tools.Resizer;
import ToolsPanels.Canvas;
import ToolsPanels.CustomButtonStyle;
import ToolsPanels.EditBox;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import static java.awt.SystemColor.menu;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicMenuBarUI;
public class MainWindow extends javax.swing.JFrame {
public static JButton old;
public MainWindow() {
initComponents();
this.setTitle("Paint");
editBox1.setCanvas(canvas1);
mainButtonGroup1.setCc(canvas1);
setLocationRelativeTo(null);
stroker.setValue(1);
getContentPane().setBackground(new Color(83, 83, 83));
menu.setUI(new BasicMenuBarUI() {
public void paint(Graphics g, JComponent c) {
g.setColor(new Color(40, 40, 40));
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
});
canvas1.setFocusable(true);
canvas1.requestFocusInWindow();
setIcon();
}
public static void setPosition(String s) {
position.setText(s);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
canvas1 = new ToolsPanels.Canvas();
jPanel1 = new javax.swing.JPanel();
position = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
colorStrip1 = new ToolsPanels.ColorStrip();
mainButtonGroup1 = new ToolsPanels.MainButtonGroup();
toolBoxs1 = new ToolsPanels.ToolBoxs();
editBox1 = new ToolsPanels.EditBox();
colorBoxes1 = new ToolsPanels.ColorBoxes();
stroker = new javax.swing.JSlider();
menu = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem6 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
Edit = new javax.swing.JMenu();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
formKeyReleased(evt);
}
});
canvas1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
canvas1MouseClicked(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
canvas1MouseReleased(evt);
}
});
canvas1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
canvas1KeyPressed(evt);
}
});
javax.swing.GroupLayout canvas1Layout = new javax.swing.GroupLayout(canvas1);
canvas1.setLayout(canvas1Layout);
canvas1Layout.setHorizontalGroup(
canvas1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1142, Short.MAX_VALUE)
);
canvas1Layout.setVerticalGroup(
canvas1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 428, Short.MAX_VALUE)
);
jPanel1.setBackground(new java.awt.Color(40, 40, 40));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
position.setForeground(new java.awt.Color(255, 255, 255));
position.setText("Mouse");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(position)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(position))
);
jPanel2.setBackground(new java.awt.Color(40, 40, 40));
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, new java.awt.Color(40, 40, 40)));
jPanel2.setForeground(new java.awt.Color(40, 40, 40));
jPanel2.setToolTipText("");
stroker.setMaximum(20);
stroker.setMinimum(1);
stroker.setToolTipText("Size");
stroker.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
strokerStateChanged(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(mainButtonGroup1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(editBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(toolBoxs1, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(colorBoxes1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(stroker, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(64, 64, 64)
.addComponent(colorStrip1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(toolBoxs1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(mainButtonGroup1, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
.addComponent(editBox1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(colorStrip1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(stroker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(colorBoxes1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jMenu1.setForeground(new java.awt.Color(255, 255, 255));
jMenu1.setText("File");
jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
entered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
exited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
pressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
released(evt);
}
});
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("Open");
jMenuItem2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
entered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
exited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
pressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
released(evt);
}
});
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Save");
jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
entered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
exited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
pressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
released(evt);
}
});
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenu2.setText("Export as");
jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem6.setText("PNG");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem6);
jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem7.setText("GIF");
jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem7ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem7);
jMenu1.add(jMenu2);
jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItem3.setText("Exit");
jMenuItem3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
entered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
exited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
pressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
released(evt);
}
});
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
menu.add(jMenu1);
Edit.setForeground(new java.awt.Color(255, 255, 255));
Edit.setText("Edit");
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem4.setText("Undo");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
Edit.add(jMenuItem4);
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem5.setText("Redo");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
Edit.add(jMenuItem5);
menu.add(Edit);
setJMenuBar(menu);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(canvas1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void canvas1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_canvas1MouseClicked
}//GEN-LAST:event_canvas1MouseClicked
private void canvas1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_canvas1MouseReleased
old.doClick();
editBox1.undo.setEnabled(true);
canvas1.setFocusable(true);
canvas1.requestFocusInWindow();
}//GEN-LAST:event_canvas1MouseReleased
private void canvas1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_canvas1KeyPressed
}//GEN-LAST:event_canvas1KeyPressed
private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased
}//GEN-LAST:event_formKeyReleased
private void strokerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_strokerStateChanged
Canvas.setStroke(stroker.getValue());
}//GEN-LAST:event_strokerStateChanged
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
mainButtonGroup1.open.doClick();
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
System.exit(0);
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void exited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exited
}//GEN-LAST:event_exited
private void entered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_entered
}//GEN-LAST:event_entered
private void released(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_released
}//GEN-LAST:event_released
private void pressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pressed
}//GEN-LAST:event_pressed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
mainButtonGroup1.save.doClick();
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
EditBox.undo.doClick();
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
EditBox.redo.doClick();
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
BufferedImage image= saveImage(canvas1);
JFileChooser file = new JFileChooser();
if(file.showOpenDialog(menu)==JFileChooser.APPROVE_OPTION){
try{
ImageIO.write(image, "PNG", file.getSelectedFile());
}
catch(Exception e){
e.printStackTrace();
}
}
}//GEN-LAST:event_jMenuItem6ActionPerformed
private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
BufferedImage image= saveImage(canvas1);
JFileChooser file = new JFileChooser();
if(file.showOpenDialog(menu)==JFileChooser.APPROVE_OPTION){
try{
ImageIO.write(image, "gif", file.getSelectedFile());
}
catch(Exception e){
e.printStackTrace();
}
}
}//GEN-LAST:event_jMenuItem7ActionPerformed
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu Edit;
private ToolsPanels.Canvas canvas1;
private ToolsPanels.ColorBoxes colorBoxes1;
private ToolsPanels.ColorStrip colorStrip1;
private ToolsPanels.EditBox editBox1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private ToolsPanels.MainButtonGroup mainButtonGroup1;
private javax.swing.JMenuBar menu;
private static javax.swing.JLabel position;
private javax.swing.JSlider stroker;
private ToolsPanels.ToolBoxs toolBoxs1;
// End of variables declaration//GEN-END:variables
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("icon256.png")));
}
public BufferedImage saveImage(JPanel panel){
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
panel.print(g2);
return bi;
}
}
|
package com.itheima.redbaby.bean.goodsentry;
import java.util.List;
import com.itheima.redbaby.bean.Product;
/**
* 商品列表的bean
*/
public class GoodsTabulation {
private String response;
private int list_count;
private List<Product> productlist;
public GoodsTabulation(String response, int list_count, List<Product> productlist) {
super();
this.response = response;
this.list_count = list_count;
this.productlist = productlist;
}
public GoodsTabulation() {
super();
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public int getList_count() {
return list_count;
}
public void setList_count(int list_count) {
this.list_count = list_count;
}
public List<Product> getProductlist() {
return productlist;
}
public void setProductlist(List<Product> productlist) {
this.productlist = productlist;
}
}
|
package com.github.baloise.rocketchatrestclient.model;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents the status of this user, both their connection and their displayed one.
*
* @author Bradley Hilton (graywolf336)
* @since 0.1.0
* @version 0.0.1
*/
public enum UserStatus {
@JsonProperty("online")
ONLINE,
@JsonProperty("offline")
OFFLINE,
@JsonProperty("away")
AWAY,
@JsonProperty("busy")
BUSY;
}
|
/*
* Aipo is a groupware program developed by Aimluck,Inc.
* Copyright (C) 2004-2015 Aimluck,Inc.
* http://www.aipo.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aimluck.eip.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.cayenne.DataRow;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.capability.CapabilityMap;
import org.apache.jetspeed.capability.CapabilityMapFactory;
import org.apache.jetspeed.om.profile.Entry;
import org.apache.jetspeed.om.profile.Layout;
import org.apache.jetspeed.om.profile.PSMLDocument;
import org.apache.jetspeed.om.profile.Parameter;
import org.apache.jetspeed.om.profile.Portlets;
import org.apache.jetspeed.om.profile.Profile;
import org.apache.jetspeed.om.profile.ProfileException;
import org.apache.jetspeed.om.profile.ProfileLocator;
import org.apache.jetspeed.om.profile.psml.PsmlLayout;
import org.apache.jetspeed.om.profile.psml.PsmlParameter;
import org.apache.jetspeed.om.registry.ClientEntry;
import org.apache.jetspeed.om.registry.ClientRegistry;
import org.apache.jetspeed.om.registry.MediaTypeEntry;
import org.apache.jetspeed.om.security.Role;
import org.apache.jetspeed.om.security.UserIdPrincipal;
import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.portal.PortletConfig;
import org.apache.jetspeed.portal.portlets.VelocityPortlet;
import org.apache.jetspeed.portal.security.portlets.PortletWrapper;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.PortletFactory;
import org.apache.jetspeed.services.Profiler;
import org.apache.jetspeed.services.PsmlManager;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.util.MimeType;
import org.apache.jetspeed.util.template.BaseJetspeedLink;
import org.apache.jetspeed.util.template.ContentTemplateLink;
import org.apache.jetspeed.util.template.JetspeedLink;
import org.apache.jetspeed.util.template.JetspeedLinkFactory;
import org.apache.turbine.om.security.User;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.util.DynamicURI;
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.TurbineException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import com.aimluck.commons.field.ALDateTimeField;
import com.aimluck.commons.field.ALStringField;
import com.aimluck.eip.cayenne.om.account.AipoLicense;
import com.aimluck.eip.cayenne.om.account.EipMCompany;
import com.aimluck.eip.cayenne.om.account.EipMUserPosition;
import com.aimluck.eip.cayenne.om.portlet.EipMFacilityGroup;
import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALBaseUser;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALEipGroup;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALEipUser;
import com.aimluck.eip.common.ALMyGroups;
import com.aimluck.eip.common.ALPermissionException;
import com.aimluck.eip.http.HttpServletRequestLocator;
import com.aimluck.eip.modules.actions.controls.Restore;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.Operations;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.services.accessctl.ALAccessControlConstants;
import com.aimluck.eip.services.accessctl.ALAccessControlFactoryService;
import com.aimluck.eip.services.accessctl.ALAccessControlHandler;
import com.aimluck.eip.services.config.ALConfigHandler.Property;
import com.aimluck.eip.services.config.ALConfigService;
/**
* Aimluck EIP のユーティリティクラスです。 <br />
*
*/
public class ALEipUtils {
public static final String dummy_user_head = "dummy_";
/** logger */
private static final JetspeedLogger logger = JetspeedLogFactoryService
.getLogger(ALEipUtils.class.getName());
// iPhone メニューを表示させたい順番に並べる
// TODO: 設定ファイルで管理して VM と統合する
public static String[] IPHONE_APPS = {
"Timeline",
"Schedule",
"ExtTimecard",
"Activity",
"Blog",
"Msgboard",
"ToDo",
"Cabinet",
"Workflow",
"Note",
"Report",
"WebMail",
"AddressBook",
"UserList",
"Memo" };
/**
* セッション変数に値を格納します。 <br />
* セッション変数は各ポートレット毎に管理されます。
*
* @param rundata
* @param context
* @param key
* セッション変数名
* @param value
* セッション変数の値
*/
public static void setTemp(RunData rundata, Context context, String key,
String value) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
VelocityPortlet portlet =
((VelocityPortlet) context.get(JetspeedResources.PATH_PORTLET_KEY));
if (portlet == null) {
// Screen の場合
String js_peid =
rundata.getParameters().getString(JetspeedResources.PATH_PORTLETID_KEY);
jdata.getUser().setTemp(
new StringBuffer().append(js_peid).append(key).toString(),
value);
} else {
// Action の場合
jdata.getUser().setTemp(
new StringBuffer().append(portlet.getID()).append(key).toString(),
value);
}
}
/**
* セッション変数を削除します。 <br />
* セッション変数は各ポートレット毎に管理されます。
*
* @param rundata
* @param context
* @param key
* セッション変数名
*/
public static void removeTemp(RunData rundata, Context context, String key) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
VelocityPortlet portlet =
((VelocityPortlet) context.get(JetspeedResources.PATH_PORTLET_KEY));
if (portlet == null) {
// Screen の場合
String js_peid =
rundata.getParameters().getString(JetspeedResources.PATH_PORTLETID_KEY);
jdata.getUser().removeTemp(
new StringBuffer().append(js_peid).append(key).toString());
} else {
// Action の場合
jdata.getUser().removeTemp(
new StringBuffer().append(portlet.getID()).append(key).toString());
}
}
public static void removeTemp(RunData rundata, Context context,
List<String> list) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
VelocityPortlet portlet =
((VelocityPortlet) context.get(JetspeedResources.PATH_PORTLET_KEY));
int size = list.size();
if (portlet == null) {
// Screen の場合
String js_peid =
rundata.getParameters().getString(JetspeedResources.PATH_PORTLETID_KEY);
for (int i = 0; i < size; i++) {
jdata.getUser().removeTemp(
new StringBuffer()
.append(js_peid)
.append(list.get(i).toString())
.toString());
}
} else {
// Action の場合
String peid = portlet.getID();
for (int i = 0; i < size; i++) {
jdata.getUser().removeTemp(
new StringBuffer()
.append(peid)
.append(list.get(i).toString())
.toString());
}
}
}
/**
* セッション変数の値を取得します。 <br />
* セッション変数は各ポートレット毎に管理されます。
*
* @param rundata
* @param context
* @param key
* セッション変数名
* @return セッション変数の値
*/
public static String getTemp(RunData rundata, Context context, String key) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
Object obj = null;
VelocityPortlet portlet =
((VelocityPortlet) context.get(JetspeedResources.PATH_PORTLET_KEY));
if (portlet == null) {
// Screen の場合
String js_peid =
rundata.getParameters().getString(JetspeedResources.PATH_PORTLETID_KEY);
obj =
jdata.getUser().getTemp(
new StringBuffer().append(js_peid).append(key).toString());
} else {
// Action の場合
obj =
jdata.getUser().getTemp(
new StringBuffer().append(portlet.getID()).append(key).toString());
}
return (obj == null) ? null : obj.toString();
}
/**
* セッションに保存されているエンティティIDを整数値として返します。
*
* @param rundata
* @param context
* @return
*/
public static int getEntityId(RunData rundata, Context context) {
int entity_id = 0;
String entity_id_str =
ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
try {
entity_id = Integer.parseInt(entity_id_str);
} catch (Exception e) {
entity_id = 0;
}
return entity_id;
}
/**
* ユーザーIDを返します。
*
* @param rundata
* @return ユーザーID
*/
public static int getUserId(RunData rundata) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
String id = jdata.getJetspeedUser().getUserId();
return Integer.parseInt(id);
}
/**
* ポートレットを返します。
*
* @param rundata
* @param context
* @return 自ポートレット
*/
public static VelocityPortlet getPortlet(RunData rundata, Context context) {
return ((VelocityPortlet) context.get(JetspeedResources.PATH_PORTLET_KEY));
}
/**
* 指定したポートレット ID を持つポートレットのオブジェクトを取得します。
*
* @param rundata
* @param portletId
* @return 自ポートレット
*/
public static Portlet getPortlet(RunData rundata, String portletId) {
try {
Profile profile = ((JetspeedRunData) rundata).getProfile();
if (profile == null) {
return null;
}
Portlets portlets = profile.getDocument().getPortlets();
if (portlets == null) {
return null;
}
@SuppressWarnings("unchecked")
Iterator<Entry> iterator = portlets.getEntriesIterator();
while (iterator.hasNext()) {
Entry next = iterator.next();
if (portletId.equals(next.getId())) {
PortletWrapper activityWrapper =
(PortletWrapper) PortletFactory.getPortlet(next);
if (activityWrapper != null) {
return activityWrapper.getPortlet();
}
}
}
Portlets[] portletList = portlets.getPortletsArray();
if (portletList == null) {
return null;
}
int length = portletList.length;
for (int i = 0; i < length; i++) {
Entry[] entries = portletList[i].getEntriesArray();
if (entries == null || entries.length <= 0) {
continue;
}
int ent_length = entries.length;
for (int j = 0; j < ent_length; j++) {
if (entries[j].getId().equals(portletId)) {
PortletWrapper wrapper =
(PortletWrapper) PortletFactory.getPortlet(entries[j]);
if (wrapper != null) {
return wrapper.getPortlet();
} else {
return null;
}
}
}
}
} catch (Exception ex) {
logger.error("ALEipUtils.getPortlet", ex);
return null;
}
return null;
}
/**
* 指定したポートレット ID を持つポートレットのオブジェクトを取得します。
*
* @param rundata
* @param portletId
* @return 自ポートレット
*/
public static HashMap<String, String> getPortletFromAppIdMap(RunData rundata) {
HashMap<String, String> hash = new HashMap<String, String>();
try {
Portlets portlets =
((JetspeedRunData) rundata).getProfile().getDocument().getPortlets();
if (portlets == null) {
return hash;
}
for (@SuppressWarnings("unchecked")
Iterator<Entry> it = portlets.getEntriesIterator(); it.hasNext();) {
Entry next = it.next();
if (!hash.containsKey(next.getParent())) {
hash.put(next.getParent(), next.getId());
}
}
{
Portlets[] portletList = portlets.getPortletsArray();
if (portletList == null) {
return hash;
}
for (Portlets portlet : portletList) {
Entry[] entries = portlet.getEntriesArray();
if (entries == null) {
continue;
}
for (Entry entry : entries) {
hash.put(entry.getParent(), entry.getId());
}
}
}
} catch (Exception ex) {
logger.error("ALEipUtils.getPortletFromAppIdMap", ex);
return hash;
}
return hash;
}
/**
* リクエストが自ポートレットに対するものであるかを返します。 <br />
* true となる場合、そのポートレットに対するフォーム送信となります。
*
* @param rundata
* @param context
* @return
*/
public static boolean isMatch(RunData rundata, Context context) {
VelocityPortlet portlet = getPortlet(rundata, context);
if (portlet == null) {
// Screen の場合
return true;
}
String peid1 = portlet.getID();
String peid2 =
rundata.getParameters().getString(JetspeedResources.PATH_PORTLETID_KEY);
if (peid1 == null || peid2 == null) {
return false;
}
return peid1.equals(peid2);
}
/**
* 指定されたグループに所属するユーザーを取得します。<br/>
* DISABLEDがNのユーザー(即ち無効化されたユーザー)は取得しないことに注意してください。
*
* @param groupname
* グループ名
* @return ALEipUser の List
*/
public static List<ALEipUser> getUsers(String groupname) {
List<ALEipUser> list = new ArrayList<ALEipUser>();
// SQLの作成
StringBuffer statement = new StringBuffer();
statement.append("SELECT DISTINCT ");
statement
.append(" B.USER_ID, B.LOGIN_NAME, B.FIRST_NAME, B.LAST_NAME, D.POSITION ");
statement.append("FROM turbine_user_group_role as A ");
statement.append("LEFT JOIN turbine_user as B ");
statement.append(" on A.USER_ID = B.USER_ID ");
statement.append("LEFT JOIN turbine_group as C ");
statement.append(" on A.GROUP_ID = C.GROUP_ID ");
statement.append("LEFT JOIN eip_m_user_position as D ");
statement.append(" on A.USER_ID = D.USER_ID ");
statement.append("WHERE B.USER_ID > 3 AND B.DISABLED = 'F'");
statement.append(" AND C.GROUP_NAME = #bind($groupName) ");
statement.append("ORDER BY D.POSITION");
String query = statement.toString();
try {
List<TurbineUser> list2 =
Database
.sql(TurbineUser.class, query)
.param("groupName", groupname)
.fetchList();
for (TurbineUser tuser : list2) {
list.add(getALEipUser(tuser));
}
} catch (Throwable t) {
logger.error("ALEipUtils.getUsers", t);
}
return list;
}
/**
* 指定されたグループに所属するユーザーを取得します。<br/>
* DISABLEDがNのユーザー(即ち無効化されたユーザー)も取得します。
*
* @param groupname
* グループ名
* @return ALEipUser の List
*/
public static List<ALEipUser> getUsersIncludingN(String groupname) {
List<ALEipUser> list = new ArrayList<ALEipUser>();
// SQLの作成
StringBuffer statement = new StringBuffer();
statement.append("SELECT DISTINCT ");
statement
.append(" B.USER_ID, B.LOGIN_NAME, B.FIRST_NAME, B.LAST_NAME, D.POSITION ");
statement.append("FROM turbine_user_group_role as A ");
statement.append("LEFT JOIN turbine_user as B ");
statement.append(" on A.USER_ID = B.USER_ID ");
statement.append("LEFT JOIN turbine_group as C ");
statement.append(" on A.GROUP_ID = C.GROUP_ID ");
statement.append("LEFT JOIN eip_m_user_position as D ");
statement.append(" on A.USER_ID = D.USER_ID ");
statement.append("WHERE B.USER_ID > 3 AND B.DISABLED != 'T'");
statement.append(" AND C.GROUP_NAME = #bind($groupName) ");
statement.append("ORDER BY D.POSITION");
String query = statement.toString();
try {
List<TurbineUser> list2 =
Database
.sql(TurbineUser.class, query)
.param("groupName", groupname)
.fetchList();
for (TurbineUser tuser : list2) {
list.add(getALEipUser(tuser));
}
} catch (Throwable t) {
logger.error("ALEipUtils.getUsersIncludingN", t);
}
return list;
}
/**
* 指定されたグループに所属するユーザーのIDを取得します。
*
* @param groupname
* グループ名
* @return Integer の List
*/
public static List<Integer> getUserIds(String groupname) {
List<Integer> list = new ArrayList<Integer>();
// SQLの作成
StringBuffer statement = new StringBuffer();
statement.append("SELECT DISTINCT ");
statement.append(" B.USER_ID, D.POSITION ");
statement.append("FROM turbine_user_group_role as A ");
statement.append("LEFT JOIN turbine_user as B ");
statement.append(" on A.USER_ID = B.USER_ID ");
statement.append("LEFT JOIN turbine_group as C ");
statement.append(" on A.GROUP_ID = C.GROUP_ID ");
statement.append("LEFT JOIN eip_m_user_position as D ");
statement.append(" on A.USER_ID = D.USER_ID ");
statement.append("WHERE B.USER_ID > 3 AND B.DISABLED = 'F'");
statement.append(" AND C.GROUP_NAME = #bind($groupName) ");
statement.append("ORDER BY D.POSITION");
String query = statement.toString();
try {
List<TurbineUser> list2 =
Database
.sql(TurbineUser.class, query)
.param("groupName", groupname)
.fetchList();
for (TurbineUser tuser : list2) {
list.add(tuser.getUserId());
}
} catch (Throwable t) {
logger.error("ALEipUtils.getUsersFromPost", t);
}
return list;
}
/**
* 指定された部署に所属するユーザーを取得します。
*
* @param postid
* 部署ID
* @return ALEipUser の List
*/
public static List<ALEipUser> getUsersFromPost(int postid) {
List<ALEipUser> list = new ArrayList<ALEipUser>();
// SQLの作成
StringBuffer statement = new StringBuffer();
statement.append("SELECT DISTINCT ");
statement
.append(" B.USER_ID, B.LOGIN_NAME, B.FIRST_NAME, B.LAST_NAME, D.POSITION ");
statement.append("FROM turbine_user_group_role as A ");
statement.append("LEFT JOIN turbine_user as B ");
statement.append(" on A.USER_ID = B.USER_ID ");
statement.append("LEFT JOIN turbine_group as C ");
statement.append(" on A.GROUP_ID = C.GROUP_ID ");
statement.append("LEFT JOIN eip_m_user_position as D ");
statement.append(" on A.USER_ID = D.USER_ID ");
statement.append("WHERE B.USER_ID > 3 AND B.DISABLED = 'F'");
statement.append(" AND B.POST_ID = #bind($postId) ");
statement.append("ORDER BY D.POSITION");
String query = statement.toString();
try {
List<TurbineUser> list2 =
Database
.sql(TurbineUser.class, query)
.param("postId", postid)
.fetchList();
for (TurbineUser tuser : list2) {
list.add(getALEipUser(tuser));
}
} catch (Throwable t) {
logger.error("ALEipUtils.getUsersFromPost", t);
}
return list;
}
/**
* <code>SelectQuery</code> の条件に従ってユーザーを取得します。
*
* @param crt
* @return ALEipUser の List
*/
public static List<ALEipUser> getUsersFromSelectQuery(
SelectQuery<TurbineUser> query) {
List<ALEipUser> list = new ArrayList<ALEipUser>();
try {
List<TurbineUser> ulist =
query.orderAscending(
TurbineUser.EIP_MUSER_POSITION_PROPERTY
+ "."
+ EipMUserPosition.POSITION_PROPERTY).fetchList();
for (TurbineUser tuser : ulist) {
list.add(getALEipUser(tuser));
}
} catch (Throwable t) {
logger.error("ALEipUtils.getUsersFromSelectQuery", t);
}
return list;
}
/**
* 自ユーザーの簡易オブジェクトを取得します。
*
* @param crt
* @return ALEipUser
*/
public static ALEipUser getALEipUser(RunData rundata) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
ALBaseUser baseuser = (ALBaseUser) jdata.getJetspeedUser();
ALEipUser user = new ALEipUser();
user.initField();
user.setUserId(Integer.parseInt(baseuser.getUserId()));
user.setName(baseuser.getUserName());
user.setAliasName(baseuser.getFirstName(), baseuser.getLastName());
user.setCreated(baseuser.getCreated());
return user;
}
/**
* 指定したユーザーIDの簡易オブジェクトを取得します。
*
* @param id
* @return
*/
public static ALEipUser getALEipUser(int id) throws ALDBErrorException {
TurbineUser tuser = getTurbineUser(id);
return getALEipUser(tuser);
}
/**
* 指定したユーザーIDの簡易オブジェクトを取得します。
*
* @param id
* @return
*/
public static ALEipUser getALEipUser(TurbineUser tuser)
throws ALDBErrorException {
if (tuser == null) {
return null;
}
ALEipUser user = new ALEipUser();
user.initField();
user.setUserId(tuser.getUserId().intValue());
user.setName(tuser.getLoginName());
user.setAliasName(tuser.getFirstName(), tuser.getLastName());
user.setHasPhoto("T".equals(tuser.getHasPhoto()));
user.setPhotoModified(tuser.getPhotoModified() != null ? tuser
.getPhotoModified()
.getTime() : 0);
user.setCreated(tuser.getCreated());
return user;
}
/**
* 指定したユーザーIDの簡易オブジェクトを取得します。
*
* @param id
* @return
*/
public static ALEipUser getALEipUser(String loginname)
throws ALDBErrorException {
TurbineUser tuser = getTurbineUser(loginname);
if (tuser == null) {
return null;
}
return getALEipUser(tuser);
}
/**
* 指定したユーザーIDのオブジェクトを取得します。
*
* @param userid
* ユーザID
* @return
*/
public static ALBaseUser getBaseUser(Integer userid) {
if (userid == null) {
logger.debug("Empty ID...");
return null;
}
String uid = String.valueOf(userid);
try {
return (ALBaseUser) JetspeedSecurity.getUser(new UserIdPrincipal(uid));
} catch (Exception ex) {
logger.error("ALEipUtils.getBaseUser", ex);
return null;
}
}
/**
* 指定したユーザーIDのユーザーオブジェクトを取得します。
*
* @param id
* @return
*/
public static TurbineUser getTurbineUser(int id) throws ALDBErrorException {
Object obj = ALEipManager.getInstance().getTurbineUser(id);
TurbineUser tuser = null;
if (obj == null) {
tuser = Database.get(TurbineUser.class, id);
ALEipManager.getInstance().setTurbineUser(id, tuser);
} else {
tuser = (TurbineUser) obj;
}
return tuser;
}
/**
* 指定したログイン名のユーザーオブジェクトを取得します。
*
* @param login_name
* @return
*/
public static TurbineUser getTurbineUser(String login_name)
throws ALDBErrorException {
Object obj = ALEipManager.getInstance().getTurbineUser(login_name);
TurbineUser tuser = null;
if (obj == null) {
tuser =
Database
.query(TurbineUser.class)
.where(Operations.eq(TurbineUser.LOGIN_NAME_PROPERTY, login_name))
.fetchSingle();
ALEipManager.getInstance().setTurbineUser(login_name, tuser);
} else {
tuser = (TurbineUser) obj;
}
return tuser;
}
/**
* 指定したユーザーIDが有効か(無効化、削除されていないか)どうか調べます。
*
* @param id
* @return
*/
public static boolean isEnabledUser(int id) throws ALDBErrorException {
TurbineUser tuser = getTurbineUser(id);
if (tuser == null) {
return false;
}
return "F".equals(tuser.getDisabled());
}
/**
* ユーザーのフルネームを取得します。
*
* @param userid
* ユーザID
* @return
*/
public static String getUserFullName(int userid) {
String userName = "";
ALBaseUser user = getBaseUser(userid);
if (user != null) {
userName =
new StringBuffer().append(user.getLastName()).append(" ").append(
user.getFirstName()).toString();
}
return userName;
}
/**
* 部署の変更を行います。 <br>
* 部署に関連付けされているグループの更新も同時に行います。
*
* @param rundata
* @param username
* ユーザー名
* @param postid
* 部署ID
* @return true 部署変更成功 false 部署変更失敗
*/
public static boolean changePost(RunData rundata, String username, int postid)
throws ALDBErrorException {
try {
ALBaseUser user = (ALBaseUser) JetspeedSecurity.getUser(username);
// グループへ追加
JetspeedSecurity.joinGroup(username, (ALEipManager
.getInstance()
.getPostMap().get(Integer.valueOf(postid))).getGroupName().getValue());
// 部署を変更
user.setPostId(postid);
// ユーザーを更新
JetspeedSecurity.saveUser(user);
ALBaseUser currentUser = (ALBaseUser) rundata.getUser();
if (currentUser.getUserName().equals(user.getUserName())) {
// 自ユーザーのセッション情報を更新する
currentUser.setPostId(user.getPostId());
}
} catch (JetspeedSecurityException ex) {
logger.error("ALEipUtils.changePost", ex);
throw new ALDBErrorException();
}
return true;
}
/**
* 自ユーザーのマイグループを再読み込みします。 <br>
* 読み込まれたマイグループはセッションに保存されます。 <br>
* マイグループの更新が行われた場合はこのメソッドを呼び出してください。
*
* @param rundata
*/
public static void reloadMygroup(RunData rundata) throws ALDBErrorException {
List<ALEipGroup> ulist = new ArrayList<ALEipGroup>();
try {
Expression exp =
ExpressionFactory.matchExp(TurbineGroup.OWNER_ID_PROPERTY, Integer
.valueOf(getUserId(rundata)));
List<TurbineGroup> list =
Database.query(TurbineGroup.class, exp).fetchList();
for (TurbineGroup record : list) {
ALEipGroup group = new ALEipGroup();
group.initField();
group.setName(record.getGroupName());
group.setAliasName(record.getGroupAliasName());
ulist.add(group);
}
} catch (Exception ex) {
logger.error("ALEipUtils.reloadMygroup", ex);
throw new ALDBErrorException();
}
// ServletRequestのマイグループに保存
ALMyGroups mygroups = new ALMyGroups();
mygroups.addList(ulist);
HttpServletRequest request = HttpServletRequestLocator.get();
if (request != null) {
request.setAttribute(ALEipConstants.MYGROUP, mygroups);
}
}
/**
* 自ユーザーのマイグループを取得します。
*
* @param rundata
* @return ALEipGroup の List
*/
public static List<ALEipGroup> getMyGroups(RunData rundata)
throws ALDBErrorException {
JetspeedRunData jdata = (JetspeedRunData) rundata;
// ServletRequestからマイグループのリストを読み込み
Object obj = null;
HttpServletRequest request = HttpServletRequestLocator.get();
if (request != null) {
obj = request.getAttribute(ALEipConstants.MYGROUP);
}
if (obj == null || !(obj instanceof ALMyGroups)) {
// まだMyGroupが読み込まれていない場合は
reloadMygroup(rundata);
if (request != null) {
obj = request.getAttribute(ALEipConstants.MYGROUP);
}
}
ALMyGroups mygroups = (ALMyGroups) obj;
return mygroups.getList();
}
public static List<ALEipGroup> getFacilityGroups() {
List<ALEipGroup> facilityGroupAllList = new ArrayList<ALEipGroup>();
try {
SelectQuery<EipMFacilityGroup> query =
Database.query(EipMFacilityGroup.class);
List<EipMFacilityGroup> facility_list =
query.orderAscending(EipMFacilityGroup.GROUP_NAME_PROPERTY).fetchList();
for (EipMFacilityGroup record : facility_list) {
ALEipGroup bean = new ALEipGroup();
bean.initField();
bean.setAliasName(record.getGroupName());
bean.setName(record.getGroupId().toString());
facilityGroupAllList.add(bean);
}
} catch (Exception ex) {
logger.error("ALEipUtils.getFacilityGroups", ex);
}
return facilityGroupAllList;
}
public static List<ALEipGroup> getALEipGroups() {
List<ALEipGroup> facilityGroupAllList = new ArrayList<ALEipGroup>();
try {
SelectQuery<EipMFacilityGroup> query =
Database.query(EipMFacilityGroup.class);
List<EipMFacilityGroup> facility_list =
query.orderAscending(EipMFacilityGroup.GROUP_NAME_PROPERTY).fetchList();
for (EipMFacilityGroup record : facility_list) {
ALEipGroup bean = new ALEipGroup();
bean.initField();
bean.setAliasName(record.getGroupName());
bean.setName(record.getGroupId().toString());
facilityGroupAllList.add(bean);
}
} catch (Exception ex) {
logger.error("ALEipUtils.getALEipGroups", ex);
}
return facilityGroupAllList;
}
/**
* 会社名を取得します。
*
* @param id
* @return
*/
public static String getCompanyName(int id) {
String companyName = null;
try {
Expression exp =
ExpressionFactory.matchDbExp(EipMCompany.COMPANY_ID_PK_COLUMN, Integer
.valueOf(id));
List<EipMCompany> list =
Database.query(EipMCompany.class, exp).select(
EipMCompany.COMPANY_NAME_COLUMN).fetchList();
if (list == null || list.size() == 0) {
// 指定したCompany IDのレコードが見つからない場合
logger.debug("[ALEipUtils] Not found ComapnyID...");
return null;
}
EipMCompany record = list.get(0);
companyName = record.getCompanyName();
} catch (Exception ex) {
logger.error("ALEipUtils.getCompanyName", ex);
companyName = null;
}
return companyName;
}
/**
* 部署名を取得します。
*
* @param id
* @return
*/
public static String getPostName(int id) {
if (ALEipManager
.getInstance()
.getPostMap()
.containsKey(Integer.valueOf(id))) {
return (ALEipManager.getInstance().getPostMap().get(Integer.valueOf(id)))
.getPostName()
.getValue();
}
return null;
}
/**
* 役職名を取得します。
*
* @param id
* @return
*/
public static String getPositionName(int id) {
if (ALEipManager.getInstance().getPositionMap().containsKey(
Integer.valueOf(id))) {
return (ALEipManager.getInstance().getPositionMap().get(Integer
.valueOf(id))).getPositionName().getValue();
}
return null;
}
/**
* ページが見つからない場合に、リダイレクト処理します。
*
* @return
*/
public static boolean redirectPageNotFound(RunData rundata) {
try {
JetspeedLink jsLink = JetspeedLinkFactory.getInstance(rundata);
DynamicURI duri = jsLink.getPage();
String template =
rundata.getParameters().getString(JetspeedResources.PATH_TEMPLATE_KEY);
if (template != null && !("".equals(template))) {
if (template.endsWith("DetailScreen")
|| template.endsWith("FormScreen")) {
VelocityContext context = new VelocityContext();
setupContext(rundata, context);
try {
ServletOutputStream out = null;
HttpServletResponse response = rundata.getResponse();
out = response.getOutputStream();
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(
out,
ALEipConstants.DEF_CONTENT_ENCODING));
context
.put("l10n", ALLocalizationUtils.createLocalization(rundata));
Template templete =
Velocity.getTemplate("screens/html/AjaxPageNotFound.vm");
templete.merge(context, writer);
writer.flush();
writer.close();
} catch (ResourceNotFoundException e) {
logger.error("ALEipUtils.redirectPageNotFound", e);
throw new RuntimeException(e);
} catch (ParseErrorException e) {
logger.error("ALEipUtils.redirectPageNotFound", e);
throw new RuntimeException(e);
} catch (Exception e) {
logger.error("ALEipUtils.redirectPageNotFound", e);
throw new RuntimeException(e);
}
return true;
}
}
duri.addPathInfo("template", "PageNotFound");
rundata.setRedirectURI(duri.toString());
rundata.getResponse().sendRedirect(rundata.getRedirectURI());
JetspeedLinkFactory.putInstance(jsLink);
jsLink = null;
return true;
} catch (TurbineException e) {
logger.error("ALEipUtils.redirectPageNotFound", e);
return false;
} catch (IOException e) {
logger.error("ALEipUtils.redirectPageNotFound", e);
return false;
}
}
/**
* データベースエラーの場合に、リダイレクト処理します。
*
* @return
*/
public static boolean redirectDBError(RunData rundata) {
try {
JetspeedLink jsLink = JetspeedLinkFactory.getInstance(rundata);
DynamicURI duri = jsLink.getPage();
String template =
rundata.getParameters().getString(JetspeedResources.PATH_TEMPLATE_KEY);
if (template != null && !("".equals(template))) {
if (template.endsWith("DetailScreen")
|| (template.endsWith("FormScreen"))) {
Context context =
org.apache.turbine.services.velocity.TurbineVelocity
.getContext(rundata);
if (null == context) {
context = new VelocityContext();
setupContext(rundata, context);
}
try {
ServletOutputStream out = null;
HttpServletResponse response = rundata.getResponse();
out = response.getOutputStream();
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(
out,
ALEipConstants.DEF_CONTENT_ENCODING));
context
.put("l10n", ALLocalizationUtils.createLocalization(rundata));
context.put("utils", new ALCommonUtils());
Template templete =
Velocity.getTemplate("screens/html/AjaxDBError.vm");
templete.merge(context, writer);
writer.flush();
writer.close();
} catch (ResourceNotFoundException e) {
logger.error("ALEipUtils.redirectDBError", e);
throw new RuntimeException(e);
} catch (ParseErrorException e) {
logger.error("ALEipUtils.redirectDBError", e);
throw new RuntimeException(e);
} catch (Exception e) {
logger.error("ALEipUtils.redirectDBError", e);
throw new RuntimeException(e);
}
return true;
}
}
duri.addPathInfo(JetspeedResources.PATH_TEMPLATE_KEY, "DBError");
rundata.setRedirectURI(duri.toString());
rundata.getResponse().sendRedirect(rundata.getRedirectURI());
JetspeedLinkFactory.putInstance(jsLink);
jsLink = null;
return true;
} catch (TurbineException e) {
logger.error("ALEipUtils.redirectDBError", e);
return false;
} catch (IOException e) {
logger.error("ALEipUtils.redirectDBError", e);
return false;
}
}
/**
* パーミッションエラーの場合に、リダイレクト処理します。
*
* @return
*/
public static boolean redirectPermissionError(RunData rundata) {
try {
JetspeedLink jsLink = JetspeedLinkFactory.getInstance(rundata);
DynamicURI duri = jsLink.getPage();
String template =
rundata.getParameters().getString(JetspeedResources.PATH_TEMPLATE_KEY);
if (template != null && !("".equals(template))) {
if (template.endsWith("JSONScreen")) {
VelocityContext context = new VelocityContext();
setupContext(rundata, context);
ServletOutputStream out = null;
HttpServletResponse response = rundata.getResponse();
out = response.getOutputStream();
List<String> list = new ArrayList<String>();
list.add("PermissionError");
list.add(ALAccessControlConstants.DEF_PERMISSION_ERROR_STR);
JSONArray json = JSONArray.fromObject(list);
StringBuffer result =
new StringBuffer().append("/* ").append(json.toString()).append(
" */");
byte[] byteResult =
result.toString().getBytes(ALEipConstants.DEF_CONTENT_ENCODING);
out.write(byteResult);
out.flush();
out.close();
return true;
} else if (template.endsWith("FormScreen")
|| template.endsWith("DetailScreen")) {
VelocityContext context = new VelocityContext();
setupContext(rundata, context);
try {
ServletOutputStream out = null;
HttpServletResponse response = rundata.getResponse();
out = response.getOutputStream();
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(
out,
ALEipConstants.DEF_CONTENT_ENCODING));
context
.put("l10n", ALLocalizationUtils.createLocalization(rundata));
Template templete =
Velocity.getTemplate("screens/html/AjaxPermissionError.vm");
templete.merge(context, writer);
writer.flush();
writer.close();
} catch (ResourceNotFoundException e) {
logger.error("ALEipUtils.redirectPermissionError", e);
throw new RuntimeException(e);
} catch (ParseErrorException e) {
logger.error("ALEipUtils.redirectPermissionError", e);
throw new RuntimeException(e);
} catch (Exception e) {
logger.error("ALEipUtils.redirectPermissionError", e);
throw new RuntimeException(e);
}
return true;
} else if (template.endsWith("Screen")) {
// 一覧表示の場合
VelocityContext context = new VelocityContext();
setupContext(rundata, context);
try {
ServletOutputStream out = null;
HttpServletResponse response = rundata.getResponse();
out = response.getOutputStream();
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(
out,
ALEipConstants.DEF_CONTENT_ENCODING));
context
.put("l10n", ALLocalizationUtils.createLocalization(rundata));
Template templete =
Velocity.getTemplate("portlets/html/PermissionError.vm");
templete.merge(context, writer);
writer.flush();
writer.close();
} catch (Exception e) {
return false;
}
return true;
} else if (template.equals("Customize") || template.equals("Home")) {
// ポートレットカスタマイズ
duri.addPathInfo(
JetspeedResources.PATH_TEMPLATE_KEY,
"PermissionError");
rundata.setRedirectURI(duri.toString());
rundata.getResponse().sendRedirect(rundata.getRedirectURI());
JetspeedLinkFactory.putInstance(jsLink);
jsLink = null;
return true;
} else if (isCellularPhone(rundata)) {
duri.addPathInfo(
JetspeedResources.PATH_TEMPLATE_KEY,
"CellPermissionError");
rundata.setRedirectURI(duri.toString());
rundata.getResponse().sendRedirect(rundata.getRedirectURI());
JetspeedLinkFactory.putInstance(jsLink);
jsLink = null;
Restore restore = new Restore();
try {
restore.doPerform(rundata);
} catch (Exception e) {
}
return true;
} else if (isSmartPhone(rundata)) {
duri.addPathInfo(
JetspeedResources.PATH_TEMPLATE_KEY,
"CellPermissionError");
rundata.setRedirectURI(duri.toString());
rundata.getResponse().sendRedirect(rundata.getRedirectURI());
JetspeedLinkFactory.putInstance(jsLink);
jsLink = null;
Restore restore = new Restore();
try {
restore.doPerform(rundata);
} catch (Exception e) {
}
return true;
}
}
/*-
try {
Restore restore = new Restore();
restore.doPerform(rundata);
} catch (Exception e) {
}
*/
JetspeedRunData jdata = (JetspeedRunData) rundata;
if (jdata.getMode() == JetspeedRunData.MAXIMIZE) {
rundata.getRequest().setAttribute(
"redirectTemplate",
"permission-error-maximize");
/*-
duri
.addPathInfo(JetspeedResources.PATH_TEMPLATE_KEY, "PermissionError");
rundata.setRedirectURI(duri.toString());
rundata.getResponse().sendRedirect(rundata.getRedirectURI());
JetspeedLinkFactory.putInstance(jsLink);
jsLink = null;
*/
} else {
Context context =
(Context) jdata.getTemplateInfo().getTemplateContext(
"VelocityPortletContext");
context.put(JetspeedResources.PATH_TEMPLATE_KEY, "PermissionError");
}
return true;
} catch (TurbineException e) {
logger.error("ALEipUtils.redirectPermissionError", e);
return false;
} catch (IOException e) {
logger.error("ALEipUtils.redirectPermissionError", e);
return false;
}
}
/**
* 改行コードを含む文字列を、複数行に分割します。
*
* @return
*/
public static String getMessageList(String msgline) {
StringBuffer sb = new StringBuffer();
ALStringField field = null;
if (msgline == null || msgline.equals("")) {
return "";
}
msgline = Normalizer.normalize(msgline, Normalizer.Form.NFC);
if (msgline.indexOf("\r") < 0
&& msgline.indexOf("\n") < 0
&& msgline.indexOf("\r\n") < 0) {
field = new ALStringField();
field.setTrim(false);
field.setValue(msgline);
return ALCommonUtils
.replaceToAutoCR(replaceStrToLink(replaseLeftSpace(field.toString())));
}
String token = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new StringReader(msgline));
while ((token = reader.readLine()) != null) {
field = new ALStringField();
field.setTrim(false);
field.setValue(token);
sb.append(
ALCommonUtils.replaceToAutoCR(replaceStrToLink(replaseLeftSpace(field
.toString())))).append("<br/>");
}
reader.close();
} catch (IOException ioe) {
try {
reader.close();
} catch (IOException e) {
}
return "";
}
int index = sb.lastIndexOf("<br/>");
if (index == -1) {
return sb.toString();
}
return sb.substring(0, index).replaceAll("<wbr/><br/>", "<br/>");
}
/**
* 左端の半角空文字を「 」に変換する。
*
* @param str
* @return
*/
public static String replaseLeftSpace(String str) {
if (str == null || str.length() <= 0) {
return str;
}
int len = str.length();
int st = 0;
char[] val = str.toCharArray();
StringBuffer sb = new StringBuffer();
boolean left = true;
while ((st < len)) {
if (val[st] == ' ' && left) {
sb.append(" ");
} else {
sb.append(val[st]);
left = false;
}
st++;
}
return (sb.length() > 0) ? sb.toString() : str;
}
/**
* アクセス元の端末が携帯電話であるかを判定します。
*
* @param data
* @return
*/
public static boolean isCellularPhone(RunData data) {
boolean isCellularPhone = false;
CapabilityMap cm =
CapabilityMapFactory.getCapabilityMap(data.getRequest().getHeader(
"User-Agent"));
MimeType mime = cm.getPreferredType();
if (mime != null) {
MediaTypeEntry media =
(MediaTypeEntry) Registry.getEntry(Registry.MEDIA_TYPE, cm
.getPreferredMediaType());
String mediatype = media.getName();
if ("docomo_imode".equals(mediatype)
|| "docomo_foma".equals(mediatype)
|| "au".equals(mediatype)
|| "vodafone".equals(mediatype)) {
isCellularPhone = true;
}
}
return isCellularPhone;
}
/**
* アクセス元の端末がスマートフォンであるかを判定します。
*
* @param data
* @return
*/
public static boolean isSmartPhone(RunData data) {
boolean isSmartPhone = false;
CapabilityMap cm =
CapabilityMapFactory.getCapabilityMap(data.getRequest().getHeader(
"User-Agent"));
MimeType mime = cm.getPreferredType();
if (mime != null) {
MediaTypeEntry media =
(MediaTypeEntry) Registry.getEntry(Registry.MEDIA_TYPE, cm
.getPreferredMediaType());
String mediatype = media.getName();
if ("iphone".equals(mediatype) || "wm".equals(mediatype)) {
isSmartPhone = true;
}
}
return isSmartPhone;
}
/**
* 指定した2つの日付を比較します。
*
* @param date1
* @param date2
* @return 等しい場合、0。date1>date2の場合、1。date1 < date2の場合、2。
*/
public static int compareToDate(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int date1Year = cal1.get(Calendar.YEAR);
int date1Month = cal1.get(Calendar.MONTH) + 1;
int date1Day = cal1.get(Calendar.DATE);
int date1Hour = cal1.get(Calendar.HOUR);
int date1Minute = cal1.get(Calendar.MINUTE);
int date1Second = cal1.get(Calendar.SECOND);
int date2Year = cal2.get(Calendar.YEAR);
int date2Month = cal2.get(Calendar.MONTH) + 1;
int date2Day = cal2.get(Calendar.DATE);
int date2Hour = cal2.get(Calendar.HOUR);
int date2Minute = cal2.get(Calendar.MINUTE);
int date2Second = cal2.get(Calendar.SECOND);
if (date1Year == date2Year
&& date1Month == date2Month
&& date1Day == date2Day
&& date1Hour == date2Hour
&& date1Minute == date2Minute
&& date1Second == date2Second) {
return 0;
}
if (cal1.after(cal2)) {
return 2;
} else {
return 1;
}
}
/**
* データベースの検索結果から、指定したキーに対応する値を取得します。
*
* @param dataRow
* @param key
* @return
*/
public static Object getObjFromDataRow(DataRow dataRow, String key) {
String lowerKey = key.toLowerCase();
if (dataRow.containsKey(lowerKey)) {
return dataRow.get(lowerKey);
} else {
return dataRow.get(key.toUpperCase());
}
}
/**
* 会社情報のオブジェクトを取得します。
*
* @param id
* @return
*/
public static EipMCompany getEipMCompany(String id) {
Expression exp =
ExpressionFactory.matchDbExp(EipMCompany.COMPANY_ID_PK_COLUMN, Integer
.valueOf(id));
List<EipMCompany> list = Database.query(EipMCompany.class, exp).fetchList();
if (list == null || list.size() == 0) {
logger.debug("Not found ID...");
return null;
}
return list.get(0);
}
/**
* @see ALServletUtils#getAccessUrl(String, int, boolean)
* @param ip
* @param port
* @param servername
* @param isGlobal
* @return
* @deprecated
*/
@Deprecated
public static String getUrl(String ip, int port, String servername,
boolean isGlobal) {
if (ip == null || ip.length() == 0 || port == -1) {
return "";
}
String protocol =
isGlobal
? ALConfigService.get(Property.ACCESS_GLOBAL_URL_PROTOCOL)
: ALConfigService.get(Property.ACCESS_LOCAL_URL_PROTOCOL);
StringBuffer url = new StringBuffer();
if (port == 80 || port == 443) {
url.append(protocol).append("://").append(ip).append("/").append(
servername).append(servername.isEmpty() ? "" : "/");
} else {
url
.append(protocol)
.append("://")
.append(ip)
.append(":")
.append(port)
.append("/")
.append(servername)
.append(servername.isEmpty() ? "" : "/");
}
return url.toString();
}
/**
*
* @param rundata
* @param context
*/
public static void setupContext(RunData rundata, Context context) {
String js_peid;
if (!rundata.getParameters().containsKey(
JetspeedResources.PATH_PORTLETID_KEY)) {
return;
}
js_peid =
rundata.getParameters().getString(JetspeedResources.PATH_PORTLETID_KEY);
Portlet portlet = getPortlet(rundata, js_peid);
context.put("portlet", portlet);
context.put("jslink", new BaseJetspeedLink(rundata));
context.put("clink", new ContentTemplateLink(rundata));
}
public static void setupContext(String js_peid, RunData rundata,
Context context) {
Portlet portlet = getPortlet(rundata, js_peid);
context.put("portlet", portlet);
context.put("jslink", new BaseJetspeedLink(rundata));
context.put("clink", new ContentTemplateLink(rundata));
}
/**
*
* @param rundata
* @param context
* @param key
* @return
*/
public static String getParameter(RunData rundata, Context context, String key) {
String name = null;
String idParam = rundata.getParameters().getString(key);
name = ALEipUtils.getTemp(rundata, context, key);
if (idParam == null && name == null) {
ALEipUtils.removeTemp(rundata, context, key);
name = null;
} else if (idParam != null) {
ALEipUtils.setTemp(rundata, context, key, idParam);
name = idParam;
}
return name;
}
/**
* 指定したエントリー名のポートレットへの URI を取得します。
*
* @param rundata
* @param portletEntryName
* PSML ファイルに記述されているタグ entry の要素 parent
* @return
*/
public static String getPortletURI(RunData rundata, String portletEntryId) {
try {
Portlets portlets =
((JetspeedRunData) rundata).getProfile().getDocument().getPortlets();
if (portlets == null) {
return null;
}
Portlets[] portletList = portlets.getPortletsArray();
if (portletList == null) {
return null;
}
int length = portletList.length;
for (int i = 0; i < length; i++) {
Entry[] entries = portletList[i].getEntriesArray();
if (entries == null || entries.length <= 0) {
continue;
}
int ent_length = entries.length;
for (int j = 0; j < ent_length; j++) {
if (entries[j].getId().equals(portletEntryId)) {
JetspeedLink jsLink = JetspeedLinkFactory.getInstance(rundata);
DynamicURI duri =
jsLink.getLink(
JetspeedLink.CURRENT,
null,
null,
JetspeedLink.CURRENT,
null);
duri =
duri.addPathInfo(
JetspeedResources.PATH_PANEID_KEY,
portletList[i].getId()).addPathInfo(
JetspeedResources.PATH_PORTLETID_KEY,
entries[j].getId()).addQueryData(
JetspeedResources.PATH_ACTION_KEY,
"controls.Maximize");
return duri.toString();
}
}
}
} catch (Exception ex) {
logger.error("ALEipUtils.getPortletURI", ex);
return null;
}
return null;
}
/**
*
* @param rundata
* @param portletEntryId
* @return
*/
public static String getPortletURItoTopPage(RunData rundata,
String portletEntryId) {
try {
Portlets portlets =
((JetspeedRunData) rundata).getProfile().getDocument().getPortlets();
if (portlets == null) {
return null;
}
Portlets[] portletList = portlets.getPortletsArray();
if (portletList == null) {
return null;
}
int length = portletList.length;
for (int i = 0; i < length; i++) {
Entry[] entries = portletList[i].getEntriesArray();
if (entries == null || entries.length <= 0) {
continue;
}
int ent_length = entries.length;
for (int j = 0; j < ent_length; j++) {
if (entries[j].getId().equals(portletEntryId)) {
JetspeedLink jsLink = JetspeedLinkFactory.getInstance(rundata);
DynamicURI duri =
jsLink.getLink(
JetspeedLink.CURRENT,
null,
null,
JetspeedLink.CURRENT,
null);
duri =
duri.addPathInfo(
JetspeedResources.PATH_PANEID_KEY,
portletList[i].getId()).addQueryData(
JetspeedResources.PATH_ACTION_KEY,
"controls.Restore");
return duri.toString();
}
}
}
} catch (Exception ex) {
logger.error("ALEipUtils.getPortletURItoTopPage", ex);
return null;
}
return null;
}
/**
* 文字列内のリンクにタグAを追加します。
*
* @param msg
* @return
*/
public static String replaceStrToLink(String msg) {
if (msg != null) {
String regex =
"(https?|ftp|gopher|telnet|whois|news)\\:([\\w|\\:\\!\\#\\$\\%\\=\\&\\-\\^\\`\\\\|\\@\\~\\[\\{\\]\\}\\;\\+\\*\\,\\.\\?\\/]+)";
Pattern p = Pattern.compile(regex);
boolean check = true;
while (check) {
check = false;
Matcher m = p.matcher(msg);
while (m.find()) {
if (m.group(0).contains("@")) {
String matchString = m.group(0);
matchString = matchString.replaceAll("@", "%40");
String pre = msg.substring(0, m.start(0));
String post = msg.substring(m.end(0), msg.length());
msg = pre + matchString + post;
check = true;
}
}
}
// 日本語(ひらがな、かたかな、漢字)が含まれていてもリンク化されるように正規表現を追加する。
String newMsg =
msg
.replaceAll(
"(https?|ftp|gopher|telnet|whois|news)\\:([\\w|\\p{InHiragana}\\p{InKatakana}\\p{InCJKUnifiedIdeographs}\\:\\!\\#\\$\\%\\=\\&\\-\\^\\`\\\\|\\@\\~\\[\\{\\]\\}\\;\\+\\*\\,\\.\\?\\/]+)",
"<a href=\"$1\\:$2\" target=\"_blank\">$1\\:$2</a>");
return newMsg.replaceAll(
"[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",
"<a href='mailto:$0'>$0</a>");
} else {
return "";
}
}
/**
* フォルダを再帰的に消します。
*
* @param parent_folder
* 親フォルダ
* @param cal
*
* @return フォルダの中身が全て消去されたときのみtrueを返します
*/
/**
* ユーザーの所属する部署を取得します。
*
* @param id
* ユーザーID
* @return 所属する部署リスト
*/
public static List<ALStringField> getPostNameList(int id) {
SelectQuery<TurbineUserGroupRole> query =
Database.query(TurbineUserGroupRole.class);
Expression exp1 =
ExpressionFactory.matchExp(
TurbineUserGroupRole.TURBINE_USER_PROPERTY,
Integer.valueOf(id));
Expression exp2 =
ExpressionFactory.greaterExp(
TurbineUserGroupRole.TURBINE_GROUP_PROPERTY,
Integer.valueOf(3));
Expression exp3 =
ExpressionFactory.matchExp(TurbineUserGroupRole.TURBINE_GROUP_PROPERTY
+ "."
+ TurbineGroup.OWNER_ID_PROPERTY, Integer.valueOf(1));
query.setQualifier(exp1);
query.andQualifier(exp2);
query.andQualifier(exp3);
List<TurbineUserGroupRole> list = query.fetchList();
ALStringField sf = null;
List<ALStringField> postNames = new ArrayList<ALStringField>();
for (TurbineUserGroupRole role : list) {
sf = new ALStringField(role.getTurbineGroup().getGroupAliasName());
postNames.add(sf);
}
return postNames;
}
/**
* ユーザーの所属する部署のIDを取得します。
*
* @param id
* ユーザーID
* @return 所属する部署リスト
*/
public static List<Integer> getPostIdList(int id) {
SelectQuery<TurbineUserGroupRole> query =
Database.query(TurbineUserGroupRole.class);
Expression exp1 =
ExpressionFactory.matchExp(
TurbineUserGroupRole.TURBINE_USER_PROPERTY,
Integer.valueOf(id));
Expression exp2 =
ExpressionFactory.greaterExp(
TurbineUserGroupRole.TURBINE_GROUP_PROPERTY,
Integer.valueOf(3));
Expression exp3 =
ExpressionFactory.matchExp(TurbineUserGroupRole.TURBINE_GROUP_PROPERTY
+ "."
+ TurbineGroup.OWNER_ID_PROPERTY, Integer.valueOf(1));
query.setQualifier(exp1);
query.andQualifier(exp2);
query.andQualifier(exp3);
List<TurbineUserGroupRole> list = query.fetchList();
List<Integer> postIds = new ArrayList<Integer>();
for (TurbineUserGroupRole role : list) {
postIds.add(role.getTurbineGroup().getEipMPost().getPostId());
}
return postIds;
}
/**
* アクセス権限をチェックします(ポートレットカスタマイズ)
*
* @return
*/
public static boolean checkAclPermissionForCustomize(RunData rundata,
Context context, int defineAclType) {
try {
if (defineAclType == 0) {
return true;
}
boolean hasAuthority = getHasAuthority(rundata, context, defineAclType);
if (!hasAuthority) {
throw new ALPermissionException();
}
return true;
} catch (ALPermissionException e) {
ALEipUtils.redirectPermissionError(rundata);
return false;
}
}
public static boolean getHasAuthority(RunData rundata, Context context,
int defineAclType) {
String pfeature =
ALAccessControlConstants.POERTLET_FEATURE_PORTLET_CUSTOMIZE;
if (pfeature == null || "".equals(pfeature)) {
return true;
}
ALAccessControlFactoryService aclservice =
(ALAccessControlFactoryService) ((TurbineServices) TurbineServices
.getInstance()).getService(ALAccessControlFactoryService.SERVICE_NAME);
ALAccessControlHandler aclhandler = aclservice.getAccessControlHandler();
return aclhandler.hasAuthority(
ALEipUtils.getUserId(rundata),
pfeature,
defineAclType);
}
public static int getLimitUsers() {
try {
List<AipoLicense> list =
Database
.query(AipoLicense.class)
.select(AipoLicense.LIMIT_USERS_COLUMN)
.fetchList();
if (list != null && list.size() > 0) {
AipoLicense record = list.get(0);
Integer result = record.getLimitUsers();
return result.intValue();
}
} catch (Exception e) {
logger.error("ALEipUtils.getLimitUsers", e);
}
return 0;
}
/**
* 現在登録されている有効なユーザー数(システムユーザ、論理削除は除く)を取得します。
*
* @return
*/
public static int getCurrentUserNumEnabledOnly(RunData rundata) {
int registeredUserNum = -1;
try {
// 論理削除ユーザーを除く
// ユーザーテーブルDISABLEDがTのものが論理削除
// システムユーザtemplateは論理削除されているため
// RES_USER_NUMは3だが2として計算しないといけない。
Expression exp =
ExpressionFactory.matchExp(TurbineUser.DISABLED_PROPERTY, "F");
List<TurbineUser> list =
Database.query(TurbineUser.class, exp).fetchList();
if (list == null || list.size() <= 0) {
return -1;
}
int size = list.size();
// admin,anonユーザが含まれるので2ユーザ分減算
registeredUserNum = size - 2;
} catch (Exception ex) {
logger.error("ユーザー情報をDBから取得できませんでした。");
logger.error("ALEipUtils.getCurrentUserNumEnabledOnly", ex);
return -1;
}
return registeredUserNum;
}
/**
* 現在登録されている有効なユーザー数(システムユーザ、論理削除、無効化は除く)を取得します。
*
* @return
*/
public static int getCurrentUserNum(RunData rundata) {
int registeredUserNum = -1;
try {
// 論理削除ユーザーを除く
// ユーザーテーブルDISABLEDがTのものが論理削除
// システムユーザtemplateは論理削除されているため
// RES_USER_NUMは3だが2として計算しないといけない。
Expression exp =
ExpressionFactory.noMatchExp(TurbineUser.DISABLED_PROPERTY, "T");
List<TurbineUser> list =
Database.query(TurbineUser.class, exp).fetchList();
if (list == null || list.size() <= 0) {
return -1;
}
int size = list.size();
// admin,anonユーザが含まれるので2ユーザ分減算
registeredUserNum = size - 2;
} catch (Exception ex) {
logger.error("ユーザー情報をDBから取得できませんでした。");
logger.error("ALEipUtils.getCurrentUserNum", ex);
return -1;
}
return registeredUserNum;
}
/**
* 指定されたユーザが管理者権限を持っているかを返します。
*
* @param uid
* @return
*/
public static boolean isAdmin(int uid) {
boolean res = false;
try {
Role adminrole = JetspeedSecurity.getRole("admin");
TurbineUserGroupRole role =
Database
.query(TurbineUserGroupRole.class)
.where(
Operations.eq(TurbineUserGroupRole.TURBINE_ROLE_PROPERTY, adminrole
.getId()),
Operations.eq(TurbineUserGroupRole.TURBINE_USER_PROPERTY, uid))
.fetchSingle();
res = role != null;
} catch (JetspeedSecurityException e) {
logger.error("管理者ロールが存在しません。");
logger.error("ALEipUtils.isAdmin", e);
}
return res;
}
/**
* ログインユーザが管理者権限を持っているかを返します。
*
* @param rundata
* @return
*/
public static boolean isAdmin(RunData rundata) {
JetspeedRunData jdata = (JetspeedRunData) rundata;
return isAdmin(Integer.valueOf(jdata.getUserId()));
}
/**
* is LoginUser Admin ?
*/
public static boolean isAdminUser(RunData runData) {
int userId = getUserId(runData);
return isAdminUser(userId);
}
public static boolean isAdminUser(int userId) {
// admin user definition : user id equals 1
return userId == 1;
}
public static String getLoginName(RunData runData) {
JetspeedRunData jdata = (JetspeedRunData) runData;
return jdata.getJetspeedUser().getUserName();
}
/**
* Dateに対して整形されたALDateTimeFieldを返します。
*
* @param date
* @return 整形されたALDateTimeField
*/
public static ALDateTimeField getFormattedTime(Date date) {
Calendar Now = new GregorianCalendar();
Now.setTime(new Date());
Calendar Time = new GregorianCalendar();
Time.setTime(date);
ALDateTimeField rtn;
rtn =
(Now.get(Calendar.YEAR) == Time.get(Calendar.YEAR)) ? (Now
.get(Calendar.MONTH) == Time.get(Calendar.MONTH)
&& Now.get(Calendar.DATE) == Time.get(Calendar.DATE)
? new ALDateTimeField("H:mm")
: new ALDateTimeField("M月d日")) : new ALDateTimeField("yyyy年M月d日");
rtn.setValue(date);
return rtn;
}
public static ALDateTimeField getFormattedTime(ALDateTimeField timeField) {
if (!timeField.isNotNullValue()) {
return null;
}
return getFormattedTime(timeField.getValue());
}
public static ALDateTimeField getFormattedTimeDetail(Date date) {
Calendar Now = new GregorianCalendar();
Now.setTime(new Date());
Calendar Time = new GregorianCalendar();
Time.setTime(date);
ALDateTimeField rtn;
rtn =
(Now.get(Calendar.YEAR) == Time.get(Calendar.YEAR))
? new ALDateTimeField("M月d日 H:mm")
: new ALDateTimeField("yyyy年M月d日 H:mm");
rtn.setValue(date);
return rtn;
}
public static ALDateTimeField getFormattedTimeDetail(ALDateTimeField timeField) {
if (!timeField.isNotNullValue()) {
return null;
}
return getFormattedTimeDetail(timeField.getValue());
}
/**
* 指定したユーザのPSMLにシステム管理のページを追加します。
*
* @param user_name
* @throws Exception
*/
public static void addAdminPage(String user_name) throws Exception {
ProfileLocator locator = Profiler.createLocator();
locator.createFromPath(String.format("user/%s/media-type/html", user_name));
/** for request cache clear */
ALEipManager.getInstance().removeProfile(locator);
Profile profile = Profiler.getProfile(locator);
Portlets portlets = profile.getDocument().getPortlets();
if (portlets != null) {
// 既に配置されているかどうかを確認
long max_position = 0;
int portlet_size = portlets.getPortletsCount();
for (int i = 0; i < portlet_size; i++) {
Portlets p = portlets.getPortlets(i);
if (p.getSecurityRef().getParent().equals("admin-view")) {
return;
}
if (p.getLayout().getPosition() > max_position) {
max_position = p.getLayout().getPosition();
}
}
// レイアウトの作成
Layout newLayout = new PsmlLayout();
newLayout.setPosition(max_position + 1);
newLayout.setSize(-1);
ProfileLocator admin_locator = Profiler.createLocator();
admin_locator.createFromPath("user/admin/media-type/html");
Portlets admin_portlets =
Profiler.createProfile(admin_locator).getDocument().getPortlets();
admin_portlets = admin_portlets.getPortlets(0);
Entry[] entriesArray = admin_portlets.getEntriesArray();
int size = entriesArray.length;
for (int i = 0; i < size; i++) {
if (entriesArray[i].getParent().equals("DeleteSample")) {
admin_portlets.removeEntry(i);
break;
}
}
admin_portlets.setLayout(newLayout);
portlets.addPortlets(admin_portlets);
PsmlManager.store(profile);
}
}
public static String getFirstPortletId(String username) {
try {
ProfileLocator locator = Profiler.createLocator();
locator
.createFromPath(String.format("user/%s/media-type/html", username));
Profile profile = Profiler.getProfile(locator);
Portlets portlets = profile.getDocument().getPortlets();
if (portlets == null) {
return null;
}
Portlets[] portletList = portlets.getPortletsArray();
if (portletList == null) {
return null;
}
for (Portlets portlet : portletList) {
Entry[] entries = portlet.getEntriesArray();
if (entries == null || entries.length == 0) {
continue;
}
for (String name : IPHONE_APPS) {
for (Entry entry : entries) {
String portletName = entry.getParent();
if (portletName.equals("AjaxScheduleWeekly")) {
portletName = "Schedule";
}
if (name.equals(portletName)) {
return entry.getId();
}
}
}
}
} catch (Exception ex) {
logger.error("ALEipUtils.getFirstPortletId", ex);
return null;
}
return null;
}
public static String getClient(RunData rundata) {
if (Boolean.parseBoolean((String) rundata.getSession().getAttribute(
"changeToPc"))) { // PC表示切り替え用
return "PCIPHONE";
} else {
return getClient(rundata.getUserAgent().trim());
}
}
public static String getClient(String userAgent) {
return getClientEntry(userAgent).getKey();
}
/**
* 期待するユーザーエージェントが含まれていればtrue
*
* @param expect
* @param rundata
* @return
*/
public static boolean isMatchUserAgent(String expect, RunData rundata) {
// User-Agent の取得
String userAgent = rundata.getUserAgent().trim();
if (userAgent == null || "".equals(userAgent)) {
return false;
}
return userAgent.indexOf(expect) > -1;
}
/**
* アクセスしてきたユーザが利用するブラウザ名が Windows の MSIE であるかを判定する.
*
* @param rundata
* @return MSIE の場合は,true.
*/
public static boolean isMsieBrowser(RunData rundata) {
return isMatchUserAgent("Win", rundata)
&& (isMatchUserAgent("MSIE", rundata) || isMatchUserAgent(
"Trident",
rundata));
}
/**
* アクセスしてきたユーザが利用するブラウザ名が Android.
*
* @param rundata
* @return MSIE の場合は,true.
*/
public static boolean isAndroidBrowser(RunData rundata) {
return isMatchUserAgent("Android", rundata);
}
public static boolean isAndroid2Browser(RunData rundata) {
int[] version = getAndroidVersion(rundata);
return version != null && version[0] == 2;
}
public static int[] getAndroidVersion(RunData rundata) {
final String userAgent = rundata.getUserAgent().trim();
if (userAgent == null || "".equals(userAgent)) {
return null;
}
Pattern androidVersion =
Pattern.compile(
"Android ([\\d]+).([\\d]+).([\\d]+)",
Pattern.CASE_INSENSITIVE);
Matcher matcher = androidVersion.matcher(userAgent);
if (matcher.find()) {
return new int[] {
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)) };
} else {
return null;
}
}
public static String getClientVersion(RunData rundata) {
return getClientVersion(rundata.getUserAgent().trim());
}
public static String getClientVersion(String userAgent) {
return getClientEntry(userAgent).getValue();
}
protected static Map.Entry<String, String> getClientEntry(String userAgent) {
Map<String, String> map = new HashMap<String, String>(1);
String key = "com.aimluck.eip.util.getClient.client";
String keyVer = "com.aimluck.eip.util.getClient.clientVer";
String client = null;
String clientVer = "0";
HttpServletRequest request = HttpServletRequestLocator.get();
if (request != null) {
client = (String) request.getAttribute(key);
clientVer = (String) request.getAttribute(keyVer);
if (client != null && client.length() > 0) {
if (clientVer == null) {
clientVer = "";
}
map.put(client, clientVer);
return map.entrySet().iterator().next();
}
}
ClientRegistry registry = (ClientRegistry) Registry.get(Registry.CLIENT);
ClientEntry entry = registry.findEntry(userAgent);
client = entry == null ? "OUTER" : entry.getManufacturer();
if ("IPAD".equals(client) || "IPHONE".equals(client)) {
clientVer = String.valueOf(userAgent.charAt(userAgent.indexOf("OS") + 3));
}
if (isIE(userAgent)) {
client = "IE";
clientVer = getIEVersion(userAgent);
}
if (request != null) {
request.setAttribute(key, client);
request.setAttribute(keyVer, clientVer);
}
if (clientVer == null) {
clientVer = "";
}
map.put(client, clientVer);
return map.entrySet().iterator().next();
}
public static boolean isIE(String userAgent) {
return (userAgent.matches(".*((MSIE)+ [0-9]\\.[0-9]).*") || userAgent
.matches(".*(.*(Trident/)+[0-9]\\.[0-9]).*"));
}
/**
* PSMLにデータを埋め込みます。
*
* @param rundata
* @param context
* @param key
* @param value
* @return
*/
public static boolean setPsmlParameters(RunData rundata, Context context,
String key, String value) {
try {
String portletEntryId =
rundata.getParameters().getString("js_peid", null);
if (value == null || "".equals(value)) {// nullで送信するとpsmlが破壊される
return false;
}
Profile profile = ((JetspeedRunData) rundata).getProfile();
Portlets portlets = profile.getDocument().getPortlets();
if (portlets == null) {
return false;
}
Portlets[] portletList = portlets.getPortletsArray();
if (portletList == null) {
return false;
}
PsmlParameter param = null;
int length = portletList.length;
for (int i = 0; i < length; i++) {
Entry[] entries = portletList[i].getEntriesArray();
if (entries == null || entries.length <= 0) {
continue;
}
int ent_length = entries.length;
for (int j = 0; j < ent_length; j++) {
if (entries[j].getId().equals(portletEntryId)) {
boolean hasParam = false;
Parameter params[] = entries[j].getParameter();
int param_len = params.length;
for (int k = 0; k < param_len; k++) {
if (params[k].getName().equals(key)) {
hasParam = true;
params[k].setValue(value);
entries[j].setParameter(k, params[k]);
}
}
if (!hasParam) {
param = new PsmlParameter();
param.setName(key);
param.setValue(value);
entries[j].addParameter(param);
}
break;
}
}
}
profile.store();
} catch (Exception ex) {
logger.error("ALEipUtils.setPsmlParameters", ex);
return false;
}
return true;
}
/**
*
* PSMLに設定されているデータと比較して valueが正しい値ならその値を新しくPSMLに保存。
*
*
* @param rundata
* @param context
* @param config
* @return
*/
public static String passPSML(RunData rundata, Context context, String key,
String value) {
VelocityPortlet portlet = ALEipUtils.getPortlet(rundata, context);
PortletConfig config = portlet.getPortletConfig();
if (value == null || "".equals(value)) {
value = config != null ? config.getInitParameter(key) : "";
} else {
ALEipUtils.setPsmlParameters(rundata, context, key, value);
}
return value;
}
public static boolean isFileUploadable(RunData rundata) {
if (isMatchUserAgent("iPhone", rundata)) {
String iOSver = getIOSVersion(rundata.getUserAgent().trim());
if (iOSver.length() > 1) {
Integer num = Integer.parseInt(iOSver.substring(0, 1));
if (num.intValue() < 6) {
return false;
}
}
}
return true;
}
public static String getIOSVersion(String userAgent) {
Pattern pattern = Pattern.compile("OS\\s[0-9_]+");
Matcher matcher = pattern.matcher(userAgent);
if (matcher.find()) {
String words = matcher.group();
return words.replaceAll("OS\\s", "");
}
return "";
}
public static String getIEVersion(String userAgent) {
Pattern pattern = Pattern.compile("MSIE\\s[0-9_]+");
Matcher matcher = pattern.matcher(userAgent);
Pattern pattern2 = Pattern.compile("rv:[0-9_]+");
Matcher matcher2 = pattern2.matcher(userAgent);
if (matcher.find()) {
String words = matcher.group();
return words.replaceAll("MSIE\\s", "");
} else if (matcher2.find()) {
String words2 = matcher2.group();
return words2.replaceAll("rv:", "");
}
return "";
}
public static Map<String, Entry> getGlobalPortlets(RunData rundata) {
Map<String, Entry> maps = new HashMap<String, Entry>();
Profile profile = ((JetspeedRunData) rundata).getProfile();
if (profile == null) {
User user = rundata.getUser();
if (user != null) {
ProfileLocator locator = Profiler.createLocator();
locator.createFromPath(String.format("user/%s/media-type/html", user
.getUserName()));
try {
profile = Profiler.getProfile(locator);
} catch (ProfileException ignore) {
// ignore
}
}
}
if (profile != null) {
PSMLDocument doc = profile.getDocument();
if (doc != null) {
@SuppressWarnings("unchecked")
Iterator<Entry> iterator = doc.getPortlets().getEntriesIterator();
while (iterator.hasNext()) {
Entry next = iterator.next();
maps.put(next.getParent(), next);
}
}
}
return maps;
}
}
|
package toutiao17.p1;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* Created by shugenniu on 2017/10/17.
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int m = sc.nextInt();
char[][] map = new char[n][m];
for (int i = 0; i < n; i++) {
map[i] = sc.next().toCharArray();
}
int px = 0, py = 0, bx = 0, by = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
//玩家
if (map[i][j] == 'S') {
px = i;
py = j;
}
//箱子
if (map[i][j] == '0') {
bx = i;
by = j;
}
}
}
Map S = new Map(px, py, bx, by);
Map E = resolve(S, map, m, n);
int res = -1;
if (E != null) {
res = 0;
while (E.previous != null) {
res++;
E = E.previous;
}
}
System.out.println(res);
}
}
public static void printMX(char[][] arr) {
for (char[] row : arr) {
for (char cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
public static Map resolve(Map begin, char[][] map, int m, int n) {
Queue<Map> queue = new LinkedList<>();
ArrayList<Map> arrayList = new ArrayList<>();
//表示箱子的移动的方向
int[][] dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
queue.offer(begin);
while (!queue.isEmpty()) {
Map local = queue.remove();
arrayList.add(local);
for (int i = 0; i < dir.length; i++) {
//对上下左右四个方向进行尝试
Map next = new Map(local.px + dir[i][0], local.py + dir[i][1]);
next.previous = local;
//保证箱子不会出界
if (next.px >= 0 && next.px < n && next.py < m && next.py >= 0
&& map[next.px][next.py] != '#') {
//如果人到达了箱子的位置,要箱子换为人的坐标,箱子的坐标想dir[i]移动
if (next.px == local.bx && next.py == local.by) {
next.bx = local.bx + dir[i][0];
next.by = local.by + dir[i][1];
} else {
next.bx = local.bx;
next.by = local.by;
}
if (arrayList.contains(next))
continue;
//如果next节点是合法的节点,则可以将该节点做为最终的节点
if (next.bx >= 0 && next.bx < n && next.by < m && next.by >= 0
&& map[next.bx][next.by] != '#') {
arrayList.add(next);
queue.offer(next);
} else {
continue;
}
//到达最终状态
if (map[next.bx][next.by] == 'E') {
return next;
}
}
}
}
return null;
}
}
class Map {
//玩家坐标
int px;
int py;
//箱子坐标
int bx;
int by;
Map previous;
public Map(int px, int py) {
this.px = px;
this.py = py;
}
public Map(int px, int py, int bx, int by) {
this.px = px;
this.py = py;
this.bx = bx;
this.by = by;
}
// ArrayList 的contains 会隐式的调用对象的equals 方法
public boolean equals(Object obj) {
if (obj instanceof Map) {
if (((Map) obj).px == px && ((Map) obj).py == py && ((Map) obj).bx == bx && ((Map) obj).by == by)
return true;
}
return false;
}
}
|
/*******************************************************************************
* Besiege
* by Kyle Dhillon
* Source Code available under a read-only license. Do not copy, modify, or distribute.
******************************************************************************/
package kyle.game.besiege.title;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldFilter;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.utils.Align;
import kyle.game.besiege.Assets;
import kyle.game.besiege.SoundPlayer;
import kyle.game.besiege.WarchiefGame;
import kyle.game.besiege.MapScreen;
import kyle.game.besiege.party.ClickListenerWithHover;
import kyle.game.besiege.party.UnitLoader;
// TODO separate MainMenuScreen from background.
public class MainMenuScreen implements Screen {
// private static final String TITLE = "CHIEFTAIN";
private static final String TITLE_1 = "C H I E F T A I N";
private static final String TITLE = "W A R C H I E F";
private final int PAD_BELOW_TITLE = 100;
private final int PAD_ABOVE_TITLE = -20;
private final int WIDTH = 500;
private final int SEPARATE = 260;
private final int MAX_NAME = 15;
private final int FIXED_SIZE_BOTTOM = 100;
enum ScreenState{Title, InputName};
ScreenState state;
private WarchiefGame main;
private Stage stage;
private Table mainTable;
private Table lowerTable;
// private Button buttonNew;
// private Button buttonLoad;
private Label labelTitle;
private Label labelNew;
private Label labelLoad;
private Label quickBattle;
private Label about;
private QuickBattleScreen qbs;
private LabelStyle styleTitle;
public static LabelStyle styleButtons = new LabelStyle(Assets.pixel40, Color.WHITE);
TextField tf;
private float count;
private MenuBackground menuBackground;
// private ButtonStyle bs;
public MainMenuScreen(WarchiefGame main) {
this.main = main;
state = ScreenState.Title;
stage = new Stage();
Gdx.input.setInputProcessor(stage);
stage.addListener(new InputListener());
menuBackground = new MenuBackground();
stage.addActor(menuBackground);
mainTable = new Table();
lowerTable = new Table();
// topTable.debug();
mainTable.defaults().expandX().center();
mainTable.setX(0);
mainTable.setY(0);
mainTable.setWidth(WIDTH);
mainTable.setHeight(WarchiefGame.HEIGHT);
lowerTable.defaults().expandX().center();
lowerTable.setX(0);
lowerTable.setY(0);
lowerTable.setWidth(WIDTH);
lowerTable.setHeight(WarchiefGame.HEIGHT / 2);
styleTitle = new LabelStyle();
styleTitle.font = Assets.pixel150;
// bs = new ButtonStyle();
float titleFade = 3.5f;
float titleDelay = 1.5f;
labelTitle = new Label(TITLE, styleTitle);
// labelTitle.addAction(Actions.fadeIn(3));
labelTitle.addAction(Actions.sequence(Actions.alpha(0), Actions.delay(titleDelay), Actions.fadeIn(titleFade)));
float buttonFade = 2f;
float buttonDelay = 3f;
labelNew = new Label("C A M P A I G N", styleButtons);
labelLoad = new Label("L O A D", styleButtons);
labelNew.addAction(Actions.sequence(Actions.alpha(0), Actions.delay(buttonDelay), Actions.fadeIn(buttonFade)));
labelLoad.addAction(Actions.sequence(Actions.alpha(0), Actions.delay(buttonDelay), Actions.fadeIn(buttonFade)));
quickBattle = new Label("Q U I C K B A T T L E", styleButtons);
quickBattle.addAction(Actions.sequence(Actions.alpha(0), Actions.delay(buttonDelay), Actions.fadeIn(buttonFade)));
about = new Label("A B O U T", styleButtons);
about.addAction(Actions.sequence(Actions.alpha(0), Actions.delay(buttonDelay), Actions.fadeIn(buttonFade)));
mainTable.add(labelTitle).padBottom(PAD_BELOW_TITLE).padTop(PAD_ABOVE_TITLE);
mainTable.row();
mainTable.add(lowerTable).height(FIXED_SIZE_BOTTOM);
// mainTable.debug();
labelNew.addListener(new ClickListenerWithHover(labelNew) {
@Override
public void touchUp(InputEvent event, float x, float y,
int pointer, int button) {
clickNew();
}
});
labelLoad.addListener(new ClickListenerWithHover(labelLoad) {
@Override
public void touchUp(InputEvent event, float x, float y,
int pointer, int button) {
clickLoad();
}
});
quickBattle.addListener(new ClickListenerWithHover(quickBattle) {
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
clickQuickBattle();
}
});
about.addListener(new ClickListenerWithHover(about) {
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
clickAbout();
}
});
// lowerTable.debug();
lowerTable.add(labelNew).right().padRight(SEPARATE);
lowerTable.add(labelLoad).left().padLeft(SEPARATE);
lowerTable.row();
lowerTable.add(quickBattle).left().colspan(2).expandX().padTop(25);
lowerTable.row();
// TODO add about screen later
// lowerTable.add(about).left().colspan(2).expandX().padTop(25);
stage.addActor(mainTable);
SoundPlayer.startMusic(UnitLoader.cultureTypes.get("Forest"));
count = 0f;
this.checkForFile();
}
private void setNewOn() {
if (labelNew.getActions().size == 0) {
labelNew.setColor(Color.LIGHT_GRAY);
}
}
public void returnFromOtherPanel(boolean tint) {
stage.clear();
stage.addActor(menuBackground);
stage.addActor(mainTable);
menuBackground.drawWithTint(tint);
}
@Override
public void render(float delta) {
stage.act(delta);
Gdx.gl.glClearColor(.1f,.1f,.1f,0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
SoundPlayer.updateSounds(delta);
mainTable.act(delta);
// check for a file every second
if (count > 1) {
checkForFile();
count = 0;
}
count += delta;
if (Gdx.input.isKeyPressed(Keys.ENTER) &&
state == ScreenState.Title)
this.clickNew();
// Table.drawDebug(stage);
}
private void checkForFile() {
com.esotericsoftware.kryo.io.Input input = null;
try {
FileHandle file = Gdx.files.local(MapScreen.getSaveFileName());
input = new com.esotericsoftware.kryo.io.Input(file.read());
input.close();
this.labelLoad.setVisible(true);
}
catch (Exception e) {
System.out.println("no save file");
this.labelLoad.setVisible(false);
}
}
@Override
public void resize(int width, int height) {
WarchiefGame.HEIGHT = height;
WarchiefGame.WIDTH = width;
mainTable.setWidth(width);
mainTable.setHeight(height);
// lowerTable.setWidth(width);
// lowerTable.setHeight(height/2);
menuBackground.resize(width, height);
// TODO fix resizing here by using a viewport
// topTable.getCells().get(1).padLeft(width-WIDTH).padRight(SEPARATE);
// topTable.getCells().get(2).padRight(width-WIDTH).padLeft(SEPARATE);
// stage
// TODO do we need to update this manually still?
// stage.set(WarchiefGame.WIDTH, WarchiefGame.HEIGHT, false);
}
private void clickNew() {
this.state = ScreenState.InputName;
lowerTable.clear();
Label prompt = new Label("Who are you?", styleButtons);
lowerTable.add(prompt).expandX();
lowerTable.row();
TextFieldStyle tfs = new TextFieldStyle();
tfs.fontColor = Color.WHITE;
tfs.font = Assets.pixel64;
tf = new TextField("", tfs);
// need a second textfield so that it's automatically selected?
TextField tf2 = new TextField("", tfs);
tf2.setVisible(false);
lowerTable.add(tf).center().colspan(2).align(Align.center);
tf.setMaxLength(MAX_NAME);
lowerTable.row();
lowerTable.add(tf2).colspan(2).height(0); // needed to autoselect
tf.next(true);
tf.setTextFieldFilter(new TextFieldFilter() {
public boolean acceptChar(TextField textField, char key) {
expand();
// System.out.println("Hello");
return true;
}
});
tf.addListener(new InputListener() {
public boolean keyDown (InputEvent event, int keyCode) {
if (keyCode == Input.Keys.ENTER) enterName(((TextField)event.getTarget()).getText());
return true;
}
});
tf2.next(false);
}
private void expand() {
this.tf.setWidth(50000);
}
public void clickAbout() {
AboutScreen as = new AboutScreen(main, this, menuBackground);
main.setScreen(as);
menuBackground.drawWithTint(true);
}
public void clickQuickBattle() {
if (qbs != null) {
qbs.returnToThis();
} else {
qbs = new QuickBattleScreen(main, this, menuBackground);
main.setScreen(qbs);
}
}
private void clickLoad() {
// check if null
System.out.println("clicked load");
main.loadMapScreen();
main.setScreen(main.mapScreen);
}
private void enterName(String text) {
System.out.println("User entered: " + text);
if (text.equals("")) text = "Defacto";
main.createMapScreen(text);
// main.setPlayerName(text);
main.setScreen(main.mapScreen);
}
public void addActor(MenuBackground menuBackground) {
stage.addActor(menuBackground);
}
@Override
public void show() {
// TODO Auto-generated method stub
Gdx.input.setInputProcessor(stage);
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}
|
package np_lda;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.List;
import lda.Topic;
import newalgo.Tagger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.PosixParser;
public class StreamSearch extends InferModel<Tweet, Topic>
{
public StreamSearch(CommandLine cli) throws Exception
{
super(cli);
}
public void search() throws Exception
{
Tagger tagger = new Tagger();
String modelFilename = "jar/model.alldata.gz";
tagger.loadModel(modelFilename);
NPLexer lexer = new NPLexer();
double [] p = new double[K];
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine(); //read the header
while((line=br.readLine())!=null)
{
String [] tokens = line.split("\t");
Tweet tweet = new Tweet();
tweet.status_id = Long.parseLong(tokens[0]);
tweet.user_id = Integer.parseInt(tokens[1]);
tweet.content = tokens[2];
tweet.time = Timestamp.valueOf(tokens[3]).getTime();
if(tweet.content.trim().length() <= 2)
{
continue;
}
List<String> nps = TagTweets.findNPs(tagger, lexer, tweet.content);
for(String text : nps)
{
tweet.add(text, stop_words);
}
tweet.init(K);
//first infer the topics of this tweet
for(NounPhrase np : tweet.nps)
{
int z = sample(p, tweet, np);
np.z = z;
tweet.includeTopic(z, np.getWeight());
}
for(int i=0;i<iterations;i++)
{
for(NounPhrase np : tweet.nps)
{
int z = np.z;
tweet.excludeTopic(z, np.getWeight());
z = sample(p, tweet, np);
np.z = z;
tweet.includeTopic(z, np.getWeight());
}
}
double log_mle = countMLE(tweet);
double perplexity;
if(log_mle >= 0)
{
perplexity = 1e99;
}
else
{
perplexity = Math.exp(-log_mle /tweet.getWeight());
}
p = tweet.getTopicDistribution(K);
System.out.print(String.format("%1.4f", p[0]));
for(int k=1;k<K;k++)
{
System.out.print(String.format(",%1.4f", p[k]));
}
System.out.println(String.format("\t%s\t%s\t%d\t%f\t%e", tweet.content, (new Timestamp(tweet.time)).toString(), tweet.time, log_mle, perplexity));
}
br.close();
}
public static void main(String [] args) throws Exception
{
PosixParser parser = new PosixParser();
initOptions();
CommandLine cli = parser.parse(options, args);
StreamSearch model = new StreamSearch(cli);
String line;
BufferedReader br;
br = new BufferedReader(new FileReader(String.format("%s/data/tweets/%s_K=%d.np_lda", model.prefix_dir, model.expt_name, model.K)));
while((line=br.readLine())!=null)
{
String [] tokens = line.split("\t");
Tweet tweet = new Tweet();
tweet.status_id = Long.parseLong(tokens[0]);
tweet.user_id = Integer.parseInt(tokens[1]);
tweet.content = tokens[2];
tweet.time = Long.parseLong(tokens[3]);
while((line = br.readLine()).length() > 0)
{
tokens = line.split("\t");
NounPhrase np = tweet.add(tokens[0], model.stop_words, model.vocabulary);
np.z = Integer.parseInt(tokens[1]);
}
if(tweet.getWeight() > 0)
{
model.tweets.add(tweet);
}
}
br.close();
//End of reading input file
//perform the model inference
model.init();
model.search();
}
}
|
package com.gushiyu.springbootwebcrud;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import com.gushiyu.springbootwebcrud.config.ApplicationStartupUtil;
public class TestCountDownLatch {
@Test
public void testCountDownLatch() {
boolean result = false;
try {
result = ApplicationStartupUtil.checkExternalServices();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("External services validation completed !! Result was :: " + result);
}
@Test
public void test2() {
final CountDownLatch latch = new CountDownLatch(2);
new Thread() {
@Override
public void run() {
try {
System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
Thread.sleep(3000);
System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕.");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
@Override
public void run() {
try {
System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
Thread.sleep(3000);
System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
try {
System.out.println("等待两个线程执行完毕");
latch.await();
System.out.println("两个线程执行完毕");
System.out.println("开始执行主线程");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package test;
import exception.UserNotAuthorizedException;
import model.Comment;
import model.Post;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import service.*;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class CommentServiceImplTest {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestCase.class);
if (result.wasSuccessful()) {
System.out.println("Excellent - Test ran successfully");
} else {
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
}
public static class TestCase {
private UserService userService;
private PostService postService;
private CommentService commentService;
@Before
public void start() {
userService = new UserServiceImpl();
postService = new PostServiceImpl();
commentService = new CommentServiceImpl();
}
@Test
public void testFields() {
Class<?> clazz = CommentServiceImpl.class;
Field[] fields = clazz.getDeclaredFields();
assertTrue("Make sure the fields are correct!", fields.length == 1);
}
@Test
public void testExistsAndInheritsFromObject() {
Class<?> clazz = CommentServiceImpl.class;
assertTrue("Ensure that your file CommentServiceImpl.java extends Objects!", Object.class.isInstance(clazz));
}
@Test
public void testHasAllMethods() {
Method getCommentsByPost;
Method createComment;
Method deleteComment;
Method storeComment;
Method editComment;
Method getCommentsByUser;
try {
getCommentsByPost = CommentService.class.getDeclaredMethod("getCommentsByPost", Post.class);
if (!getCommentsByPost.getReturnType().equals(List.class)) {
fail("Ensure that your getCommentsByPost() method in CommentService return type is of type " +
"List!");
return;
}
} catch (NoSuchMethodException e) {
fail("Ensure that you have a method called getCommentsByPost() in the CommentService interface!");
return;
}
try {
createComment = CommentService.class.getDeclaredMethod("createComment", UUID.class, String.class, String.class);
if (!createComment.getReturnType().equals(Comment.class)) {
fail("Ensure that your createComment() method in CommentService return type is of type " +
"Comment!");
return;
}
} catch (NoSuchMethodException e) {
fail("Ensure that you have a method called createComment() in the CommentService interface!");
return;
}
try {
deleteComment = CommentService.class.getDeclaredMethod("deleteComment", Comment.class, String.class);
if (!deleteComment.getReturnType().equals(void.class)) {
fail("Ensure that your deleteComment() method in CommentService return type is of type " +
"void!");
return;
}
} catch (NoSuchMethodException e) {
fail("Ensure that you have a method called deleteComment() in the CommentService interface!");
return;
}
try {
storeComment = CommentService.class.getDeclaredMethod("storeComment", Comment.class);
if (!storeComment.getReturnType().equals(void.class)) {
fail("Ensure that your storeComment() method in CommentService return type is of type " +
"void!");
return;
}
} catch (NoSuchMethodException e) {
fail("Ensure that you have a method called storeComment() in the CommentService interface!");
return;
}
try {
editComment = CommentService.class.getDeclaredMethod("editComment", UUID.class, UUID.class, String.class, String.class);
if (!editComment.getReturnType().equals(void.class)) {
fail("Ensure that your editComment() method in CommentService return type is of type " +
"void!");
return;
}
} catch (NoSuchMethodException e) {
fail("Ensure that you have a method called editComment() in the CommentService interface!");
return;
}
try {
getCommentsByUser = CommentService.class.getDeclaredMethod("getCommentsByUser", String.class);
if (!getCommentsByUser.getReturnType().equals(List.class)) {
fail("Ensure that your getCommentsByUser() method in CommentService return type is of type " +
"List!");
return;
}
} catch (NoSuchMethodException e) {
fail("Ensure that you have a method called getCommentsByUser() in the CommentService interface!");
return;
}
}
@Test
public void testGetCommentsByPostSuccess() {
deleteFiles();
Post post1 = postService.createPost("content", "testUser");
Post post2 = postService.createPost("more content", "testUser");
commentService.createComment(post1.getUuid(), "testComment", "testUser2");
commentService.createComment(post2.getUuid(), "testComment2", "testUser2");
List<Comment> comments = commentService.getCommentsByPost(post1);
assertTrue("Make sure comments are fetched from the proper post!", comments.size() == 1);
}
@Test
public void testGetCommentsByPostFailure() {
deleteFiles();
//there are no failures for fetching comments
}
@Test
public void testCreateCommentSuccess() {
deleteFiles();
Post post1 = postService.createPost("content", "testUser");
commentService.createComment(post1.getUuid(), "testComment", "testUser2");
List<Comment> comments = commentService.getCommentsByPost(post1);
assertTrue("Make sure a comment was created!", comments.size() == 1);
}
@Test
public void testCreateCommentFailure() {
deleteFiles();
//no failures for creating comments
}
@Test
public void testDeleteCommentSuccess() {
deleteFiles();
Post post1 = postService.createPost("content", "testUser");
Comment comment = commentService.createComment(post1.getUuid(), "testComment", "testUser2");
List<Comment> comments = commentService.getCommentsByPost(post1);
int initialCommentCount = comments.size();
commentService.deleteComment(comment, "testUser2");
comments = commentService.getCommentsByPost(post1);
int finalCommentCount = comments.size();
assertTrue("Make sure the comment was deleted!", initialCommentCount > finalCommentCount);
}
@Test
public void testDeleteCommentFailure() {
deleteFiles();
Post post1 = postService.createPost("content", "testUser");
Comment comment = commentService.createComment(post1.getUuid(), "testComment", "testUser2");
try {
commentService.deleteComment(comment, "another user");
} catch (Exception e) {
assertTrue("Make sure a UserNotAuthorizedException is thrown!", e instanceof UserNotAuthorizedException);
}
}
@Test
public void testStoreCommentSuccess() {
deleteFiles();
Post post1 = postService.createPost("content", "testUser");
Comment comment = new Comment(UUID.randomUUID(), post1.getUuid(), new Date(), "content", "testUser2");
commentService.storeComment(comment);
File directory = new File("comments");
directory.mkdir();
File[] commentFiles = directory.listFiles();
assertTrue("Make sure the comment was properly stored!", commentFiles.length > 0);
}
@Test
public void testStoreCommentFailure() {
deleteFiles();
//no failures for storing comments
}
@Test
public void testEditCommentSuccess() {
deleteFiles();
String createdUsername = "testPost4";
String content = "testPostContent";
String newContent = "newPostContent";
boolean exceptionThrown = false;
Post post = postService.createPost(content, createdUsername);
Comment comment = commentService.createComment(post.getUuid(), "test comment", "testUser");
try {
commentService.editComment(comment.getUuid(), post.getUuid(), "comment edited", "testUser");
} catch (UserNotAuthorizedException e) {
exceptionThrown = true;
} finally {
assertTrue("Make sure UserNotAuthorizedException isn't thrown!", !exceptionThrown);
}
}
@Test
public void testEditCommentFailure() {
deleteFiles();
String createdUsername = "testPost4";
String content = "testPostContent";
String newContent = "newPostContent";
boolean exceptionThrown = false;
Post post = postService.createPost(content, createdUsername);
Comment comment = commentService.createComment(post.getUuid(), "test comment", "testUser");
try {
commentService.editComment(comment.getUuid(), post.getUuid(), "comment edited", "testUser2");
} catch (Exception e) {
assertTrue("Make sure UserNotAuthorizedException is thrown!", e instanceof UserNotAuthorizedException);
}
}
@Test
public void testGetCommentsByUserSuccess() {
deleteFiles();
Post post1 = postService.createPost("content", "testUser");
commentService.createComment(post1.getUuid(), "testComment", "testUser");
commentService.createComment(post1.getUuid(), "testComment2", "testUser2");
List<Comment> commentsByPost = commentService.getCommentsByPost(post1);
List<Comment> commentsByUser = commentService.getCommentsByUser("testUser");
assertTrue("Make sure comments are fetched from the proper user!", commentsByPost.size() != commentsByUser.size());
}
@Test
public void testGetCommentsByUserFailure() {
deleteFiles();
//no failures for fetching comments by a user
}
private void deleteFiles() {
File directory = new File("comments");
directory.mkdir();
File[] userFiles = directory.listFiles();
for (File file : userFiles) {
file.delete();
}
directory = new File("posts");
directory.mkdir();
userFiles = directory.listFiles();
for (File file : userFiles) {
file.delete();
}
directory = new File("users");
directory.mkdir();
userFiles = directory.listFiles();
for (File file : userFiles) {
file.delete();
}
}
}
}
|
package com.example.structural.proxy;
/**
* Copyright (C), 2020
* FileName: Subject
*
* @author: xieyufeng
* @date: 2020/10/20 18:42
* @description:
*/
public interface Subject {
public void proxySubject();
}
|
package com.xiaoxiao.service;
import com.xiaoxiao.pojo.vo.XiaoxiaoLeaveMessageVo;
import com.xiaoxiao.utils.PageResult;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/19:15:53
* @author:shinelon
* @Describe:
*/
public interface RedisLeaveMessageService
{
/**
* 缓存
* @param leaveMessage
* @param page
*/
void insertLeaveMessage(PageResult leaveMessage, Integer page);
/**
* 获取
* @param page
* @return
*/
PageResult getLeaveMessage(Integer page);
/**
* 删除
*/
void deleteLeaveMessage();
/**
* 缓存留言数
* @param leaveMessageVo
*/
void insertLeaveMessageSum(XiaoxiaoLeaveMessageVo leaveMessageVo);
/**
* 获取的留言总数
* @return
*/
XiaoxiaoLeaveMessageVo getLeaveMessageSum();
/**
* 删除留言总数
*/
void deleteLeaveMessageSum();
}
|
package utils;
public class Classe extends Personagem {
public Classe()
{
}
}
|
package com.xjy.person.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import org.pmw.tinylog.Logger;
/**
* 第一个测试类.
*/
public class HelloWord {
/**
* 私有构造方法.
*/
private HelloWord() {
super();
}
/**
* main方法.
* @param args 数组参数
*/
public static void main(String[] args) {
URL banner = HelloWord.class.getResource("/banner.txt");
if (banner == null) {
Logger.info("未获取到banner.txt文件!");
return;
}
File file = new File(banner.getPath());
Logger.info(txt2String(file));
}
/**
* 读取txt文件的内容.
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
private static String txt2String(File file) {
StringBuilder sb = new StringBuilder("");
//构造一个BufferedReader类来读取文件
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String s;
//使用readLine方法,一次读一行
while ((s = br.readLine()) != null) {
sb.append(System.lineSeparator()).append(s);
}
} catch (Exception e) {
Logger.error(e, "读取文件");
}
return sb.toString();
}
}
|
package com.jst.mapper.question;
import java.util.List;
import java.util.Map;
import com.jst.model.QuestionsComment;
public interface QuestionsCommentMapper {
// 查询
public List<QuestionsComment> listAll(Map map);
// 添加
public void save(QuestionsComment questionsComment);
// 删除
public void delete(int qcid);
// 根据id查询全部
public QuestionsComment getById(int qcid);
// 修改
public void update(QuestionsComment questionsComment);
// 查看回复
public List<QuestionsComment> getqId(int qid);
// 采纳为最佳
public void updateIsBest(int qcid);
//点赞
public void updatepraise(int id);
public List<QuestionsComment> getById2(int qid);
public List<QuestionsComment> getById3(int qid);
public List<QuestionsComment> getListById(int commentId);
// 回复数量修改
public void updateReplyCount(int qcid);
public List<QuestionsComment> getListById2(int commentId);
}
|
package com.tencent.mm.plugin.mmsight.segment.a;
import com.tencent.mm.plugin.u.c;
import com.tencent.mm.sdk.platformtools.x;
class b$1 implements c {
final /* synthetic */ b lnH;
b$1(b bVar) {
this.lnH = bVar;
}
public final void iy() {
if (this.lnH.lnF != null) {
this.lnH.lnF.bG(this.lnH.lnz);
}
if (this.lnH.bTv) {
this.lnH.lnz.start();
}
this.lnH.Fd = true;
}
public final void wd() {
if (this.lnH.dGv) {
this.lnH.lnz.sG(this.lnH.lnB);
}
}
public final void onError(int i, int i2) {
if (this.lnH.lnD != null) {
this.lnH.lnD.cS(i, i2);
}
}
public final void bdq() {
x.i("MicroMsg.MMSegmentVideoPlayer", "onSeekComplete, onSeekCompleteListener: %s", new Object[]{this.lnH.lnG});
if (this.lnH.lnG != null) {
this.lnH.lnG.bH(this.lnH.lnz);
} else if (this.lnH.bTv) {
this.lnH.lnz.start();
}
}
public final void N(int i, int i2, int i3) {
this.lnH.lnA = i3;
if (this.lnH.lnE != null) {
this.lnH.lnE.P(i, i2, i3);
}
}
}
|
package com.upu.zenka.broadcasttest.model;
import com.upu.zenka.broadcasttest.bean.ApinfoBean;
import com.upu.zenka.broadcasttest.bean.BkbroadcastBean;
import com.upu.zenka.broadcasttest.bean.DownloadBean;
import com.upu.zenka.broadcasttest.bean.broadcastBean;
import com.upu.zenka.broadcasttest.bean.exceptionBean;
import com.upu.zenka.broadcasttest.bean.nettestBean;
import com.upu.zenka.broadcasttest.bean.uploadBean;
import com.upu.zenka.broadcasttest.bean.vertifyBean;
import com.upu.zenka.broadcasttest.callback.ModelCallBack;
import com.upu.zenka.broadcasttest.tools.GetDataInterface;
import com.upu.zenka.broadcasttest.tools.publicParam;
import com.upu.zenka.broadcasttest.util.OffretrofitUtils;
import com.upu.zenka.broadcasttest.util.RetrofitUnitl;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
/**
* Created by ThinkPad on 2018/11/13.
*/
public class GetbroadcastModel {
public void getApinfo(String schoolid,String deviceid,final ModelCallBack.getApinfoCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("schoolid",schoolid);
map.put("deviceid",deviceid);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.getapinfo(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ApinfoBean>(){
@Override
public void accept(ApinfoBean apinfoBean) throws Exception {
callBack.success(apinfoBean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void getBkBroadcastData(String schoolid,String classid,final ModelCallBack.getBkBroadcastCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("schoolid",schoolid);
map.put("classid",classid);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.getBkbroadcast(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<BkbroadcastBean>(){
@Override
public void accept(BkbroadcastBean bkbroadcastBean) throws Exception {
callBack.success(bkbroadcastBean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void getBroadcastData(String schoolid,String classid,final ModelCallBack.BroadcastCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("classid",classid);
map.put("schoolid",schoolid);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.getbroadcast(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<broadcastBean>(){
@Override
public void accept(broadcastBean broadcastbean) throws Exception {
callBack.success(broadcastbean);
System.out.println("广播信息:"+broadcastbean.toString());
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void getOffBroadcastData(String schoolid,String classid,String serverip,boolean iscreat,final ModelCallBack.BroadcastCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30,TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
if (classid==null){
map.put("classid","");
}else{
map.put("classid",classid);
}
map.put("schoolid",schoolid);
OffretrofitUtils.getInstance("http://"+serverip+":8080/",ok,iscreat)
.setCreate(GetDataInterface.class)
.getOfflinebroadcast("",map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<broadcastBean>(){
@Override
public void accept(broadcastBean broadcastbean) throws Exception {
callBack.success(broadcastbean);
System.out.println("广播信息:"+broadcastbean.toString());
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void vertify(final String deviceid,final ModelCallBack.VertifyCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.verify(deviceid)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<vertifyBean>(){
@Override
public void accept(vertifyBean vertifybean) throws Exception {
callBack.success(vertifybean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void netTest(String deviceid,String schoolid,final ModelCallBack.netTestCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("deviceid",deviceid);
map.put("schoolid",schoolid);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.netTest(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<nettestBean>(){
@Override
public void accept(nettestBean nettestbean) throws Exception {
callBack.success(nettestbean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void sentException(String appname,String deviceid,String exception,String time,final ModelCallBack.sentExceptionCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("app",appname);
map.put("deviceid", deviceid);
map.put("exception", exception);
map.put("exception_time",time);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.sentException(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<exceptionBean>(){
@Override
public void accept(exceptionBean exceptionbean) throws Exception {
callBack.success(exceptionbean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void downLodaServerInfo(String deviceid,final ModelCallBack.downloadInfoCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("deviceid", deviceid);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.downloadInfo(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<DownloadBean>(){
@Override
public void accept(DownloadBean downloadBean) throws Exception {
callBack.success(downloadBean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
public void upload(String deviceid,String ip,String version,final ModelCallBack.uploadInfoCallBack callBack){
OkHttpClient ok=new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build();
Map<String,String> map=new HashMap<>();
map.put("deviceid", deviceid);
map.put("ip",ip);
map.put("version",version);
RetrofitUnitl.getInstance(publicParam.BASE_URL,ok)
.setCreate(GetDataInterface.class)
.upload(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<uploadBean>(){
@Override
public void accept(uploadBean uploadbean) throws Exception {
callBack.success(uploadbean);
}
},new Consumer<Throwable>(){
@Override
public void accept(Throwable throwable) throws Exception{
callBack.failed(throwable);
}
});
}
}
|
package Keming;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Node {
static Node[] nodes = new Node[100];
String id;
ArrayList<Node> children;
public Node(String string) {
id = string;
}
public static void graphInit() throws IOException {
FileOutputStream fos = new FileOutputStream(new File("GraphSchema"));
for(int i=0; i<99; i++) {
Node node = new Node(new Integer(i).toString());
nodes[i]= node;
Node parentNode = nodes[ (int) (Math.random() * i) ];
if( parentNode.children == null ) {
parentNode.children = new ArrayList<Node>();
}
parentNode.children.add(node);
String output = String.format("%s %d,", parentNode.id, i);
System.out.printf(output);
fos.write(output.getBytes());
}
fos.close();
}
public static void printr(Node node, String indent) {
System.out.println(indent + node.id);
ArrayList<Node> children = node.children;
if(children!=null) {
for(int i=0; i<children.size(); i++) {
Node child = children.get(i);
if( i < children.size() - 1 ) {
printr(child, indent + "\t");
} else {
printr(child, indent + "\t");
}
}
}
}
public static void printr2(Node node, String path) {
System.out.println(path + node.id);
ArrayList<Node> children = node.children;
if(children!=null) {
for(int i=0; i<children.size(); i++) {
Node child = children.get(i);
if( i < children.size() - 1 ) {
printr2(child, path + node.id + "\\");
} else {
printr2(child, path + node.id + "\\");
}
}
}
}
public static void main(String[] argv) throws IOException {
graphInit();
for(int i=1; i<9; i++) {
printr2( nodes[i], "");
}
}
}
|
package com.wisape.android.activity;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
/**
* @author Duke
*/
public class BaseCompatActivity extends AppCompatActivity {
private boolean destroyed;
@Override
protected void onDestroy() {
if(17 > Build.VERSION.SDK_INT){
destroyed = true;
}
super.onDestroy();
}
public boolean isDestroyed() {
if(17 > Build.VERSION.SDK_INT){
return destroyed;
}else{
return super.isDestroyed();
}
}
}
|
package com.uwetrottmann.trakt5.entities;
import javax.annotation.Nonnull;
public class MovieIds extends BaseIds {
public String slug;
@Nonnull
public static MovieIds trakt(int trakt) {
MovieIds ids = new MovieIds();
ids.trakt = trakt;
return ids;
}
@Nonnull
public static MovieIds imdb(String imdb) {
MovieIds ids = new MovieIds();
ids.imdb = imdb;
return ids;
}
@Nonnull
public static MovieIds tmdb(int tmdb) {
MovieIds ids = new MovieIds();
ids.tmdb = tmdb;
return ids;
}
@Nonnull
public static MovieIds slug(String slug) {
MovieIds ids = new MovieIds();
ids.slug = slug;
return ids;
}
}
|
package controller;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.concurrent.Phaser;
import application.CompanyMain;
import application.InventoryMain;
import application.LoginMain;
import application.ReportMain;
import application.TradeListMain;
import dao.CompanyDAO;
import dao.InventoryDAO;
import dao.TradeListDAO;
import javafx.stage.Stage;
import model.CompanyModel;
import model.Inventory;
import model.TradeListModel;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
public class InventoryManagementController implements Initializable {
@FXML
private Tab tabInventory;
@FXML
private Tab tabPurchase;
@FXML
private Tab tabSell;
@FXML
private Button btnInventory;
@FXML
private Button btnTrade;
@FXML
private Button btnReport;
@FXML
private Button btnCompany;
@FXML
private Button btnLogout;
@FXML
private Button btnOk;
@FXML
private Button btnEdit;
@FXML
private Button btnDelete;
@FXML
private Button btnSearch1;
@FXML
private Button btnSearch2;
@FXML
private Button btnSearch3;
@FXML
private Button btnReset1;
@FXML
private Button btnReset2;
@FXML
private Button btnReset3;
@FXML
private Button btnCal1;
@FXML
private Button btnCal2;
@FXML
private Button btnPurchase;
@FXML
private Button btnSell;
@FXML
private TextField txtSearch1;
@FXML
private TextField txtCompany1;
@FXML
private TextField txtProduct1;
@FXML
private TextField txtProductNumber1;
@FXML
private TextField txtStock1;
@FXML
private TextField txtPurchase1;
@FXML
private TextField txtSell1;
@FXML
private TextField txtType1;
@FXML
private TextField txtColor1;
@FXML
private TextField txtSize1;
@FXML
private TextField txtSearch2;
@FXML
private TextField txtCompany2;
@FXML
private TextField txtProduct2;
@FXML
private TextField txtProductNumber2;
@FXML
private TextField txtStock2;
@FXML
private TextField txtPurchase2;
@FXML
private TextField txtType2;
@FXML
private TextField txtColor2;
@FXML
private TextField txtSize2;
@FXML
private TextField txtOrder1;
@FXML
private TextField txtTotalPurchase;
@FXML
private TextField txtSearch3;
@FXML
private TextField txtCompany3;
@FXML
private TextField txtProduct3;
@FXML
private TextField txtProductNumber3;
@FXML
private TextField txtStock3;
@FXML
private TextField txtSell2;
@FXML
private TextField txtType3;
@FXML
private TextField txtColor3;
@FXML
private TextField txtSize3;
@FXML
private TextField txtOrder2;
@FXML
private TextField txtTotalSell;
// 재고 탭 콤보박스
@FXML
private ComboBox cmbCompany1;
@FXML
private ComboBox cmbType4;
@FXML
private ComboBox cmbColor4;
@FXML
private ComboBox cmbSize4;
@FXML
private ComboBox cmbCompany4;
// 주문 탭 콤보박스
@FXML
private ComboBox cmbCompany2;
@FXML
private ComboBox cmbType2;
@FXML
private ComboBox cmbSize2;
@FXML
private ComboBox cmbColor2;
// 판매 탭 콤보박스
@FXML
private ComboBox cmbCompany3;
@FXML
private ComboBox cmbType3;
@FXML
private ComboBox cmbSize3;
@FXML
private ComboBox cmbColor3;
@FXML
private ComboBox cmbCompany5;
@FXML
private TableView tvInventory1;
@FXML
private TableView tvInventory2;
@FXML
private TableView tvInventory3;
@FXML
private RadioButton rdoRegister;
@FXML
private RadioButton rdoEdit;
public Stage inventoryStage;
private ObservableList<Inventory> obList;
private ObservableList<Inventory> obList2;
private ObservableList<String> obList1;
private ObservableList<String> obList3;
private ObservableList<CompanyModel> obList4;
private ObservableList<CompanyModel> obList5;
private int tvInventoryIndex = -1;
private int cmbselect = 0;
private String production = "생산";
private String production2 = "소비";
private String purchase = "주문";
private String sell = "판매";
private ArrayList<Inventory> arrayList = null;
private ArrayList<CompanyModel> arrayList2 = null;// 콤보박스에 들어간 소비업체 객체정보 기억
public InventoryManagementController() {
this.inventoryStage = null;
this.obList = FXCollections.observableArrayList();
this.obList1 = FXCollections.observableArrayList();
this.obList2 = FXCollections.observableArrayList();
this.obList3 = FXCollections.observableArrayList();
this.obList5 = FXCollections.observableArrayList();
this.arrayList = new ArrayList<Inventory>();
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// 다른 화면으로 이동 버튼
btnCompany.setOnAction(e -> handleBtnCompanyAction());
btnTrade.setOnAction(e -> handleBtnTradeAction());
btnReport.setOnAction(e -> handleBtnReportAction());
btnLogout.setOnAction(e -> handleBtnLogoutAction());
// 탭 이동시 리스트 초기화
tabInventory.setOnSelectionChanged(e -> selectTabInventoryAction());
tabPurchase.setOnSelectionChanged(e -> selectTabPurchaseAction());
tabSell.setOnSelectionChanged(e -> selectTabSellAction());
tvInventory1Column(); // 재고 리스트 컬럼
tvInventory2Column(); // 주문 리스트 컬럼
tvInventory3Column(); // 판매 리스트 컬럼
totalLoadList(); // 전체 재고 리스트
registerFormat();// 등록 text 포맷
companyComboBoxList();
typeComboBoxList();
colorComboBoxList();
sizeComboBoxList();
radioButtonGroup();// 등록 수정 group
cmbCompany4.setOnAction(e -> cmbselect = cmbCompany4.getSelectionModel().getSelectedIndex());
// 목록 클릭시 이벤트
tvInventory1.setOnMouseClicked(e -> handleTvinventory1MouseClicked(e));
tvInventory2.setOnMouseClicked(e -> handleTvinventory2MouseClicked(e));
tvInventory3.setOnMouseClicked(e -> handleTvinventory3MouseClicked(e));
btnOk.setOnAction(e -> handleBtnOkAction(e)); // 등록 버튼
btnEdit.setOnAction(e -> handleBtnEditAction(e)); // 수정 버튼
btnDelete.setOnAction(e -> handleBtnDeleteAction(e)); // 삭제버튼
btnSearch1.setOnAction(e -> handleBtnSearch1Action(e)); // 재고 화면 검색버튼
btnSearch2.setOnAction(e -> handleBtnSearch2Action(e)); // 주문 화면 검색버튼
btnSearch3.setOnAction(e -> handleBtnSearch3Action(e)); // 판매 화면 검색버튼
btnCal1.setOnAction(e -> handleBtnCal1Action(e)); // 구매총액 계산 버튼
btnPurchase.setOnAction(e -> handleBtnPurchaseAction(e)); // 구매 버튼
btnCal2.setOnAction(e -> handleBtnCal2Action(e)); // 판매총액 계산 버튼
btnSell.setOnAction(e -> handleBtnSellAction(e)); // 판매 버튼
btnReset1.setOnAction(e -> handleBtnReset1Action(e)); // 재고 화면 초기화 버튼
btnReset2.setOnAction(e -> handleBtnReset2Action(e)); // 주문 화면 초기화 버튼
btnReset3.setOnAction(e -> handleBtnReset3Action(e)); // 판매 화면 초기화 버튼
rdoRegister.setOnAction(e -> handleRdoRegisterAction());// 등록 rdoButton 눌렀을 때 이벤트
rdoEdit.setOnAction(e -> handleRdoEditAction());// 수정 rdoButton 눌렀을 때 이벤트
}// initialize
// toggleGroup init
private void radioButtonGroup() {
ToggleGroup tg = new ToggleGroup();
rdoRegister.setToggleGroup(tg);
rdoEdit.setToggleGroup(tg);
// default 설정
rdoRegister.setSelected(true);
btnEdit.setVisible(false);
}
// 수정 rdoButton 눌렀을 때 이벤트
private void handleRdoEditAction() {
btnEdit.setVisible(true);
btnOk.setVisible(false);
}
// 등록 rdoButton 눌렀을 때 이벤트
private void handleRdoRegisterAction() {
btnEdit.setVisible(false);
btnOk.setVisible(true);
//클리어
tvInventoryIndex = -1;
txtSearch1.clear();
txtProduct1.clear();
txtProductNumber1.clear();
txtStock1.clear();
txtPurchase1.clear();
txtSell1.clear();
cmbCompany4.getSelectionModel().clearSelection();
cmbType4.getSelectionModel().clearSelection();
cmbColor4.getSelectionModel().clearSelection();
cmbSize4.getSelectionModel().clearSelection();
}
// 제품 등록시 입력 포멧 설정
private void registerFormat() {
// 제품번호 7자리로 한정
DecimalFormat cmNumber = new DecimalFormat("#######");
txtProductNumber1.setTextFormatter(new TextFormatter<>(e -> {
// 글자를 입력해서 빈 '공백'이면 다시 이벤트를 돌려줌
if (e.getControlNewText().isEmpty()) {
return e;
}
// 위치조사( 키보드 치는 위치를 추적한다.)
ParsePosition parsePosition = new ParsePosition(0);
// 숫자만 받겠다.
Object object = cmNumber.parse(e.getControlNewText(), parsePosition);
int number = Integer.MAX_VALUE;
if (object == null || e.getControlNewText().length() >= 8) {
return null; // 입력한 값을 안받겠다.
} else {
return e;
}
}));
// 제품명 최대 45자리
txtProduct1.setOnKeyTyped(event -> {
int maxCharacters = 44;
if (txtProduct1.getText().length() > maxCharacters)
event.consume();
});
// 재고 최대 5자리
DecimalFormat stockFormat = new DecimalFormat("#####");
txtStock1.setTextFormatter(new TextFormatter<>(e -> {
// 글자를 입력해서 빈 '공백'이면 다시 이벤트를 돌려줌
if (e.getControlNewText().isEmpty()) {
return e;
}
// 위치조사( 키보드 치는 위치를 추적한다.)
ParsePosition parsePosition = new ParsePosition(0);
// 숫자만 받겠다.
Object object = stockFormat.parse(e.getControlNewText(), parsePosition);
int number = Integer.MAX_VALUE;
if (object == null || e.getControlNewText().length() >= 6) {
return null; // 입력한 값을 안받겠다.
} else {
return e;
}
}));
// 구입가 최대 4자리
DecimalFormat txtPurchase1Format = new DecimalFormat("####");
txtPurchase1.setTextFormatter(new TextFormatter<>(e -> {
// 글자를 입력해서 빈 '공백'이면 다시 이벤트를 돌려줌
if (e.getControlNewText().isEmpty()) {
return e;
}
// 위치조사( 키보드 치는 위치를 추적한다.)
ParsePosition parsePosition = new ParsePosition(0);
// 숫자만 받겠다.
Object object = txtPurchase1Format.parse(e.getControlNewText(), parsePosition);
int number = Integer.MAX_VALUE;
if (object == null || e.getControlNewText().length() >= 5) {
return null; // 입력한 값을 안받겠다.
} else {
return e;
}
}));
// 판매가 최대 4자리
DecimalFormat txtSell1Format = new DecimalFormat("####");
txtSell1.setTextFormatter(new TextFormatter<>(e -> {
// 글자를 입력해서 빈 '공백'이면 다시 이벤트를 돌려줌
if (e.getControlNewText().isEmpty()) {
return e;
}
// 위치조사( 키보드 치는 위치를 추적한다.)
ParsePosition parsePosition = new ParsePosition(0);
// 숫자만 받겠다.
Object object = txtSell1Format.parse(e.getControlNewText(), parsePosition);
int number = Integer.MAX_VALUE;
if (object == null || e.getControlNewText().length() >= 5) {
return null; // 입력한 값을 안받겠다.
} else {
return e;
}
}));
}
private void sizeComboBoxList() {
cmbSize4.setItems(FXCollections.observableArrayList("성인용", "어린이용"));
cmbSize4.setPromptText("사이즈 선택");
}
private void colorComboBoxList() {
cmbColor4.setItems(FXCollections.observableArrayList("흰색", "검정색"));
cmbColor4.setPromptText("색상 선택");
}
private void typeComboBoxList() {
cmbType4.setItems(FXCollections.observableArrayList("KF80", "KF94", "덴탈 마스크", "면 마스크"));
cmbType4.setPromptText("종류 선택");
}
// 보고서 화면으로 이동 버튼
private void handleBtnReportAction() {
try {
new ReportMain().start(inventoryStage);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 로그인 화면으로 이동 버튼
private void handleBtnLogoutAction() {
try {
new LoginMain().start(new Stage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
inventoryStage.close();
}
// 거래 내역 화면으로 이동 버튼
private void handleBtnTradeAction() {
try {
new TradeListMain().start(inventoryStage);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 업체 관리 화면으로 이동 버튼
private void handleBtnCompanyAction() {
try {
new CompanyMain().start(inventoryStage);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 탭 선택시 리스트 초기화 이벤트
private void selectTabInventoryAction() {
txtSearch1.clear();
txtProduct1.clear();
txtProductNumber1.clear();
txtStock1.clear();
txtPurchase1.clear();
txtSell1.clear();
cmbType4.getSelectionModel().clearSelection();
cmbColor4.getSelectionModel().clearSelection();
cmbSize4.getSelectionModel().clearSelection();
cmbCompany4.getSelectionModel().clearSelection();
obList.clear();
totalLoadList();
}
private void selectTabPurchaseAction() {
txtSearch2.clear();
txtCompany2.clear();
txtProduct2.clear();
txtProductNumber2.clear();
txtStock2.clear();
txtPurchase2.clear();
txtType2.clear();
txtColor2.clear();
txtSize2.clear();
txtOrder1.clear();
txtTotalPurchase.clear();
obList.clear();
totalLoadList();
}
private void selectTabSellAction() {
txtSearch3.clear();
cmbCompany5.getSelectionModel().clearSelection();
txtCompany3.clear();
txtProduct3.clear();
txtProductNumber3.clear();
txtStock3.clear();
txtSell2.clear();
txtType3.clear();
txtColor3.clear();
txtSize3.clear();
txtOrder2.clear();
txtTotalSell.clear();
obList.clear();
totalLoadList();
}
// 판매 버튼 이벤트
private void handleBtnSellAction(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
TradeListDAO tradelistDAO = new TradeListDAO();
Inventory iv = obList.get(tvInventoryIndex);
int returnValue = 0;
int currentStock = iv.getStock();
int sOrder = Integer.parseInt(txtOrder2.getText());
if (currentStock < 10) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("에러");
alert.setHeaderText("재고가 부족합니다");
alert.setContentText("재고 주문 필요");
alert.showAndWait();
return;
}
Calendar cal = Calendar.getInstance();
int second = cal.get(Calendar.YEAR);
int minute = cal.get(Calendar.MONTH) + 1;
int hour = cal.get(Calendar.DAY_OF_MONTH);
// 거래가 이뤼지는 시스템 날짜를 받는 문
String s = String.valueOf(second) + "-" + String.valueOf(minute) + "-" + String.valueOf(hour);
// 콤보박스에서 선택된 소비업체의 업체번호를 받아오기 위한 문
CompanyModel c = arrayList2.get(cmbCompany5.getSelectionModel().getSelectedIndex());
int returnValue2 = tradelistDAO.registrationPurchaseOrSell(Integer.parseInt(txtOrder2.getText()),
txtTotalSell.getText(), s, sell, c.getCompany_number(), iv.getProductNumber());
int editStock = (currentStock - sOrder);
iv.setStock(editStock);
returnValue = inventoryDAO.getProductSell(iv);
if (returnValue != 0 && returnValue2 != 0) {
obList.set(tvInventoryIndex, iv);
inventoryDAO.getTotalLoadList();
}
handleBtnReset1Action(e);
} catch (Exception e1) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Edit Error");
alert.setHeaderText("재고 선택 오류");
alert.setContentText("판매할 재고를 선택하시오");
alert.showAndWait();
}
}
// 구매 버튼 이벤트
private void handleBtnPurchaseAction(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
TradeListDAO tradelistDAO = new TradeListDAO();
Calendar cal = Calendar.getInstance();
int second = cal.get(Calendar.YEAR);
int minute = cal.get(Calendar.MONTH) + 1;
int hour = cal.get(Calendar.DAY_OF_MONTH);
String s = String.valueOf(second) + "-" + String.valueOf(minute) + "-" + String.valueOf(hour);
Inventory inven = arrayList.get(tvInventoryIndex);
int returnValue2 = tradelistDAO.registrationPurchaseOrSell(Integer.parseInt(txtOrder1.getText()),
txtTotalPurchase.getText(), s, purchase, inven.getCompanyNumber(), inven.getProductNumber());
Inventory iv = obList.get(tvInventoryIndex);
int currentStock = iv.getStock();
int pOrder = Integer.parseInt(txtOrder1.getText());
int editStock = (currentStock + pOrder);
iv.setStock(editStock);
int returnValue = inventoryDAO.getProductPurchase(iv);
if (returnValue != 0 && returnValue2 != 0) {
obList.set(tvInventoryIndex, iv);
inventoryDAO.getTotalLoadList();
}
handleBtnReset1Action(e);
} catch (Exception e1) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Edit Error");
alert.setHeaderText("재고 선택 오류");
alert.setContentText("구매할 재고를 선택하시오");
alert.showAndWait();
}
}
// 판매 총액 계산 이벤트
private void handleBtnCal2Action(ActionEvent e) {
try {
int order = Integer.parseInt(txtOrder2.getText());
int purchase = Integer.parseInt(txtSell2.getText());
int totalPrice = order * purchase;
txtTotalSell.setText(String.valueOf(totalPrice));
} catch (Exception e1) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("재고 입력 오류");
alert.setContentText("판매 수량을 입력 하시오");
alert.showAndWait();
}
}
// 구매 총액 계산 이벤트
private void handleBtnCal1Action(ActionEvent e) {
try {
int order = Integer.parseInt(txtOrder1.getText());
int purchase = Integer.parseInt(txtPurchase2.getText());
int totalPrice = order * purchase;
txtTotalPurchase.setText(String.valueOf(totalPrice));
} catch (Exception e1) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("재고 입력 오류");
alert.setContentText("구매 수량을 입력 하시오");
alert.showAndWait();
}
}
// 재고 화면 검색 버튼
private void handleBtnSearch1Action(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
if (txtSearch1.getText().trim().equals("")) {
throw new Exception();
}
ArrayList<Inventory> arrList = inventoryDAO.getProductSearch(txtSearch1.getText().trim());
if (arrList.size() != 0) {
obList.clear();
for (int i = 0; i < arrList.size(); i++) {
Inventory inven = arrList.get(i);
obList.add(inven);
}
}
} catch (Exception event) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Search Error");
alert.setHeaderText("검색할 제품 번호를 입력하시오");
alert.setContentText("제품 번호를 입력하시오");
alert.showAndWait();
}
}
// 주문 화면 검색 버튼
private void handleBtnSearch2Action(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
if (txtSearch2.getText().trim().equals("")) {
throw new Exception();
}
ArrayList<Inventory> arrList = inventoryDAO.getProductSearch(txtSearch2.getText().trim());
if (arrList.size() != 0) {
obList.clear();
for (int i = 0; i < arrList.size(); i++) {
Inventory inven = arrList.get(i);
obList.add(inven);
}
}
} catch (Exception event) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Search Error");
alert.setHeaderText("검색할 제품 번호를 입력하시오");
alert.setContentText("제품 번호를 입력하시오");
alert.showAndWait();
}
}
// 판매 화면 검색 버튼
private void handleBtnSearch3Action(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
if (txtSearch3.getText().trim().equals("")) {
throw new Exception();
}
ArrayList<Inventory> arrList = inventoryDAO.getProductSearch(txtSearch3.getText().trim());
if (arrList.size() != 0) {
obList.clear();
for (int i = 0; i < arrList.size(); i++) {
Inventory inven = arrList.get(i);
obList.add(inven);
}
}
} catch (Exception event) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Search Error");
alert.setHeaderText("검색할 제품 번호를 입력하시오");
alert.setContentText("제품 번호를 입력하시오");
alert.showAndWait();
}
}
// 등록 버튼 이벤트
private void handleBtnOkAction(ActionEvent e) {
InventoryDAO inventoryDAO = new InventoryDAO();
Inventory iv = null;
try {
iv = new Inventory(txtProductNumber1.getText(), txtProduct1.getText(),
Integer.parseInt(txtStock1.getText()), Integer.parseInt(txtPurchase1.getText()),
Integer.parseInt(txtSell1.getText()), cmbType4.getSelectionModel().getSelectedItem().toString(),
cmbSize4.getSelectionModel().getSelectedItem().toString(),
cmbColor4.getSelectionModel().getSelectedItem().toString(),
cmbCompany4.getSelectionModel().getSelectedItem().toString(),
String.valueOf(obList5.get(cmbselect).getCompany_number()));
handleBtnReset1Action(e);
} catch (Exception e1) {
}
int returnValue = inventoryDAO.getInventoryRegist(iv);
if (returnValue != 0) {
obList.clear();
totalLoadList();
}
}
// 수정 버튼 이벤트
private void handleBtnEditAction(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
Inventory inven = obList.get(tvInventoryIndex);
inven.setProduct(txtProduct1.getText());
inven.setPurchase(Integer.parseInt(txtPurchase1.getText()));
inven.setSell(Integer.parseInt(txtSell1.getText()));
inven.setType(cmbType4.getSelectionModel().getSelectedItem().toString());
inven.setSize(cmbSize4.getSelectionModel().getSelectedItem().toString());
inven.setColor(cmbColor4.getSelectionModel().getSelectedItem().toString());
int returnValue = inventoryDAO.getInventoryUpdate(inven);
if (returnValue != 0) {
obList.set(tvInventoryIndex, inven);
}
} catch (Exception e1) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Edit Error");
alert.setHeaderText("재고 선택 오류");
alert.setContentText("수정할 재고를 선택하시오");
alert.showAndWait();
}
}
// 재고 리스트에서 목록 선택시 이벤트
private void handleTvinventory1MouseClicked(MouseEvent e) {
if (rdoEdit.isSelected()) {
tvInventoryIndex = tvInventory1.getSelectionModel().getSelectedIndex();
try {
Inventory inventory = obList.get(tvInventoryIndex);
txtProductNumber1.setText(String.valueOf(inventory.getProductNumber()));
txtProduct1.setText(inventory.getProduct());
txtStock1.setText(String.valueOf(inventory.getStock()));
txtPurchase1.setText(String.valueOf(inventory.getPurchase()));
txtSell1.setText(String.valueOf(inventory.getSell()));
cmbCompany4.getSelectionModel().select(inventory.getCompanyName());
cmbType4.getSelectionModel().select(inventory.getType());
cmbColor4.getSelectionModel().select(inventory.getColor());
cmbSize4.getSelectionModel().select(inventory.getSize());
} catch (Exception e1) {
}
} else {
return;
}
}
private void handleTvinventory2MouseClicked(MouseEvent e) {
tvInventoryIndex = tvInventory2.getSelectionModel().getSelectedIndex();
try {
Inventory inventory = obList.get(tvInventoryIndex);
txtProductNumber2.setText(String.valueOf(inventory.getProductNumber()));
txtCompany2.setText(inventory.getCompanyName());
txtProduct2.setText(inventory.getProduct());
txtStock2.setText(String.valueOf(inventory.getStock()));
txtPurchase2.setText(String.valueOf(inventory.getPurchase()));
txtType2.setText(inventory.getType());
txtColor2.setText(inventory.getColor());
txtSize2.setText(inventory.getSize());
} catch (Exception e1) {
}
txtOrder1.clear();
txtTotalPurchase.clear();
}
private void handleTvinventory3MouseClicked(MouseEvent e) {
tvInventoryIndex = tvInventory3.getSelectionModel().getSelectedIndex();
try {
Inventory inventory = obList.get(tvInventoryIndex);
txtProductNumber3.setText(String.valueOf(inventory.getProductNumber()));
txtCompany3.setText(inventory.getCompanyName());
txtProduct3.setText(inventory.getProduct());
txtStock3.setText(String.valueOf(inventory.getStock()));
txtSell2.setText(String.valueOf(inventory.getSell()));
txtType3.setText(inventory.getType());
txtColor3.setText(inventory.getColor());
txtSize3.setText(inventory.getSize());
} catch (Exception e1) {
}
cmbCompany5.getSelectionModel().select(-1);
txtOrder2.clear();
txtTotalSell.clear();
}
// 재고 리스트, DB 에서 해당 목록 삭제
private void handleBtnDeleteAction(ActionEvent e) {
try {
InventoryDAO inventoryDAO = new InventoryDAO();
Inventory inventory = obList.get(tvInventoryIndex);
String no = inventory.getProductNumber();
int returnValue = inventoryDAO.getInventoryDelete(no);
obList.remove(tvInventoryIndex);
txtProduct1.clear();
txtProductNumber1.clear();
txtStock1.clear();
txtPurchase1.clear();
txtSell1.clear();
cmbType4.getSelectionModel().clearSelection();
cmbColor4.getSelectionModel().clearSelection();
cmbSize4.getSelectionModel().clearSelection();
cmbCompany4.getSelectionModel().clearSelection();
} catch (ArrayIndexOutOfBoundsException e1) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Edit Error");
alert.setHeaderText("재고 선택 오류");
alert.setContentText("삭제할 재고를 선택하시오");
alert.showAndWait();
}
obList.clear();
totalLoadList();
}
// DB에서 재고 가져오기
private void totalLoadList() {
btnInventory.setDefaultButton(true);// inventory 버튼 표시를 위한 것
InventoryDAO inventoryDAO = new InventoryDAO();
arrayList = inventoryDAO.getTotalLoadList();
if (arrayList == null) {
return;
}
obList.clear();
for (int i = 0; i < arrayList.size(); i++) {
Inventory iv = arrayList.get(i);
obList.add(iv);
}
}
// 검색 조건 및 리스트 초기화버튼 (재고 화면)
private void handleBtnReset1Action(ActionEvent e) {
tvInventoryIndex = -1;
txtSearch1.clear();
txtProduct1.clear();
txtProductNumber1.clear();
txtStock1.clear();
txtPurchase1.clear();
txtSell1.clear();
cmbCompany4.getSelectionModel().clearSelection();
cmbType4.getSelectionModel().clearSelection();
cmbColor4.getSelectionModel().clearSelection();
cmbSize4.getSelectionModel().clearSelection();
obList.clear();
totalLoadList();
handleRdoRegisterAction();
rdoRegister.setSelected(true);
}
// 검색 조건 및 리스트 초기화버튼 (주문 화면)
private void handleBtnReset2Action(ActionEvent e) {
tvInventoryIndex = -1;
txtSearch2.clear();
txtCompany2.clear();
txtProduct2.clear();
txtProductNumber2.clear();
txtStock2.clear();
txtPurchase2.clear();
txtType2.clear();
txtColor2.clear();
txtSize2.clear();
txtOrder1.clear();
txtTotalPurchase.clear();
obList.clear();
totalLoadList();
}
// 검색 조건 및 리스트 초기화버튼 (판매 화면)
private void handleBtnReset3Action(ActionEvent e) {
tvInventoryIndex = -1;
txtSearch3.clear();
txtCompany3.clear();
txtProduct3.clear();
txtProductNumber3.clear();
txtStock3.clear();
txtSell2.clear();
txtType3.clear();
txtColor3.clear();
txtSize3.clear();
txtOrder2.clear();
txtTotalSell.clear();
obList.clear();
totalLoadList();
}
// 콤보박스 리스트
// 업체
private void companyComboBoxList() {
CompanyDAO companyDAO = new CompanyDAO();
ArrayList<CompanyModel> arrayList = companyDAO.inventoryStageCompanyComboboxListUp(production);
String cName = null;
if (arrayList == null) {
return;
}
for (int i = 0; i < arrayList.size(); i++) {
CompanyModel com = arrayList.get(i);
obList5.add(com);
obList1.add(com.getCompany_name());
}
arrayList2 = companyDAO.inventoryStageCompanyComboboxListUp(production2);
String cName2 = null;
if (arrayList2 == null) {
return;
}
for (int i = 0; i < arrayList2.size(); i++) {
CompanyModel com = arrayList2.get(i);
cName2 = com.getCompany_name();
obList3.add(cName2);
}
cmbCompany4.setPromptText("업체 선택");
cmbCompany4.setItems(obList1);
cmbCompany5.setPromptText("판매처 선택");
cmbCompany5.setItems(obList3);
}
// 재고 리스트 테이블
private void tvInventory1Column() {
TableColumn colPnumber = new TableColumn("제품코드");
colPnumber.setPrefWidth(90.0);
colPnumber.setCellValueFactory(new PropertyValueFactory<>("productNumber"));
TableColumn colCompany = new TableColumn("업체명");
colCompany.setPrefWidth(140.0);
colCompany.setCellValueFactory(new PropertyValueFactory<>("companyName"));
TableColumn colProduct = new TableColumn("제품명");
colProduct.setPrefWidth(180.0);
colProduct.setCellValueFactory(new PropertyValueFactory<>("product"));
TableColumn colStock = new TableColumn("재고");
colStock.setMaxWidth(100);
colStock.setCellValueFactory(new PropertyValueFactory<>("stock"));
TableColumn colPurchase = new TableColumn("구입가");
colPurchase.setPrefWidth(80.0);
colPurchase.setCellValueFactory(new PropertyValueFactory<>("purchase"));
TableColumn colSell = new TableColumn("판매가");
colSell.setPrefWidth(80.0);
colSell.setCellValueFactory(new PropertyValueFactory<>("sell"));
TableColumn colType = new TableColumn("종류");
colType.setMaxWidth(90);
colType.setCellValueFactory(new PropertyValueFactory<>("type"));
TableColumn colSize = new TableColumn("사이즈");
colSize.setPrefWidth(80.0);
colSize.setCellValueFactory(new PropertyValueFactory<>("size"));
TableColumn colColor = new TableColumn("색상");
colColor.setMaxWidth(60);
colColor.setCellValueFactory(new PropertyValueFactory<>("color"));
tvInventory1.getColumns().addAll(colPnumber, colCompany, colProduct, colStock, colPurchase, colSell, colType,
colSize, colColor);
tvInventory1.setItems(obList);
}
// 구매화면 리스트
private void tvInventory2Column() {
TableColumn colPnumber = new TableColumn("제품코드");
colPnumber.setPrefWidth(90.0);
colPnumber.setCellValueFactory(new PropertyValueFactory<>("productNumber"));
TableColumn colCompany = new TableColumn("업체명");
colCompany.setPrefWidth(180.0);
colCompany.setCellValueFactory(new PropertyValueFactory<>("companyName"));
TableColumn colProduct = new TableColumn("제품명");
colProduct.setPrefWidth(200.0);
colProduct.setCellValueFactory(new PropertyValueFactory<>("product"));
TableColumn colStock = new TableColumn("재고");
colStock.setMaxWidth(100);
colStock.setCellValueFactory(new PropertyValueFactory<>("stock"));
TableColumn colPurchase = new TableColumn("구입가");
colPurchase.setPrefWidth(80.0);
colPurchase.setCellValueFactory(new PropertyValueFactory<>("purchase"));
TableColumn colType = new TableColumn("종류");
colType.setMaxWidth(100);
colType.setCellValueFactory(new PropertyValueFactory<>("type"));
TableColumn colSize = new TableColumn("사이즈");
colSize.setPrefWidth(80.0);
colSize.setCellValueFactory(new PropertyValueFactory<>("size"));
TableColumn colColor = new TableColumn("색상");
colColor.setMaxWidth(60);
colColor.setCellValueFactory(new PropertyValueFactory<>("color"));
tvInventory2.getColumns().addAll(colPnumber, colCompany, colProduct, colStock, colPurchase, colType, colSize,
colColor);
tvInventory2.setItems(obList);
}
// 판매화면 리스트
private void tvInventory3Column() {
TableColumn colPnumber = new TableColumn("제품코드");
colPnumber.setPrefWidth(90.0);
colPnumber.setCellValueFactory(new PropertyValueFactory<>("productNumber"));
TableColumn colCompany = new TableColumn("업체명");
colCompany.setPrefWidth(180.0);
colCompany.setCellValueFactory(new PropertyValueFactory<>("companyName"));
TableColumn colProduct = new TableColumn("제품명");
colProduct.setPrefWidth(200.0);
colProduct.setCellValueFactory(new PropertyValueFactory<>("product"));
TableColumn colStock = new TableColumn("재고");
colStock.setMaxWidth(100);
colStock.setCellValueFactory(new PropertyValueFactory<>("stock"));
TableColumn colSell = new TableColumn("판매가");
colSell.setPrefWidth(80.0);
colSell.setCellValueFactory(new PropertyValueFactory<>("sell"));
TableColumn colType = new TableColumn("종류");
colType.setMaxWidth(100);
colType.setCellValueFactory(new PropertyValueFactory<>("type"));
TableColumn colSize = new TableColumn("사이즈");
colSize.setPrefWidth(80.0);
colSize.setCellValueFactory(new PropertyValueFactory<>("size"));
TableColumn colColor = new TableColumn("색상");
colColor.setMaxWidth(60);
colColor.setCellValueFactory(new PropertyValueFactory<>("color"));
tvInventory3.getColumns().addAll(colPnumber, colCompany, colProduct, colStock, colSell, colType, colSize,
colColor);
tvInventory3.setItems(obList);
}
}
|
/* A Naive recursive implementation of LCS problem in java*/
public class LongestSubstring
{
//String lcs="";
static String mat[][];
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
String lcs( char[] X, char[] Y, int m, int n ,String cs)
{
if (m == 0 || n == 0)
return cs;
if (X[m-1] == Y[n-1])
{
cs=X[m-1]+cs;
return lcs(X, Y, m-1, n-1,cs);
}
else{
// if(lcs.length()<cs.length())
// {
// lcs=cs;
// }
String s1=lcs(X, Y, m, n-1,"");
String s2=lcs(X, Y, m-1, n,"");
if(cs.length()>=s1.length()&&cs.length()>=s2.length())return cs;
else if(s1.length()>=cs.length()&&s1.length()>=s2.length())return s1;
else return s2;
}
}
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b)? a : b;
}
public static void main(String[] args)
{
LongestSubstring lcs = new LongestSubstring();
String s1 = "AGGTAB";
String s2 = "GXTABXX";
mat=new String[s1.length()][s2.length()];
char[] X=s1.toCharArray();
char[] Y=s2.toCharArray();
int m = X.length;
int n = Y.length;
System.out.println("Length of LCS is" + " " + lcs.lcs( X, Y, m, n ,""));
}
}
|
package com.wit.getaride;
import java.util.ArrayList;
import views.SlidingTabLayout;
import android.app.ActionBar;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseUser;
public class MainActivity extends Base{
private MapFragment mapFr;
ActionBar actionBar;
ViewPager viewPager;
SlidingTabLayout mSlidingtabs;
private GoogleMap map;
private Location currentLocation;
private Button btnConfirm;
private LocationManager manager;
private GoogleApiClient client;
private MarkerOptions markerOptions;
private Marker marker;
public static FragmentManager fragmentManager;
private String imgDecodableString="";
private Intent mRequestFileIntent;
private ParcelFileDescriptor mInputPFD;
private SharedPreference sp = new SharedPreference();
public GetArideApp app = (GetArideApp)getApplication();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkGPS();
fragmentManager = getSupportFragmentManager();
viewPager = (ViewPager)findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
mSlidingtabs = (SlidingTabLayout)findViewById(R.id.sliding_tabs);
mSlidingtabs.setViewPager(viewPager);
mSlidingtabs.setDistributeEvenly(true);
if(app.currentParseUser.getString("radius")!=null)
app.searchRadius = Double.parseDouble(ParseUser.getCurrentUser().getString("radius"));
ArrayList<Destination> dests = sp.loadDestinations(this);
if(dests==null){
sp.addDestination(this, new Destination("Waterford City", 52.259538, -7.105995));
}
}
public void onConfirmPressed(View view){
Double lat = app.thisUser.dest.getLongitude();
if(lat == 0){
Toast.makeText(this, "Please select your destination",
Toast.LENGTH_LONG).show();
return;
}
startActivity (new Intent(this, RideList.class));
}
public void onSavePressed(View view){
EditText destName = (EditText)findViewById(R.id.etDestName);
double lat = app.thisUser.dest.getLatitude();
double lng = app.thisUser.dest.getLongitude();
String name = destName.getText().toString();
if(name.equals("")||lat==0){
Toast.makeText(this, "Please choose a destination and enter a name",
Toast.LENGTH_LONG).show();
return;
}
Log.v("", String.valueOf(lat));
Destination destination = new Destination(name, lat, lng);
sp.addDestination(this, destination);
destName.setText("");
Toast.makeText(this, "The Destination has been saved",
Toast.LENGTH_LONG).show();
}
public void logout(View v){
ParseUser.logOut();
startActivity (new Intent(this, LoggIn.class));
finish();
}
////////////////==================
class MyAdapter extends FragmentPagerAdapter{
String[] tabText = getResources().getStringArray(R.array.tabTitles);
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int arg0) {
Fragment fr =null;
if(arg0 == 0){
fr = new FrSetDestination();
}
if(arg0 == 1){
fr = new FrSettings();
}
if(arg0 == 2){
fr = new FrSavedDestinations();
}
return fr;
}
@Override
public CharSequence getPageTitle(int position){
return tabText[position];
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
}
|
package net.minecraft.potion;
public class PotionHealth extends Potion {
public PotionHealth(boolean isBadEffectIn, int liquidColorIn) {
super(isBadEffectIn, liquidColorIn);
}
public boolean isInstant() {
return true;
}
public boolean isReady(int duration, int amplifier) {
return (duration >= 1);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\potion\PotionHealth.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package cn.fuego.misp.webservice.json;
import java.util.List;
/**
*
* @ClassName: PageJson
* @Description: TODO
* @author Tang Jun
* @date 2014-10-20 上午10:58:01
*
*/
public class MispPageDataJson<E>
{
private List<E> rows;
private int total;
public List<E> getRows()
{
return rows;
}
public void setRows(List<E> rows)
{
this.rows = rows;
}
public int getTotal()
{
return total;
}
public void setTotal(int total)
{
this.total = total;
}
}
|
package com.tencent.mm.ui.chatting;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import com.tencent.mm.R;
import com.tencent.mm.ak.o;
import com.tencent.mm.an.a.b;
import com.tencent.mm.bg.d;
import com.tencent.mm.g.a.ch;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.s;
import com.tencent.mm.model.u;
import com.tencent.mm.plugin.biz.a.a;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.pluginsdk.model.e;
import com.tencent.mm.protocal.c.avq;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.gallery.ImageGalleryUI;
import com.tencent.mm.ui.chatting.viewitems.c.f;
import com.tencent.mm.ui.transmit.MsgRetransmitUI;
import com.tencent.mm.y.g$a;
import com.tencent.mm.y.i;
import com.tencent.mm.y.l;
import com.tencent.mm.y.m;
import com.tencent.smtt.sdk.TbsListener$ErrorCode;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.HashMap;
public final class r {
public static void dr(View view) {
if (view.getTag() instanceof f) {
f fVar = (f) view.getTag();
long j = fVar.bJC;
b bVar;
String valueOf;
String str;
if (fVar.uaH == -1) {
boolean z;
int g;
bd bdVar;
com.tencent.mm.modelstat.b bVar2;
au.HU();
bd dW = c.FT().dW(fVar.bJC);
if (KK(String.valueOf(j))) {
h.mEJ.k(10231, "1");
com.tencent.mm.an.b.PW();
if (dW.field_msgId == j) {
com.tencent.mm.modelstat.b bVar3 = com.tencent.mm.modelstat.b.ehL;
z = false;
g = com.tencent.mm.y.h.g(dW);
bdVar = dW;
bVar2 = bVar3;
} else {
return;
}
}
g$a gp = g$a.gp(fVar.bVv);
if (gp != null) {
h.mEJ.k(10090, "0,1");
bVar = (b) g.l(b.class);
valueOf = String.valueOf(fVar.bJC);
str = fVar.bSw;
au.HU();
com.tencent.mm.an.b.b(bVar.a(gp, valueOf, str, c.Gq(), fVar.bSw));
}
if (dW.field_msgId == j) {
bVar2 = com.tencent.mm.modelstat.b.ehL;
if (gp != null) {
g = gp.type;
z = true;
bdVar = dW;
} else {
g = 0;
z = true;
bdVar = dW;
}
} else {
return;
}
bVar2.a(bdVar, z, g);
return;
}
String str2 = fVar.bJC + "_" + fVar.uaH;
au.HU();
bd dW2 = c.FT().dW(fVar.bJC);
l wS = ((a) g.l(a.class)).wS(fVar.bVv);
h hVar;
Object[] objArr;
if (KK(str2)) {
h.mEJ.k(10231, "1");
com.tencent.mm.an.b.PW();
if (dW2.field_msgId == j) {
com.tencent.mm.modelstat.b.ehL.a(dW2, false, com.tencent.mm.y.h.g(dW2));
}
if (wS != null && wS.dzs != null && wS.dzs.size() > fVar.uaH) {
m mVar = (m) wS.dzs.get(fVar.uaH);
hVar = h.mEJ;
objArr = new Object[2];
objArr[0] = Integer.valueOf(mVar.type == 6 ? 1 : 0);
objArr[1] = Integer.valueOf(1);
hVar.h(14972, objArr);
return;
}
return;
}
if (!(wS == null || wS.dzs == null || wS.dzs.size() <= fVar.uaH)) {
h.mEJ.k(10090, "0,1");
m mVar2 = (m) wS.dzs.get(fVar.uaH);
bVar = (b) g.l(b.class);
valueOf = fVar.bSw;
str = mVar2.title;
String str3 = mVar2.dzM;
String str4 = mVar2.url;
String str5 = mVar2.url;
String str6 = mVar2.dzL;
au.HU();
com.tencent.mm.an.b.b(bVar.a(0, valueOf, str, str3, str4, str5, str6, str2, c.Gq(), fVar.bSw, "", ""));
hVar = h.mEJ;
objArr = new Object[2];
objArr[0] = Integer.valueOf(mVar2.type == 6 ? 1 : 0);
objArr[1] = Integer.valueOf(0);
hVar.h(14972, objArr);
}
if (dW2.field_msgId == j) {
com.tencent.mm.modelstat.b.ehL.a(dW2, true, com.tencent.mm.y.h.g(dW2));
}
}
}
private static boolean KK(String str) {
avq Qa = com.tencent.mm.an.b.Qa();
if (Qa == null || Qa.rsp == null || Qa.rYj != 0 || !com.tencent.mm.an.b.PY()) {
return false;
}
try {
if (bi.fS(Qa.rsp, str)) {
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
public static void a(View view, Context context, String str) {
com.tencent.mm.ui.chatting.viewitems.au auVar = (com.tencent.mm.ui.chatting.viewitems.au) view.getTag();
Object obj = auVar.bKk;
if (TextUtils.isEmpty(obj)) {
obj = ((com.tencent.mm.plugin.emoji.b.c) g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().zn(auVar.cGB);
}
if (TextUtils.isEmpty(obj)) {
Intent intent = new Intent();
intent.putExtra("geta8key_username", str);
intent.putExtra("rawUrl", auVar.cGB);
d.b(context, "webview", ".ui.tools.WebViewUI", intent);
return;
}
Intent intent2 = new Intent();
intent2.putExtra("extra_id", obj);
intent2.putExtra("extra_name", auVar.title);
if (auVar.ufz) {
intent2.putExtra("download_entrance_scene", 20);
intent2.putExtra("preceding_scence", 3);
intent2.putExtra("reward_tip", true);
h.mEJ.h(12953, new Object[]{Integer.valueOf(1), obj});
} else if (auVar.ufA) {
intent2.putExtra("download_entrance_scene", 25);
intent2.putExtra("preceding_scence", 9);
intent2.putExtra("reward_tip", true);
} else {
intent2.putExtra("download_entrance_scene", 22);
intent2.putExtra("preceding_scence", TbsListener$ErrorCode.DOWNLOAD_HAS_COPY_TBS_ERROR);
h.mEJ.h(10993, new Object[]{Integer.valueOf(2), obj});
}
d.b(context, "emoji", ".ui.EmojiStoreDetailUI", intent2);
}
public static void a(m mVar, View view, String str) {
if (view != null && mVar != null) {
view.setOnClickListener(new 1(mVar, str));
}
}
public static void a(int i, Context context, String str, String str2, long j, long j2) {
l wS = ((a) g.l(a.class)).wS(str);
if (wS == null) {
x.w("MicroMsg.ChattingItemHelper", "transmitAppBrandMsg reader is null");
} else if (i >= 0 && i < wS.dzs.size()) {
m mVar = (m) wS.dzs.get(i);
String a = g$a.a(l.a(str2, mVar), null, null);
if (!bi.oW(a)) {
Serializable hashMap = new HashMap();
hashMap.put("desc", mVar.dzA);
hashMap.put("type", Integer.valueOf(2));
hashMap.put("title", mVar.title);
hashMap.put("app_id", mVar.dzH);
hashMap.put("pkg_type", Integer.valueOf(mVar.dzG));
hashMap.put("pkg_version", Integer.valueOf(mVar.dzF));
hashMap.put("img_url", mVar.dzI);
hashMap.put("is_dynamic", Boolean.valueOf(false));
hashMap.put("cache_key", "");
hashMap.put("path", mVar.dzE);
Intent intent = new Intent(context, MsgRetransmitUI.class);
intent.putExtra("appbrand_params", hashMap);
intent.putExtra("Retr_Msg_content", a);
intent.putExtra("Retr_Msg_Type", 2);
intent.putExtra("Retr_Biz_Msg_Selected_Msg_Index", i);
intent.putExtra("Retr_Msg_Id", j);
intent.putExtra("Retr_MsgFromScene", 3);
a = u.ic(String.valueOf(j2));
intent.putExtra("reportSessionId", a);
u.b v = u.Hx().v(a, true);
v.p("prePublishId", "msg_" + j2);
v.p("preUsername", str2);
v.p("preChatName", str2);
v.p("preMsgIndex", Integer.valueOf(i));
v.p("sendAppMsgScene", Integer.valueOf(1));
context.startActivity(intent);
}
}
}
public static void a(long j, int i, Context context, Fragment fragment, Activity activity, bd bdVar) {
String str = bdVar.field_talker;
String ic = u.ic(bdVar.field_msgSvrId);
u.b v = u.Hx().v(ic, true);
v.p("prePublishId", "msg_" + bdVar.field_msgSvrId);
v.p("preUsername", str);
v.p("preChatName", str);
v.p("preMsgIndex", Integer.valueOf(i));
v.p("sendAppMsgScene", Integer.valueOf(1));
ch chVar = new ch();
chVar.bJF.bJJ = i;
chVar.bJF.bJK = ic;
chVar.bJF.nd = fragment;
chVar.bJF.activity = activity;
chVar.bJF.bJM = 40;
e.a(chVar, bdVar);
com.tencent.mm.sdk.b.a.sFg.m(chVar);
if (chVar.bJG.ret == 0) {
g$a gp = g$a.gp(i.a(context, i, bdVar.field_content, bdVar.field_talker));
if (bdVar.aQm()) {
com.tencent.mm.modelstat.b.ehL.b(bdVar, gp != null ? gp.type : 0);
} else {
com.tencent.mm.modelstat.b.ehL.x(bdVar);
}
if (gp != null && gp.type == 5 && gp.url != null) {
x.d("MicroMsg.ChattingItemHelper", "report(%s), url : %s, clickTimestamp : %d, scene : %d, actionType : %d, flag : %d", new Object[]{Integer.valueOf(13378), gp.url, Long.valueOf(j), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(1)});
str = "";
try {
str = URLEncoder.encode(gp.url, "UTF-8");
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.ChattingItemHelper", e, "", new Object[0]);
}
h.mEJ.h(13378, new Object[]{str, Long.valueOf(j), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(1)});
}
}
}
public static void a(bd bdVar, Context context, com.tencent.mm.ui.chatting.c.a aVar) {
int i = 1;
au.HU();
if (c.isSDCardAvailable()) {
com.tencent.mm.ak.e bq;
com.tencent.mm.ak.e eVar = null;
if (bdVar.field_msgId > 0) {
eVar = o.Pf().br(bdVar.field_msgId);
}
if ((eVar == null || eVar.dTK <= 0) && bdVar.field_msgSvrId > 0) {
bq = o.Pf().bq(bdVar.field_msgSvrId);
} else {
bq = eVar;
}
if (bq != null) {
int i2;
if (bdVar.field_isSend == 1) {
if (bq.ON()) {
i2 = 1;
} else {
i2 = 0;
}
} else if (bq.ON()) {
if (com.tencent.mm.a.e.cn(o.Pf().o(com.tencent.mm.ak.f.a(bq).dTL, "", ""))) {
i2 = 1;
} else {
i2 = 0;
}
} else {
i2 = 0;
}
if (bdVar.cmu()) {
x.i("MicroMsg.ChattingItemHelper", "image is clean!!!");
com.tencent.mm.ui.base.h.a(context, context.getString(R.l.imgdownload_cleaned), context.getString(R.l.app_tip), new 2());
return;
} else if (com.tencent.mm.ui.chatting.b.i.e(bdVar, o.Pf().o(com.tencent.mm.ak.f.c(bq), "", ""))) {
x.i("MicroMsg.ChattingItemHelper", "img is expired or clean!!!");
Intent intent = new Intent(context, ImageGalleryUI.class);
intent.putExtra("img_gallery_msg_id", bdVar.field_msgId);
intent.putExtra("img_gallery_msg_svr_id", bdVar.field_msgSvrId);
intent.putExtra("img_gallery_talker", bdVar.field_talker);
intent.putExtra("img_gallery_chatroom_name", bdVar.field_talker);
intent.putExtra("img_gallery_is_restransmit_after_download", true);
intent.putExtra("Retr_show_success_tips", true);
if (aVar != null) {
com.tencent.mm.ui.chatting.b.i.a(aVar, bdVar, intent);
} else if (bdVar != null) {
String str = bdVar.field_talker;
String str2 = bdVar.field_talker;
Bundle bundle = new Bundle();
String str3 = "stat_scene";
if (s.hf(str)) {
i = 7;
}
bundle.putInt(str3, i);
bundle.putString("stat_msg_id", "msg_" + Long.toString(bdVar.field_msgSvrId));
bundle.putString("stat_chat_talker_username", str);
bundle.putString("stat_send_msg_user", str2);
intent.putExtra("_stat_obj", bundle);
}
context.startActivity(intent);
return;
} else if (bq.offset < bq.dHI || bq.dHI == 0) {
Intent intent2 = new Intent(context, MsgRetransmitUI.class);
intent2.putExtra("Retr_File_Name", o.Pf().E(bdVar.field_imgPath, true));
intent2.putExtra("Retr_Msg_Id", bdVar.field_msgId);
intent2.putExtra("Retr_Msg_Type", 0);
intent2.putExtra("Retr_show_success_tips", true);
intent2.putExtra("Retr_Compress_Type", i2);
context.startActivity(intent2);
return;
} else {
Intent intent3 = new Intent(context, MsgRetransmitUI.class);
intent3.putExtra("Retr_File_Name", o.Pf().o(com.tencent.mm.ak.f.c(bq), "", ""));
intent3.putExtra("Retr_Msg_Id", bdVar.field_msgId);
intent3.putExtra("Retr_Msg_Type", 0);
intent3.putExtra("Retr_show_success_tips", true);
intent3.putExtra("Retr_Compress_Type", i2);
context.startActivity(intent3);
return;
}
}
return;
}
com.tencent.mm.ui.base.s.gH(context);
}
}
|
package it.unica.pr2.services;
import java.util.*;
public class SquareRoot extends Service {
public SquareRoot(){
}
static public Service getService(){
return new SquareRoot();
}
@Override
public String toString(){
return "square root";
}
}
|
package Chapter9;
public class Exercise9_12 {
static int getRand(int from, int to) {
return (int)(Math.random()*(Math.abs(to-from)+1)+Math.min(from, to));
}
public static void main(String[] args) {
for(int i=0;i<20;i++)
System.out.print(getRand(1,-3)+",");
}
}
|
package org.stepik.api.objects.instructions;
import com.google.gson.annotations.SerializedName;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.stepik.api.objects.AbstractObject;
import java.util.ArrayList;
import java.util.List;
/**
* @author meanmail
*/
public class Instruction extends AbstractObject {
private long step;
@SerializedName("min_reviews")
private int minReviews;
@SerializedName("strategy_type")
private String strategyType;
private List<Integer> rubrics;
@SerializedName("is_frozen")
private boolean isFrozen;
private String text;
public long getStep() {
return step;
}
public void setStep(long step) {
this.step = step;
}
public int getMinReviews() {
return minReviews;
}
public void setMinReviews(int minReviews) {
this.minReviews = minReviews;
}
@NotNull
public String getStrategyType() {
if (strategyType == null) {
strategyType = "";
}
return strategyType;
}
public void setStrategyType(@Nullable String strategyType) {
this.strategyType = strategyType;
}
@NotNull
public List<Integer> getRubrics() {
if (rubrics == null) {
rubrics = new ArrayList<>();
}
return rubrics;
}
public void setRubrics(@Nullable List<Integer> rubrics) {
this.rubrics = rubrics;
}
public boolean isFrozen() {
return isFrozen;
}
public void setFrozen(boolean frozen) {
this.isFrozen = frozen;
}
@NotNull
public String getText() {
if (text == null) {
text = "";
}
return text;
}
public void setText(@Nullable String text) {
this.text = text;
}
}
|
import java.util.Scanner;
import java.text.DecimalFormat;
//**********************************
// Distance.java
//
// Reads two coordinates, calculates
// the distance between them, and
// then prints it out.
//**********************************
public class Distance {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double x1, x2, y1, y2, distance;
System.out.print("Enter x1: ");
x1 = input.nextDouble();
System.out.print("Enter x2: ");
x2 = input.nextDouble();
System.out.print("Enter y1: ");
y1 = input.nextDouble();
System.out.print("Enter y2: ");
y2 = input.nextDouble();
DecimalFormat fmt = new DecimalFormat("0.##");
distance = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
System.out.println("The distance between the two points is: " + fmt.format(distance));
}
}
|
package com.negi.wallpapers.myimages.Fragments;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.negi.wallpapers.myimages.Activity.ShowPostActivity;
import com.negi.wallpapers.myimages.Adapters.PostListAdapter;
import com.negi.wallpapers.myimages.ClickListener;
import com.negi.wallpapers.myimages.Constants;
import com.negi.wallpapers.myimages.Model.All_Images;
import com.negi.wallpapers.myimages.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class EditorsFragment extends Fragment implements ClickListener {
RecyclerView rv;
ProgressBar pb;
View v;
DatabaseReference ref;
List<All_Images> data;
public EditorsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_editors, container, false);
rv = (RecyclerView)v.findViewById(R.id.rview);
pb = (ProgressBar)v.findViewById(R.id.progress);
pb.setVisibility(View.VISIBLE);
ref = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS).child("Admin");
data = new ArrayList<>();
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rv.setLayoutManager(gridLayoutManager);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
data.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
All_Images im = ds.getValue(All_Images.class);
data.add(im);
}
if(pb.getVisibility()==View.VISIBLE)
{
pb.setVisibility(View.GONE);
}
if(data.size()==0)
{
LinearLayout li = v.findViewById(R.id.error);
li.setVisibility(View.VISIBLE);
}
else {
LinearLayout li = v.findViewById(R.id.error);
if(li.getVisibility()==View.VISIBLE)
{
li.setVisibility(View.GONE);
}
}
Collections.reverse(data);
PostListAdapter ad = new PostListAdapter(getContext(), data);
ad.setOnClick(EditorsFragment.this);
rv.setAdapter(ad);
}
@Override
public void onCancelled(DatabaseError databaseError) {
if(pb.getVisibility()==View.VISIBLE)
{
pb.setVisibility(View.GONE);
}
}
});
return v;
}
@Override
public void onItemClick(View view, int position) {
All_Images images = data.get(position);
Intent i = new Intent(getContext(), ShowPostActivity.class);
i.putExtra("id", images.getId());
i.putExtra("uid", images.getUid());
i.putExtra("downloads", images.getDownloads());
i.putExtra("image", images.getImageUrl());
i.putExtra("date", images.getDate());
i.putExtra("owner", images.getOwner());
i.putExtra("thumb", images.getThumb());
startActivity(i);
}
@Override
public void onItemLongClick(View view, final int position) {
//delete dialog to be shown here
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete Image");
builder.setMessage("Do you want to Delete this image?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteImage(position);
dialog.dismiss();
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void deleteImage(int position) {
final ProgressDialog pd = new ProgressDialog(getContext());
pd.setMessage("Deleting...");
pd.setCancelable(false);
pd.show();
final All_Images ui = data.get(position);
final StorageReference rf2 = FirebaseStorage.getInstance().getReferenceFromUrl(ui.getThumb());
StorageReference rf = FirebaseStorage.getInstance().getReferenceFromUrl(ui.getImageUrl());
rf.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
rf2.delete();
ref.child(ui.getId()).removeValue();
} else {
Toast.makeText(getContext(), "Deletion Failed", Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
});
}
}
|
/******************************************************************************************************************
* File:TemplateMonitor.java
* Project: Assignment A3
* Copyright: Copyright (c) 2014 Carnegie Mellon University
* Versions:
* 1.0 April 2014 - Initial version of template
*
* Description:
*
* This class is a template for monitor of the system.
* Follow the TODO list to create your own monitor
*
* Parameters: IP address of the message manager (on command line). If blank, it is assumed that the message manager is
* on the local machine.
*
******************************************************************************************************************/
import InstrumentationPackage.*;
import MessagePackage.*;
class TemplateMonitor extends Thread
{
private MessageManagerInterface em = null; // Interface object to the message manager
private String MsgMgrIP = null; // Message Manager IP address
boolean Registered = true; // Signifies that this class is registered with an message manager.
MessageWindow mw = null; // This is the message window
Indicator ti; // Temperature indicator
Indicator hi; // Humidity indicator
public TemplateMonitor()
{
// message manager is on the local system
try
{
// Here we create an message manager interface object. This assumes
// that the message manager is on the local machine
em = new MessageManagerInterface();
}
catch (Exception e)
{
System.out.println("TemplateMonitor::Error instantiating message manager interface: " + e);
Registered = false;
} // catch
} //Constructor
public TemplateMonitor( String MsgIpAddress )
{
// message manager is not on the local system
MsgMgrIP = MsgIpAddress;
try
{
// Here we create an message manager interface object. This assumes
// that the message manager is NOT on the local machine
em = new MessageManagerInterface( MsgMgrIP );
}
catch (Exception e)
{
System.out.println("TemplateMonitor::Error instantiating message manager interface: " + e);
Registered = false;
} // catch
} // Constructor
public void run()
{
Message Msg = null; // Message object
MessageQueue eq = null; // Message Queue
int MsgId = 0; // User specified message ID
int Delay = 1000; // The loop delay (1 second)
boolean Done = false; // Loop termination flag
if (em != null)
{
// TODO: Set the name for the monitor
String monitorName = "";
mw = new MessageWindow(monitorName, 0, 0);
// TODO: Create necessary indicators:
// i = new Indicator ("Indicator name", 0, 0);
mw.WriteMessage( "Registered with the message manager." );
try
{
mw.WriteMessage(" Participant id: " + em.GetMyId() );
mw.WriteMessage(" Registration Time: " + em.GetRegistrationTime() );
} // try
catch (Exception e)
{
System.out.println("Error:: " + e);
} // catch
/********************************************************************
** Here we start the main simulation loop
*********************************************************************/
// TODO: Change the simulation loop
while ( !Done )
{
// Here we get our message queue from the message manager
try
{
eq = em.GetMessageQueue();
} // try
catch( Exception e )
{
mw.WriteMessage("Error getting message queue::" + e );
} // catch
int qlen = eq.GetSize();
for ( int i = 0; i < qlen; i++ )
{
Msg = eq.GetMessage();
// TODO: Handle the relevant messages
/*
* if ( Msg.GetMessageId() == 1 ) {
* ...
* }
*/
// If the message ID == 99 then this is a signal that the simulation
// is to end. At this point, the loop termination flag is set to
// true and this process unregisters from the message manager.
if ( Msg.GetMessageId() == 99 )
{
Done = true;
try
{
em.UnRegister();
} // try
catch (Exception e)
{
mw.WriteMessage("Error unregistering: " + e);
} // catch
mw.WriteMessage( "\n\nSimulation Stopped. \n");
// TODO: Dispose the resources
} // if
} // for
// TODO: Provide after-monitoring actions
// This delay slows down the sample rate to Delay milliseconds
try
{
Thread.sleep( Delay );
} // try
catch( Exception e )
{
System.out.println( "Sleep error:: " + e );
} // catch
} // while
} else {
System.out.println("Unable to register with the message manager.\n\n" );
} // if
} // main
/***************************************************************************
* CONCRETE METHOD:: IsRegistered
* Purpose: This method returns the registered status
*
* Arguments: none
*
* Returns: boolean true if registered, false if not registered
*
* Exceptions: None
*
***************************************************************************/
public boolean IsRegistered()
{
return( Registered );
}
/***************************************************************************
* CONCRETE METHOD:: Halt
* Purpose: This method posts an message that stops the system.
*
* Arguments: none
*
* Returns: none
*
* Exceptions: Posting to message manager exception
*
***************************************************************************/
public void Halt()
{
mw.WriteMessage( "***HALT MESSAGE RECEIVED - SHUTTING DOWN SYSTEM***" );
// Here we create the stop message.
Message msg;
msg = new Message( (int) 99, "XXX" );
// Here we send the message to the message manager.
try
{
em.SendMessage( msg );
} // try
catch (Exception e)
{
System.out.println("Error sending halt message:: " + e);
} // catch
} // Halt
} // TemplateMonitor
|
package com.tencent.mm.plugin.exdevice.ui;
import com.tencent.mm.ui.base.MMPullDownView$b;
class ExdeviceProfileUI$8 implements MMPullDownView$b {
final /* synthetic */ ExdeviceProfileUI iEx;
ExdeviceProfileUI$8(ExdeviceProfileUI exdeviceProfileUI) {
this.iEx = exdeviceProfileUI;
}
public final void aIc() {
ExdeviceProfileUI.A(this.iEx);
}
}
|
package com.company.current;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.logging.SimpleFormatter;
public class ThreadLocalExample implements Runnable{
private static final ThreadLocal<SimpleDateFormat>formatter=ThreadLocal.withInitial(()->new SimpleDateFormat("yyyyMMdd HHmm"));
public static void main(String[] args) throws Exception{
ThreadLocalExample obj=new ThreadLocalExample();
for (int i = 0; i <10 ; i++) {
Thread t=new Thread(obj,""+i);
Thread.sleep(new Random().nextInt(1000));
t.start();
}
}
@Override
public void run() {
System.out.println("name="+Thread.currentThread().getName()+"defult"+formatter.get().toPattern());
try {
Thread.sleep(new Random().nextInt(10000));
}catch (InterruptedException e){
e.printStackTrace();
}
formatter.set(new SimpleDateFormat());
System.out.println("name="+Thread.currentThread().getName()+"formatter"+formatter.get().toPattern());
}
}
|
package binaryTreesWithDelete;
import java.util.Comparator;
public class PathComparator implements Comparator<Node> {
public int compare(Node n1, Node n2) {
int len_path_node1 = n1.path().length();
int len_path_node2 = n2.path().length();
if (len_path_node1 < len_path_node2) return -1;
else if (len_path_node1 > len_path_node2) return 1;
else {
byte[] s1 = n1.path().getBytes();
byte[] s2 = n2.path().getBytes();
for (int i=0; i<s1.length; i++)
if (s1[i] < s2[i]) return -1;
else if (s1[i] > s2[i]) return 1;
return 0;
}
}
}
|
package com.valunskii.university.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "groups")
@Getter
@Setter
@ApiModel(value = "Group Группа")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "group_id")
@ApiModelProperty(value = "ID группы", required = true, position = 1, example = "1")
private Long id;
@ApiModelProperty(value = "Название группы", required = true, position = 1, example = "K-3120")
private String name;
public Group() {
}
public Group(String name) {
this.name = name;
}
}
|
package com.filiereticsa.arc.augmentepf.localization.guidage;
import android.util.Log;
import android.util.Pair;
import com.filiereticsa.arc.augmentepf.R;
import com.filiereticsa.arc.augmentepf.activities.AugmentEPFApplication;
import com.filiereticsa.arc.augmentepf.localization.GAFrameworkUserTracker;
import java.util.ArrayList;
/**
* Created by ARC© Team for AugmentEPF project on 07/06/2017.
*/
public class Guidance {
public static final String TAG = "Ici (Guidance)";
private ArrayList<Pair<Integer, Integer>> path;
private ArrayList<TrajectorySegment> trajectory;
private ArrayList<ArrayList<Pair<Integer, Integer>>> positionsSegment;
public Guidance(ArrayList<Pair<Integer, Integer>> path) {
this.path = path;
pathAnalysis();
}
private ArrayList<TrajectorySegment> computeAllTrajectory() {
// To put all segments in the trajectory
ArrayList<TrajectorySegment> trajectoryAllSeg = new ArrayList<>();
// Size of the path for the limit of for below
if (path != null) {
int pathSize = path.size();
// Creation of variables
int xBefore, xAfter, yBefore, yAfter;
String code;
// Start at 1 because we have i-1 & finish at (size-1) because we have i+1
// i-1 & i+1 are for the displacements of the user
for (int i = 1; i < pathSize - 1; i++) {
// For x values
xBefore = path.get(i).first - path.get(i - 1).first; // Before user displacement
xAfter = path.get(i + 1).first - path.get(i).first; // The next event in the trajectory
// For y values
yBefore = path.get(i).second - path.get(i - 1).second;
yAfter = path.get(i + 1).second - path.get(i).second;
// Method which transform the displacement in an unique code to identify the displacement
code = transformationOfValues(xBefore, xAfter, yBefore, yAfter);
// Add the segment computed with the code computed
trajectoryAllSeg.add(new TrajectorySegment(code));
// Log.d(TAG, "trajectory: " + trajectory.get(i - 1).getDirectionInstruction());
}
// if (trajectory != null) {
// for (int i = 0; i < trajectory.size(); i++) {
// Log.d(TAG, "computeAllTrajectory: " + trajectory.get(i).getDirectionInstruction());
// }
// Log.d(TAG, "computeAllTrajectory: ------------");
// }
}
// Return the trajectory
return trajectoryAllSeg;
}
/**
* Try to find if the currentPosition exist in the list of positions of the segment (n° index)
*
* @param currentPosition
* @param index
* @return
*/
public int getCurrentSegment(Pair<Integer, Integer> currentPosition, int index) {
boolean found = false;
boolean endPath = false;
// Compare all positions of the index segment with the current
if (positionsSegment.size() > index) {
//Log.d(TAG, "getCurrentSegment: =========================");
for (int i = 0; i < positionsSegment.get(index).size(); i++) {
// Create a local position to test it without call it everytime
Pair<Integer, Integer> testPosition = positionsSegment.get(index).get(i);
// Log.d(TAG, "getCurrentSegment: currentPosition:" + currentPosition);
// Log.d(TAG, "getCurrentSegment: testPosition:" + testPosition);
// Compare the two positions
if (testPosition.first.equals(currentPosition.first)
&& testPosition.second.equals(currentPosition.second)) {
// If it's the last position of the segment & the last segment => end of path
if ((i == positionsSegment.get(index).size() - 1) &&
index == positionsSegment.size() - 1) {
endPath = true;
}
// If the position is the last position of the segment, pass at the next segment
else if (i == positionsSegment.get(index).size() - 1) {
index = index + 1;
}
// The algorithm found a position
found = true;
}
}
// Log.d(TAG, "getCurrentSegment: =========================");
} else {
endPath = true;
}
// If the algorithm didn't find the position in the segment
if (!found) {
index = -1; // To identify an error
}
if (endPath) {
index = Integer.MAX_VALUE; // To identify the end of the path
if (GAFrameworkUserTracker.sharedTracker() != null) {
GAFrameworkUserTracker.sharedTracker().setTarget(null);
}
}
return index;
}
public ArrayList<TrajectorySegment> getTrajectory() {
return trajectory;
}
private void pathAnalysis() {
// Creation and initialization of the trajectory which it's suppose to be fill of
// TrajectorySegment in order to have a trajectory full
ArrayList<TrajectorySegment> trajectoryAllSeg;
// To compute all segments of the trajectory
trajectoryAllSeg = computeAllTrajectory();
// To avoid redundancy in the trajectory (for "straight ahead") and replace by the number of
// meters which user must do
trajectory = shortenTrajectory(trajectoryAllSeg);
}
/**
* Set a new path, compute a new trajectory
*
* @param path
*/
public void setPath(ArrayList<Pair<Integer, Integer>> path) {
this.path = path;
pathAnalysis();
}
private ArrayList<TrajectorySegment> shortenTrajectory(ArrayList<TrajectorySegment> trajectoryAllSeg) {
positionsSegment = new ArrayList<>();
ArrayList<TrajectorySegment> trajectory = new ArrayList<>();
// Finish at (size-1) because we compare direction instructions of the current and next
// segment
if (trajectoryAllSeg != null) {
for (int i = 0; i < trajectoryAllSeg.size() - 1; i++) {
// To have independent counter of i
// In order to have a list of positions for each segment
Pair<Integer, Integer> absolutePosition;
ArrayList<Pair<Integer, Integer>> allAbsolutePosition = new ArrayList<>();
// One segment which is necessary to have the short trajectory
TrajectorySegment trajSegment;
// If there is a repetition, same instruction 2 blocks in a row
if (trajectoryAllSeg.get(i).getDirectionInstruction().equals(trajectoryAllSeg.get(i + 1).getDirectionInstruction())) {
// Initialization
String oldCode, directionInstruction, distance;
int numberOfIteration = 0;
// While it's the same direction instruction
while (trajectoryAllSeg.get(i).getDirectionInstruction().equals(trajectoryAllSeg.get(i + 1).getDirectionInstruction())
&& (i < trajectoryAllSeg.size() - 2)) {
i = i + 1; // Increment i because we want restart after the repetition
numberOfIteration = numberOfIteration + 1; // To count the number of repetition
// To have all positions in the segment
absolutePosition = path.get(i);
allAbsolutePosition.add(absolutePosition);
}
if (trajectoryAllSeg.get(i).getDirectionInstruction()
.equals(AugmentEPFApplication.getAppContext().getString(R.string.guidanceStraightAhead))) {
// 1 instruction ~= 1m & 1 iteration = 1 instruction
distance = AugmentEPFApplication.getAppContext().getString(R.string.guidanceFor)
+ " " + (numberOfIteration + 1)
+ " " + AugmentEPFApplication.getAppContext().getString(R.string.guidanceMeters);
// Construct the new directionInstruction
directionInstruction = trajectoryAllSeg.get(i).getDirectionInstruction() + " " + distance;
} else {
// 1 instruction ~= 1m & 1 iteration = 1 instruction
distance = AugmentEPFApplication.getAppContext().getString(R.string.guidanceIn)
+ " " + (numberOfIteration + 1)
+ " " + AugmentEPFApplication.getAppContext().getString(R.string.guidanceMeters);
// Construct the new directionInstruction
directionInstruction = trajectoryAllSeg.get(i).getDirectionInstruction() + " " + distance;
}
// Get the code of the direction instruction
oldCode = trajectoryAllSeg.get(i).getCode();
// Create a new segment with without the distance
trajSegment = new TrajectorySegment(oldCode);
// Set the new segment with the new direction instruction
trajSegment.setDirectionInstruction(directionInstruction);
} else { // If there isn't a repetition just put the normal segment
String oldCode;
// To have the only position of the segment
absolutePosition = path.get(i);
allAbsolutePosition.add(absolutePosition);
oldCode = trajectoryAllSeg.get(i).getCode();
trajSegment = new TrajectorySegment(oldCode);
}
// List of all positions with the number of the segment.
// Form like this : (number of segment, list of all positions)
positionsSegment.add(allAbsolutePosition);
// Finally, we add the new segment in the short trajectory
trajectory.add(trajSegment);
}
// To display all instructions of the trajectory
/*for (int i = 0; i < trajectory.size(); i++) {
Log.d(TAG, "trajectory: " + trajectory.get(i).getDirectionInstruction());
}*/
}
return trajectory;
}
private String transformationOfValues(int xBefore, int xAfter, int yBefore, int yAfter) {
String finalCode, stringXBefore, stringXAfter, stringYBefore, stringYAfter;
// Displacements on x axis
switch (xBefore) {
case -1:
stringXBefore = "4";
break;
case 0:
stringXBefore = "0";
break;
case 1:
stringXBefore = "2";
break;
default:
stringXBefore = "0";
break;
}
switch (xAfter) {
case -1:
stringXAfter = "4";
break;
case 0:
stringXAfter = "0";
break;
case 1:
stringXAfter = "2";
break;
default:
stringXAfter = "0";
break;
}
// Displacements on y axis
switch (yBefore) {
case -1:
stringYBefore = "1";
break;
case 0:
stringYBefore = "0";
break;
case 1:
stringYBefore = "3";
break;
default:
stringYBefore = "0";
break;
}
switch (yAfter) {
case -1:
stringYAfter = "1";
break;
case 0:
stringYAfter = "0";
break;
case 1:
stringYAfter = "3";
break;
default:
stringYAfter = "0";
break;
}
// Concatenate all strings to form a unique code
finalCode = stringXBefore + stringYBefore + stringXAfter + stringYAfter;
// Return the code
return finalCode;
}
}
|
package utils;
import java.io.IOException;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
public class IdGenerator {
private ZooKeeper zk;
private DistributedLock dl;
private static IdGenerator instance;
public static IdGenerator getInstance() {
if (instance == null) {
instance = new IdGenerator();
}
return instance;
}
private IdGenerator() {
try {
zk = new ZooKeeper("127.0.0.1:2181", 40000, null);
dl = new DistributedLock(zk, "/locknode", "idlock");
} catch (IOException e) {
return;
}
}
public long getID() {
try {
dl.lock();
Long oldID = new Long(new String(zk.getData("/ids/id", false, null)));
long id = oldID + 1;
zk.setData("/ids/id", String.valueOf(id).getBytes(), -1);
dl.unlock();
return id;
} catch (IOException | KeeperException | InterruptedException e) {
return -1;
}
}
public void reset() {
try {
dl.lock();
zk.setData("/ids/id", String.valueOf(0).getBytes(), -1);
dl.unlock();
} catch (IOException | KeeperException | InterruptedException e) {}
}
}
|
package ThreadPoolExecutorABExecutor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class DefinedThreadPoolDemo {
public static void main(String[] args) {
DefinedThreadpool pool = new DefinedThreadpool(2, 2, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(10));
for(int i=0;i<3;i++){
pool.execute(new MyThread());
}
pool.shutdown();
}
static class MyThread extends Thread{
public void run(){
System.out.println("run "+Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.