text stringlengths 10 2.72M |
|---|
package com.davivienda.utilidades.ws.gestor.cliente;
//OLD: package com.davivienda.multifuncional.clientews;
import com.davivienda.utilidades.Constantes;
import com.davivienda.utilidades.log.SaraSOAPHandlerResolver;
import com.davivienda.utilidades.ws.cliente.envioTransportadora.EnvioTransportadoraDto;
import com.davivienda.utilidades.ws.cliente.envioTransportadora.EnvioTransportadoraService;
import com.davivienda.utilidades.ws.cliente.envioTransportadora.IEnvioTransportadora;
import com.davivienda.utilidades.ws.cliente.envioTransportadora.RespuestaDisminucionProvisionDto;
import com.davivienda.utilidades.ws.cliente.envioTransportadora.ServicioException_Exception;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.HandlerResolver;
/**
* EnvioTransportadora
*
*
* @author mdruiz 2011
*/
public class EnvioTransportadora {
private static final Logger logger = Logger.getLogger(Constantes.LOGGER_APP);
private static EnvioTransportadoraService servicioImplementacion = null;
private static IEnvioTransportadora servicioPort = null;
private static URL ENVIOTRANSPORTADORA_WSDL_LOCATION;
static {
String urlString = null;
try {
ENVIOTRANSPORTADORA_WSDL_LOCATION = com.davivienda.utilidades.ws.gestor.cliente.EnvioTransportadora.class.getClassLoader().getResource("META-INF/wsdl/EnvioTransportadora/EnvioTransportadora_1.wsdl");
String host = SaraConfigServicios.SERVIDOR_WS.trim();
String puerto = SaraConfigServicios.PUERTO_SERVIDOR_WS.trim();
urlString = "http://" + host + ":" + puerto + "/EnvioTransportadoraService/EnvioTransportadora";
if (ENVIOTRANSPORTADORA_WSDL_LOCATION == null) {
logger.log(Level.SEVERE, "Cannot find 'META-INF/wsdl/EnvioTransportadora/EnvioTransportadora_1.wsdl' wsdl. Place the resource correctly in the classpath.");
}
servicioImplementacion = new EnvioTransportadoraService(ENVIOTRANSPORTADORA_WSDL_LOCATION);
HandlerResolver handlerResolver = new SaraSOAPHandlerResolver();
servicioImplementacion.setHandlerResolver(handlerResolver);
servicioPort = servicioImplementacion.getEnvioTransportadoraPort();
BindingProvider bindingPort = (BindingProvider) servicioPort;
bindingPort.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, urlString);
} catch (Exception e) {
Logger.global.log(Level.SEVERE, "No se puede crear la Implementacion de " + urlString, e);
}
}
public RespuestaDisminucionProvisionDto realizarEnvioTransportadora(EnvioTransportadoraDto datosRequerimiento) throws ServicioException_Exception {
EnvioTransportadoraDto dtoRequerimiento = datosRequerimiento;
RespuestaDisminucionProvisionDto dtoRespuesta = null;
try {
if (dtoRequerimiento != null) {
if (servicioPort == null) {
if (servicioImplementacion != null) {
servicioPort = servicioImplementacion.getEnvioTransportadoraPort();
} else {
throw new Exception("No se puede acceder al puerto del servicio");
}
}
dtoRespuesta = servicioPort.envioTransportadora(dtoRequerimiento);
}
} catch (Exception ex) {
Logger.global.log(Level.SEVERE, ex.getMessage(), ex);
}
return dtoRespuesta;
}
}
|
package com.mediafire.sdk.response_models;
public class ApiResponse implements MediaFireApiResponse {
private String action;
private String message;
private String result;
private int error;
private String current_api_version;
private String new_key;
@Override
public final String getAction() {
return action;
}
@Override
public final String getMessage() {
return message;
}
@Override
public final int getError() {
return error;
}
@Override
public final String getResult() {
return result;
}
@Override
public final String getCurrentApiVersion() {
return current_api_version;
}
@Override
public final boolean hasError() {
return error != 0;
}
@Override
public boolean needNewKey() {
return new_key != null && "yes".equals(new_key);
}
}
|
package com.babin.csvreconciler.dao;
import com.babin.csvreconciler.model.QwoRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface QwoRecordDao extends JpaRepository<QwoRecord, Long> {
Optional<QwoRecord> findOneByCustomerNumberIsAndProductReference(String customerNumber, String productReference);
}
|
package fun.modelbook.boxssoserver.controller.api;
import fun.modelbook.boxssoserver.controller.ApiBaseController;
import io.swagger.annotations.Api;
/**
* @author jory
* @date 2019-03-15
*/
@Api(tags = "应用管理接口")
public class AppController extends ApiBaseController {
}
|
import java.io.*;
import java.util.*;
class sameline
{
public static void main(String[] args)
{
Scanner kb=new Scanner(System.in);
int x[]=new int[3];
int y[]=new int[3];
for(int i=0;i<3;i++)
{
x[i]=kb.nextInt();
y[i]=kb.nextInt();
}
if((x[0]==x[1])&&(x[1]==x[2]))
{
System.out.println("yes");
}
else
{
if((y[0]==y[1])&&(y[1]==y[2]))
{
System.out.println("yes");
}
else
{
System.out.println("no");
}
}
}
}
|
/*
* 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 studentmanagementsystem.courseregistration;
import java.sql.Connection;
import java.sql.Statement;
import javax.swing.JOptionPane;
import studentmanagementsystem.dbconnect;
/**
*
* @author dess
*/
public class courses extends javax.swing.JInternalFrame {
/**
* Creates new form courses
*/
public courses() {
initComponents();
}
public void executeQuery(String query,String message)
{
Connection conn=dbconnect.ConnectDB();
Statement st;
try
{
st=conn.createStatement();
if((st.executeUpdate(query)) ==1)
{
JOptionPane.showMessageDialog(null, "Data"+message+"Successfully");
}
else{
JOptionPane.showMessageDialog(null, "Data Not"+message);
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jcourseid = new javax.swing.JTextField();
jcoursename = new javax.swing.JTextField();
jfee = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setTitle("Add Course");
setToolTipText("");
jLabel1.setText("course id");
jLabel2.setText("Course Name");
jLabel3.setText("Fee Applicable");
jButton1.setText("Insert");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jcourseid)
.addComponent(jcoursename, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 174, Short.MAX_VALUE))
.addComponent(jfee))))
.addContainerGap(51, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jcourseid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jcoursename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jfee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(128, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String query="INSERT INTO sms.courses(course_id, course_name, fee) values"
+ "('"+jcourseid.getText()+"','"+jcoursename.getText()+"','"+jfee.getText()+"')";
executeQuery(query, "Added");
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jcourseid;
private javax.swing.JTextField jcoursename;
private javax.swing.JTextField jfee;
// End of variables declaration//GEN-END:variables
}
|
package ra.sumbayak.maverick.rest;
import android.support.annotation.NonNull;
import android.util.Log;
import retrofit2.*;
public abstract class QRCallback<T> implements Callback<T> {
@Override
public void onResponse (@NonNull Call<T> call, @NonNull Response<T> response) {
T body = response.body ();
Log.i ("QRCallback", call.request ().toString ());
Log.i ("QRCallback", response.toString ());
Log.i ("QRCallback", String.valueOf (body));
if (response.isSuccessful ())
if (body != null && isSuccess (body)) onSuccessful (body);
else onFailure ();
else if (response.code () == 401) onUnauthorized ();
else onFailure ();
onExit ();
}
@Override
public void onFailure (@NonNull Call<T> call, @NonNull Throwable t) {
Log.e ("QRCallback", call.request ().toString ());
t.printStackTrace ();
onFailure ();
}
protected abstract void onSuccessful (@NonNull T body);
protected boolean isSuccess (@NonNull T body) {
return true;
}
protected void onUnauthorized () {
}
protected void onFailure () {
}
protected void onExit () {
}
}
|
package com.sinodynamic.hkgta.dao.crm;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.entity.crm.PresentMaterialSeq;
@Repository
public class PresentMaterialSeqDaoImpl extends GenericDao<PresentMaterialSeq> implements PresentMaterialSeqDao{
@Override
public boolean saveOrUpdatePMS(PresentMaterialSeq pms) {
return this.saveOrUpdate(pms);
}
@Override
public int getPresentSeq(Long materialId, Long presentId) {
// TODO Auto-generated method stub
String hql = " select p.presentSeq from PresentMaterialSeq p where p.materialId = " + materialId+"and p.presentId ="+presentId;
int presentSeq = (int) super.getUniqueByHql(hql);
return presentSeq;
}
}
|
package com.zc.pivas.statistics.bean.configFee;
import java.util.ArrayList;
import java.util.List;
/**
* 配置费报表 批次名称bean
*
* @author jagger
* @version 1.0
*/
public class ConfigFeeBatchStatusBarBean {
/**
* 批次名称列表
*/
private List<String> batchNameList = new ArrayList<String>();
private List<ConfigFeeStatus2BatchBean> status2BatchList = new ArrayList<ConfigFeeStatus2BatchBean>();
public List<String> getBatchNameList() {
return batchNameList;
}
public void setBatchNameList(List<String> batchNameList) {
this.batchNameList = batchNameList;
}
public void addBatchNameList(String batchName) {
this.batchNameList.add(batchName);
}
public List<ConfigFeeStatus2BatchBean> getStatus2BatchList() {
return status2BatchList;
}
public void setStatus2BatchList(List<ConfigFeeStatus2BatchBean> status2BatchList) {
this.status2BatchList = status2BatchList;
}
public void addStatus2BatchList(ConfigFeeStatus2BatchBean status2Batch) {
this.status2BatchList.add(status2Batch);
}
}
|
package com.binarysprite.evemat.page.product.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Tabunoki
*
*/
public class Group implements Serializable {
/**
*
*/
private int id;
/**
*
*/
private String groupName;
/**
*
*/
private String characterName;
/**
*
*/
private final List<Product> products = new ArrayList<Product>();
/**
*
*/
private final List<Material> materials = new ArrayList<Material>();
/**
* @return id
*/
public int getId() {
return id;
}
/**
* @param id id を設定します。
*/
public void setId(int id) {
this.id = id;
}
/**
* @return groupName
*/
public String getGroupName() {
return groupName;
}
/**
* @param groupName
* groupName を設定します。
*/
public void setGroupName(String groupName) {
this.groupName = groupName;
}
/**
* @return characterName
*/
public String getCharacterName() {
return characterName;
}
/**
* @param characterName
* characterName を設定します。
*/
public void setCharacterName(String characterName) {
this.characterName = characterName;
}
/**
* @return products
*/
public List<Product> getProducts() {
return products;
}
/**
* @return materials
*/
public List<Material> getMaterials() {
return materials;
}
}
|
package com.library.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.library.demo.entity.Book;
import com.library.demo.repo.BookRepository;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
public BookServiceImpl() {
// TODO Auto-generated constructor stub
}
@Override
public List<Book> findAll() {
return bookRepository.findAll();
}
@Override
public Book findById(int theId) throws Exception {
// TODO Auto-generated method stub
Book book = null;
java.util.Optional<Book> received = bookRepository.findById(theId);
if (received.isPresent()) {
book = received.get();
} else {
throw new Exception("Book is Not Available with Given Id");
}
return book;
}
@Override
public void deleteById(int theId) {
// TODO Auto-generated method stub
bookRepository.deleteById(theId);
}
@Override
public void save(Book book) {
// TODO Auto-generated method stub
bookRepository.save(book);
}
}
|
package minesweeper.squares;
import minesweeper.Board;
public class CornerSquare extends Square {
public CornerSquare(int row, int col, char symbol) {
super(row, col, symbol);
}
@Override
public int getBombsInPerimeter(final Board board) {
int bombsAroundEmptySpace = 0;
int i = row;
int j = col;
Square[][] arr = board.getMinefield();
// top left corner
if (i == 0 && j == 0) {
if (arr[i][j + 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i + 1][j].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i + 1][j + 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
} // top right corner
else if (i == 0 && j == 8) {
if (arr[i][j - 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i + 1][j - 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i + 1][j].getSymbol() == 'X') {
bombsAroundEmptySpace++;
}
} // bottom left corner
else if (i == 8 && j == 0) {
if (arr[i - 1][j].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i - 1][j + 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i][j + 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
} // bottom right corner
else if (i == 8 && j == 8) {
if (arr[i - 1][j].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i - 1][j - 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
if (arr[i][j - 1].isBombSquare()) {
bombsAroundEmptySpace++;
}
}
return bombsAroundEmptySpace;
}
}
|
package com.test.base;
import com.test.SolutionA;
import com.test.SolutionB;
import junit.framework.TestCase;
public class Example extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
public void testSolutionA()
{
solution = new SolutionA();
assertSolution();
}
public void testSolutionB()
{
solution = new SolutionB();
assertSolution();
}
private void assertSolution()
{
int[] numsA = {3, 1, 5, 8};
assertEquals(167, solution.maxCoins(numsA));
int[] numsB = {42, 23, 62, 2, 89, 97, 26, 82, 47, 23, 9, 2, 9, 11, 53, 49, 40, 3, 88, 76, 63, 11, 79, 37, 52,
91, 5, 44, 71, 69, 20, 5, 74, 41, 70, 68, 26, 16, 62, 53, 47, 46, 26, 27, 99, 72, 4, 40, 77, 74, 89, 19, 26,
7, 30, 79, 49, 75, 51, 28, 47, 26, 55, 81, 82, 15, 21, 89, 51, 10, 0, 50, 31, 32, 38, 7, 99, 13, 23, 98, 68,
9, 54, 15, 34, 52, 58, 48, 66, 75, 6, 15, 91, 33, 15, 37, 25, 98, 98, 77, 60, 16, 82, 89, 48, 43, 1, 85, 39,
99, 95, 86, 45, 90, 73, 45, 93, 99, 39, 57, 32, 47, 35, 79, 25, 54, 98, 34, 60, 90, 38, 40, 5, 5, 96, 21,
18, 93, 69, 38, 85, 49, 15, 77, 84, 70, 52, 87, 73, 15, 65};
assertEquals(53234968, solution.maxCoins(numsB));
}
@Override
protected void tearDown()
throws Exception
{
super.tearDown();
}
}
|
/**
*
*/
package Com.crm.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import Com.crm.qa.Base.TestBase;
/**
* @author guptaav
*
*/
public class HomePage extends TestBase {
@FindBy(xpath="//a[contains(text(),'Home')]")
WebElement Home;
@FindBy(xpath="//a[contains(text(),'Calendar')]")
WebElement Calendar;
@FindBy(xpath="//a[contains(text(),'Companies')]")
WebElement Companies;
@FindBy(xpath="//a[contains(text(),'Contacts')]")
public WebElement Contacts;
@FindBy(xpath="//a[contains(text(),'Deals')]")
WebElement Deals;
@FindBy(xpath="//a[contains(text(),'Tasks')]")
WebElement Tasks;
@FindBy(xpath="//a[contains(text(),'Cases')]")
WebElement Cases;
@FindBy(xpath="//a[contains(text(),'Call')]")
WebElement Call;
@FindBy(xpath="//a[contains(text(),'Email')]")
WebElement Email;
@FindBy(xpath="//a[contains(text(),'Text/SMS')]")
WebElement TextSMS;
@FindBy(xpath="//a[contains(text(),'Print')]")
WebElement Print;
@FindBy(xpath="//a[contains(text(),'Campaigns')]")
WebElement Campaigns;
@FindBy(xpath="//a[contains(text(),'Docs')]")
WebElement Docs;
@FindBy(xpath="//a[contains(text(),'Forms')]")
WebElement Forms;
@FindBy(xpath="//a[contains(text(),'Reports')]")
WebElement Reports;
@FindBy(xpath="//td[contains(text(),'Contacts')]")
WebElement ContactsLabel;
@FindBy(xpath="//a[contains(text(),'Avi Gupta')]")
WebElement ContactsList;
public HomePage(){
PageFactory.initElements(driver, this);
}
public void ClickOnHome(){
Home.click();
}
public void ClickOnCalendar(){
Calendar.click();
}
public void ClickOnCompanies(){
Companies.click();
}
public void ClickOnContacts(){
Contacts.click();
}
public void ClickOnDeals(){
Deals.click();
}
public void ClickOnTasks(){
Tasks.click();
}
public void ClickOnCases(){
Cases.click();
}
public void ClickOnCall(){
Call.click();
}
public void ClickOnEmail(){
Email.click();
}
public void ClickOnTextSMS(){
TextSMS.click();
}
public void ClickOnPrint(){
Print.click();
}
public void ClickOnCampaigns(){
Campaigns.click();
}
public void ClickOnDocs(){
Docs.click();
}
public void ClickOnForms(){
Forms.click();
}
public void ClickOnReports(){
Reports.click();
}
public String VerifyHomePageTitle(){
return driver.getTitle();
}
public boolean VerifyContactPageLabel(){
return ContactsLabel.isDisplayed();
}
public boolean VerifyContactsList(){
return ContactsList.isDisplayed();
}
}
|
package com.cognizant.truyum.dao;
import java.util.List;
import com.cognizant.truyum.model.MenuItem;
public interface CartDao {
public void addCartItem(long userId,long menuItemId);
public List<MenuItem> getAllCartItems(long userId)throws CartEmptyException;
public void removeCartItem( long userId, long menuItemId);
}
|
package org.itst.service.impl;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import org.itst.dao.EquipmentMapper;
import org.itst.domain.Equipment;
import org.itst.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EquipmentServiceImpl implements EquipmentService {
@Autowired
private EquipmentMapper mapper;
public void addEquipments(List<Equipment> list) {
mapper.addEquipments(list);
}
public void deleteEquipmentById(int id) {
mapper.deleteEquipmentById(id);
}
public Equipment getEquipmentById(int id) {
return mapper.getEquipmentById(id);
}
public String getEquipmentsJsonByPage(int pageSize, int pageNow) {
List<Equipment> eqs = mapper.getEquipmentsByPage(pageSize*(pageNow-1), pageSize*pageNow);
String res = "";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
for(Equipment e : eqs){
res += "{\"id\":\"" + String.format("%06d", e.getId())
+ "\",\"type\":\"" + e.getType()
+ "\",\"usingUnit\":\"" + (e.getRecord()==null?"暂无":e.getRecord().getUsingUnit())
+ "\",\"status\":\"" + (e.getStatus()==1?"闲置":"使用中")
+ "\",\"addTime\":\"" + formatter.format(e.getAddTime())
+ "\"},";
}
if (!res.equals("")) {
res = res.substring(0, res.length() - 1);
}
return "{\"total\":" + mapper.getEquipmentCount() + ",\"rows\":[" + res + "]}";
}
public void updateEquipmentStatus(Equipment e) {
mapper.updateEquipmentStatus(e);
}
public List<Equipment> getFreeEquipmentByType(String type, int num) {
return mapper.getFreeEquipmentByType(type, num);
}
public List<Equipment> getFreeEquipmentByType(String type, String num) {
// TODO Auto-generated method stub
return null;
}
}
|
package viewsControllers;
import database.DatabaseHandler;
import database.MysqlDatabaseHandler;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import models.*;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class SearchForBooks implements Initializable {
public TextField titleTxtField;
public TextField isbnTxtField;
public TextField authorTxtField;
public ChoiceBox publisherChioceBox;
public CheckBox artChkBox;
public CheckBox geographyChkBox;
public CheckBox historyChkBox;
public CheckBox religionChkBox;
public CheckBox scienceChkBox;
public VBox resultsVBox;
public TextField minPriceTxtField;
public TextField maxPriceTxtField;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
ViewsController.getInstance().setSearchForBooksController(this);
}
public void titleChkChanged(ActionEvent actionEvent) {
checkBoxChanged(titleTxtField);
}
public void isbnChkChanged(ActionEvent actionEvent) {
checkBoxChanged(isbnTxtField);
}
public void authorChkChanged(ActionEvent actionEvent) {
checkBoxChanged(authorTxtField);
}
private void checkBoxChanged(TextField authorTxtField) {
if (authorTxtField.isDisabled())
authorTxtField.setDisable(false);
else
authorTxtField.setDisable(true);
}
public void publisherChkChanged(ActionEvent actionEvent) {
if(publisherChioceBox.isDisabled())
publisherChioceBox.setDisable(false);
else
publisherChioceBox.setDisable(true);
}
public void searchClk(ActionEvent actionEvent) {
BookDAO bookDAO = new BookDAO();
if(!titleTxtField.isDisabled())
bookDAO.setTitle(titleTxtField.getText());
if(!isbnTxtField.isDisabled())
bookDAO.setIsbn(isbnTxtField.getText());
if(!authorTxtField.isDisabled())
bookDAO.setAuthor(authorTxtField.getText());
if(!publisherChioceBox.isDisabled())
bookDAO.setPublisher(publisherChioceBox.getValue().toString());
if(!minPriceTxtField.isDisabled())
bookDAO.setLowerPrice(Float.parseFloat(minPriceTxtField.getText()));
if(!maxPriceTxtField.isDisabled())
bookDAO.setLowerPrice(Float.parseFloat(maxPriceTxtField.getText()));
bookDAO.setCategories(getChosenCategories());
DatabaseHandler databaseHandler = MysqlDatabaseHandler.getInstance();
List<Book> books = databaseHandler.findBook(bookDAO);
setTitleRow();
addBooksToResult(books);
}
private void addBooksToResult(List<Book> books) {
DatabaseHandler databaseHandler = MysqlDatabaseHandler.getInstance();
for (Book book:
books) {
HBox hBox = new HBox();
hBox.setAlignment(Pos.BASELINE_CENTER);
Label titleLabel = new Label(book.getTitle());
titleLabel.setPrefWidth(100);
Label isbnLabel = new Label(book.getIsbn());
isbnLabel.setPrefWidth(100);
isbnLabel.setAlignment(Pos.CENTER);
Label categoryLabel = new Label(book.getCategoryName());
categoryLabel.setPrefWidth(100);
categoryLabel.setAlignment(Pos.CENTER);
Label priceLabel = new Label(String.valueOf(book.getPrice()));
priceLabel.setPrefWidth(100);
priceLabel.setAlignment(Pos.CENTER);
Label publiserLabel = new Label(book.getPublisherName());
publiserLabel.setPrefWidth(100);
publiserLabel.setAlignment(Pos.CENTER);
TextField buyingQuantity = new TextField();
buyingQuantity.setPrefWidth(50);
buyingQuantity.setAlignment(Pos.CENTER);
Button buyBtn = new Button("Buy");
buyBtn.setPrefWidth(50);
buyBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
databaseHandler.addToShoppingCard(book.getIsbn(), Integer.parseInt(buyingQuantity.getText()));
buyingQuantity.setText("");
}
});
TextField orderQuantity = new TextField();
orderQuantity.setPrefWidth(50);
orderQuantity.setAlignment(Pos.CENTER);
Button orderBtn = new Button("Order");
orderBtn.setPrefWidth(100);
orderBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if(databaseHandler.orderFromSupplier(book.getIsbn(), Integer.parseInt(orderQuantity.getText()))) {
orderQuantity.setText("");
Alert alert = new Alert(Alert.AlertType.INFORMATION, "Successfully Ordered ");
alert.setHeaderText(null);
alert.show();
} else {
Alert alert = new Alert(Alert.AlertType.ERROR, "Error While Ordering ");
alert.setHeaderText(null);
alert.show();
}
}
});
Button editBtn = new Button("Edit");
editBtn.setPrefWidth(50);
editBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
try {
ViewsController.getInstance().openEditBookScreen(book);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button deleteBtn = new Button("Delete");
deleteBtn.setPrefWidth(70);
deleteBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
databaseHandler.removeBook(book);
resultsVBox.getChildren().remove(hBox);
}
});
hBox.getChildren().add(isbnLabel);
hBox.getChildren().add(titleLabel);
hBox.getChildren().add(categoryLabel);
hBox.getChildren().add(priceLabel);
hBox.getChildren().add(publiserLabel);
hBox.getChildren().add(buyingQuantity);
hBox.getChildren().add(buyBtn);
if(LoggedUser.getInstance().getUser().getIsManger()) {
hBox.getChildren().add(orderQuantity);
hBox.getChildren().add(orderBtn);
hBox.getChildren().add(editBtn);
hBox.getChildren().add(deleteBtn);
}
resultsVBox.getChildren().add(hBox);
}
}
private List<String> getChosenCategories() {
List<String> chosenCategories = new ArrayList<>();
if(artChkBox.isSelected())
chosenCategories.add("Art");
if(geographyChkBox.isSelected())
chosenCategories.add("Geography");
if(historyChkBox.isSelected())
chosenCategories.add("History");
if(religionChkBox.isSelected())
chosenCategories.add("Religion");
if(scienceChkBox.isSelected())
chosenCategories.add("Science");
return chosenCategories;
}
public void onSceneShow() {
titleTxtField.setText("");
isbnTxtField.setText("");
authorTxtField.setText("");
publisherChioceBox.setValue("");
minPriceTxtField.setText("");
maxPriceTxtField.setText("");
DatabaseHandler databaseHandler = MysqlDatabaseHandler.getInstance();
List<Publisher> publishers = databaseHandler.getPublishers();
ArrayList<String> publishersNames = getPublishersNames(publishers);
publisherChioceBox.setItems(FXCollections.observableArrayList(publishersNames));
setTitleRow();
}
private void setTitleRow() {
resultsVBox.getChildren().clear();
HBox hBox = new HBox();
hBox.setPrefHeight(25);
Label isbnLabel = new Label("ISBN");
isbnLabel.setAlignment(Pos.CENTER);
isbnLabel.setPrefWidth(100);
Label titleLabel = new Label("Title");
titleLabel.setAlignment(Pos.CENTER);
titleLabel.setPrefWidth(100);
Label categoryLabel = new Label("Category");
categoryLabel.setAlignment(Pos.CENTER);
categoryLabel.setPrefWidth(100);
Label priceLabel = new Label("Price");
priceLabel.setAlignment(Pos.CENTER);
priceLabel.setPrefWidth(100);
Label publiserLabel = new Label("Publisher");
publiserLabel.setAlignment(Pos.CENTER);
publiserLabel.setPrefWidth(100);
Label buyLabel = new Label("Add to Cart");
buyLabel.setAlignment(Pos.CENTER);
buyLabel.setPrefWidth(100);
Label orderLabel = new Label("Order From Supplier");
orderLabel.setAlignment(Pos.CENTER);
orderLabel.setPrefWidth(150);
Label editLabel = new Label("Edit");
editLabel.setAlignment(Pos.CENTER);
editLabel.setPrefWidth(50);
Label deleteLabel = new Label("Delete");
deleteLabel.setAlignment(Pos.CENTER);
deleteLabel.setPrefWidth(70);
hBox.getChildren().add(isbnLabel);
hBox.getChildren().add(titleLabel);
hBox.getChildren().add(categoryLabel);
hBox.getChildren().add(priceLabel);
hBox.getChildren().add(publiserLabel);
hBox.getChildren().add(buyLabel);
if(LoggedUser.getInstance().getUser().getIsManger()) {
hBox.getChildren().add(orderLabel);
hBox.getChildren().add(editLabel);
hBox.getChildren().add(deleteLabel);
}
resultsVBox.getChildren().add(hBox);
}
private ArrayList<String> getPublishersNames(List<Publisher> publishers) {
ArrayList<String> publishersNames = new ArrayList<>();
for (Publisher publisher :
publishers) {
publishersNames.add(publisher.getPublisherName());
}
return publishersNames;
}
public void minPriceChkChanged(ActionEvent actionEvent) {
checkBoxChanged(minPriceTxtField);
}
public void maxPriceChkChanged(ActionEvent actionEvent) {
checkBoxChanged(maxPriceTxtField);
}
public void shppingCartClk(ActionEvent actionEvent) throws IOException {
ViewsController.getInstance().openShoppingCartScreen();
}
public void backClk(ActionEvent actionEvent) throws IOException {
User curUser = LoggedUser.getInstance().getUser();
if(curUser.getIsManger()) {
ViewsController.getInstance().openControlPanelScreen();
} else {
ViewsController.getInstance().openUserHomeScreen();
}
}
}
|
package com.rudolfschmidt.amr.consumers;
import com.rudolfschmidt.amr.nodenizer.Attribute;
import com.rudolfschmidt.amr.nodenizer.Node;
import com.rudolfschmidt.amr.nodenizer.NodeType;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.rudolfschmidt.amr.Amr.parse;
public class Extender {
private static final String EXTENDS = "extends";
private static final String BLOCK = "block";
private static final String APPEND = "append";
private static final String PREPEND = "prepend";
public static List<Node> applyExtender(Path templatePath, List<Node> nodes) throws IOException {
final List<Node> posts = new ArrayList<>();
for (Node node : nodes) {
if (node.type.equals(NodeType.ELEMENT) && node.value.equals(EXTENDS)) {
final Optional<Attribute> file = node.attributes.stream().filter(a -> a.key.equals("file")).findAny();
if (file.isPresent()) {
final Attribute fileAttribute = file.get();
final Path normalized = templatePath.getParent().resolve(fileAttribute.value);
extendsTemplate(parse(normalized), node.nodes, posts);
return posts;
}
}
posts.add(new Node(node.type, node.value, node.attributes, applyExtender(templatePath, node.nodes)));
}
return posts;
}
private static void extendsTemplate(List<Node> templateNodes, List<Node> extendsBlocks, List<Node> posts) {
for (Node templateNode : templateNodes) {
if (isBlock(templateNode)) {
for (Node extendsBlock : extendsBlocks) {
if (isBlock(extendsBlock) && sameName(templateNode, extendsBlock)) {
posts.addAll(extendsBlock.nodes);
} else if (isAppend(extendsBlock) && sameName(templateNode, extendsBlock)) {
posts.addAll(Stream.concat(templateNode.nodes.stream(), extendsBlock.nodes.stream()).collect(Collectors.toList()));
} else if (isPrepend(extendsBlock) && sameName(templateNode, extendsBlock)) {
posts.addAll(Stream.concat(extendsBlock.nodes.stream(), templateNode.nodes.stream()).collect(Collectors.toList()));
}
}
} else {
final Node post = new Node(templateNode.type, templateNode.value, templateNode.attributes);
posts.add(post);
extendsTemplate(templateNode.nodes, extendsBlocks, post.nodes);
}
}
}
private static boolean sameName(Node a, Node b) {
for (Attribute x : a.attributes) {
if (x.key.equals("name")) {
for (Attribute y : b.attributes) {
if (y.key.equals("name") && x.value.equals(y.value)) {
return true;
}
}
}
}
return false;
}
private static boolean isBlock(Node node) {
return node.type == NodeType.ELEMENT && node.value.equals(BLOCK);
}
private static boolean isAppend(Node node) {
return node.type == NodeType.ELEMENT && node.value.equals(APPEND);
}
private static boolean isPrepend(Node node) {
return node.type == NodeType.ELEMENT && node.value.equals(PREPEND);
}
}
|
package coffeemachine;
public enum CoffeeType {
ESPRESSO(25, 16, 4),
LATTE(350, 20, 7, 75),
CAPPUCCINO(200, 12, 6, 100);
private int water;
private int beans;
private int price;
private int milk;
private CoffeeType(int water, int beans, int price) {
this.water = water;
this.beans = beans;
this.price = price;
}
private CoffeeType(int water, int beans, int price, int milk) {
this.water = water;
this.beans = beans;
this.price = price;
this.milk = milk;
}
public int getWater() {
return water;
}
public int getBeans() {
return beans;
}
public int getPrice() {
return price;
}
public int getMilk() {
return milk;
}
}
|
package Telas;
import Controle.ControleVisualizar;
import Controle.ControlePagamento;
import Controle.ControleNovaVenda;
import Controle.ControleRemover;
import Controle.ControleAdicionar;
import Controle.ControleFinalizarVenda;
import Controle.ControleIniciarBalanca;
import Supermercado.BD;
import Supermercado.Caixa;
import Supermercado.Estoque;
import Supermercado.Item;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class TelaFuncionario {
private final DefaultListModel<Item> itens = new DefaultListModel<>();
private final JList<Item> listaItens = new JList();
private JTextField nomeProduto;
private JTextField valorProduto;
private JTextField digitarCodigo;
private JTextField valorTotal;
private JTextField quantidade;
public void montarTelaFuncionario(BD bd, Estoque estoque, Caixa caixa, JFrame telaLogin) {
JFrame frame = new JFrame("Supermercado CLD Caixa " + caixa.getIdCaixa());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel painelGeral = new JPanel(new BorderLayout());
JPanel painelLista = new JPanel(new GridLayout(1, 1));
painelLista.setBorder(BorderFactory.createTitledBorder("Produtos"));
listaItens.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listaItens.setModel(itens);
painelLista.add(new JScrollPane(listaItens));
painelGeral.add(painelLista, BorderLayout.CENTER);
frame.add(painelGeral);
JButton novaVenda = new JButton("Nova Venda");
JButton adicionar = new JButton("Adicionar");
JButton remover = new JButton("Remover");
JButton consultar = new JButton("Consultar");
JButton balanca = new JButton("Balança");
JButton pagamento = new JButton("Forma de Pagamento");
JButton finalizarVenda = new JButton("Finalizar Venda");
JButton desconectar = new JButton("Desconectar");
JPanel painelBotoes = new JPanel(new GridLayout(10, 1));
painelBotoes.add(novaVenda);
painelBotoes.add(adicionar);
painelBotoes.add(remover);
painelBotoes.add(consultar);
painelBotoes.add(balanca);
painelBotoes.add(pagamento);
//painelBotoes.add(finalizarVenda);
painelBotoes.add(desconectar);
painelGeral.add(painelBotoes, BorderLayout.EAST);
digitarCodigo = new JTextField();
JLabel codigo = new JLabel("Codigo: ");
valorTotal = new JTextField();
JLabel valorTotalL = new JLabel("Total: R$");
quantidade = new JTextField("1");
JLabel quantidadeL = new JLabel("Quantidade: ");
JPanel painelCodigo = new JPanel(new GridLayout(1, 4));
painelCodigo.add(codigo);
painelCodigo.add(digitarCodigo);
painelCodigo.add(quantidadeL);
painelCodigo.add(quantidade);
painelCodigo.add(valorTotalL);
painelCodigo.add(valorTotal);
painelGeral.add(painelCodigo, BorderLayout.SOUTH);
nomeProduto = new JTextField(15);
valorProduto = new JTextField(15);
JLabel nome = new JLabel("Nome: ");
JLabel valor = new JLabel("Valor: R$");
JPanel painelDescricao = new JPanel(new GridLayout(10, 1));
painelDescricao.add(nome);
painelDescricao.add(nomeProduto);
painelDescricao.add(valor);
painelDescricao.add(valorProduto);
painelGeral.add(painelDescricao, BorderLayout.WEST);
adicionar.setEnabled(false);
consultar.setEnabled(false);
finalizarVenda.setEnabled(false);
remover.setEnabled(false);
pagamento.setEnabled(false);
balanca.setEnabled(false);
nomeProduto.setEditable(false);
valorProduto.setEditable(false);
valorTotal.setEditable(false);
digitarCodigo.setEnabled(false);
quantidade.setEnabled(false);
telaLogin.setVisible(false);
balanca.addActionListener(new ControleIniciarBalanca(quantidade));
novaVenda.addActionListener(new ControleNovaVenda(caixa, adicionar, consultar, remover, pagamento, finalizarVenda, novaVenda, balanca, digitarCodigo, quantidade));
consultar.addActionListener(new ControleVisualizar(estoque, nomeProduto, valorProduto, digitarCodigo));
adicionar.addActionListener(new ControleAdicionar(estoque, caixa, itens, digitarCodigo, valorTotal, quantidade));
adicionar.addActionListener(new ControleVisualizar(estoque, nomeProduto, valorProduto, digitarCodigo));
remover.addActionListener(new ControleRemover(estoque, listaItens, itens, caixa, valorTotal));
pagamento.addActionListener(new ControlePagamento(caixa, adicionar, consultar, remover, pagamento, finalizarVenda, desconectar, balanca));
finalizarVenda.addActionListener(new ControleFinalizarVenda(caixa, adicionar, consultar, remover, pagamento, finalizarVenda, novaVenda, desconectar, balanca, itens, nomeProduto, valorProduto, valorTotal, digitarCodigo, quantidade));
desconectar.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
telaLogin.setVisible(true);
}
});
frame.pack();
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
package org.sunshinelibrary.turtle.webservice;
/**
* User: fxp
* Date: 10/14/13
* Time: 5:57 PM
*/
public class WebServiceException extends Exception {
public WebServiceException(String s) {
super(s);
}
public WebServiceException(Exception e) {
super(e);
}
}
|
package com.bashan.godot.facebook;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.FacebookSdkNotInitializedException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.share.model.GameRequestContent;
import com.facebook.share.widget.GameRequestDialog;
import org.godotengine.godot.Dictionary;
import org.godotengine.godot.Godot;
import org.godotengine.godot.GodotLib;
import org.godotengine.godot.plugin.GodotPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.List;
public class GodotFacebook extends GodotPlugin {
private static final String TAG = "godot-facebook";
private Godot activity = null;
private Integer facebookCallbackId = 0;
private GameRequestDialog requestDialog;
private CallbackManager callbackManager;
private AppEventsLogger fbLogger;
public GodotFacebook(Godot godot) {
super(godot);
activity = godot;
}
public void init(final String key) {
Log.e(TAG, "Initializing Facebook plugin with token: " + key);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
FacebookSdk.setApplicationId(key);
FacebookSdk.sdkInitialize(activity.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
fbLogger = AppEventsLogger.newLogger(activity.getApplicationContext(), key);
requestDialog = new GameRequestDialog(activity);
requestDialog.registerCallback(callbackManager, new FacebookCallback<GameRequestDialog.Result>() {
public void onSuccess(GameRequestDialog.Result result) {
String id = result.getRequestId();
//result.getRequestRecipients()
Log.i(TAG, "Facebook game request finished: " + id);
Dictionary map;
try {
JSONObject object = new JSONObject();
object.put("requestId", result.getRequestId());
object.put("recipientsIds", new JSONArray(result.getRequestRecipients()));
map = JsonHelper.toMap(object);
} catch (JSONException e) {
map = new Dictionary();
}
GodotLib.calldeferred(facebookCallbackId, "request_success", new Object[]{map});
}
public void onCancel() {
Log.w(TAG, "Facebook game request cancelled");
GodotLib.calldeferred(facebookCallbackId, "request_cancelled", new Object[]{});
}
public void onError(FacebookException error) {
Log.e(TAG, "Failed to send facebook game request: " + error.getMessage());
GodotLib.calldeferred(facebookCallbackId, "request_failed", new Object[]{error.toString()});
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken at = loginResult.getAccessToken();
GodotLib.calldeferred(facebookCallbackId, "login_success", new Object[]{at.getToken()});
}
@Override
public void onCancel() {
GodotLib.calldeferred(facebookCallbackId, "login_cancelled", new Object[]{});
}
@Override
public void onError(FacebookException exception) {
GodotLib.calldeferred(facebookCallbackId, "login_failed", new Object[]{exception.toString()});
}
});
} catch (FacebookSdkNotInitializedException e) {
Log.e(TAG, "Failed to initialize FacebookSdk: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
});
}
public void setFacebookCallbackId(int facebookCallbackId) {
this.facebookCallbackId = facebookCallbackId;
}
public int getFacebookCallbackId() {
return facebookCallbackId;
}
public void gameRequest(final String message, final String recipient, final String objectId) {
Log.i(TAG, "Facebook gameRequest");
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (FacebookSdk.isInitialized()) {
GameRequestContent.Builder builder = new GameRequestContent.Builder();
builder.setMessage(message);
if (recipient != null && recipient.length() > 0)
builder.setTo(recipient);
if (objectId != null && objectId.length() > 0) {
builder.setActionType(GameRequestContent.ActionType.SEND);
builder.setObjectId(objectId);
}
GameRequestContent content = builder.build();
requestDialog.show(content);
} else {
Log.d(TAG, "Facebook sdk not initialized");
}
}
});
}
public void login(String[] permissions) {
Log.i(TAG, "Facebook login");
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null && !accessToken.isExpired()) {
GodotLib.calldeferred(facebookCallbackId, "login_success", new Object[]{accessToken.getToken()});
} else {
List<String> perm = Arrays.asList(permissions);
LoginManager.getInstance().logInWithReadPermissions(activity, perm);
}
}
public void logout() {
Log.i(TAG, "Facebook logout");
LoginManager.getInstance().logOut();
}
public boolean isLoggedIn() {
Log.i(TAG, "Facebook isLoggedIn");
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken == null || accessToken.isExpired()) {
//GodotLib.calldeferred(facebookCallbackId, "login_failed", new Object[]{"No token"});
return false;
} else {
//GodotLib.calldeferred(facebookCallbackId, "login_success", new Object[]{accessToken.getToken()});
return true;
}
}
public void userProfile(final int callbackObject, final String callbackMethod) {
Log.i(TAG, "Facebook userProfile");
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null && !accessToken.isExpired()) {
GraphRequest gr = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (object == null) {
Log.e(TAG, "Facebook graph request error: " + response.toString());
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{"Error"});
} else {
Log.i(TAG, "Facebook graph response: " + object.toString());
try {
Dictionary map = JsonHelper.toMap(object);
//String res = object.toString();
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{map});
} catch (JSONException e) {
e.printStackTrace();
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{"JSON Error"});
}
}
}
});
gr.executeAsync();
} else {
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{"No token"});
}
}
public void callApi(final String path, final Dictionary properties, final int callbackObject, final String callbackMethod) {
Log.i(TAG, "Facebook callApi");
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null && !accessToken.isExpired()) {
GraphRequest gr = GraphRequest.newGraphPathRequest(accessToken, path, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
JSONObject object = response.getJSONObject();
if (object == null || response.getError() != null) {
String err = response.getError().toString();
Log.e(TAG, "Facebook graph request error: " + response.toString());
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{err});
} else {
Log.i(TAG, "Facebook graph response: " + object.toString());
try {
Dictionary map = JsonHelper.toMap(object);
Log.i(TAG, "Api result: " + map.toString());
//String res = object.toString();
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{map});
} catch (JSONException e) {
e.printStackTrace();
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{e.toString()});
}
}
}
});
Bundle params = gr.getParameters();
for (String key : properties.get_keys()) {
params.putString(key, properties.get(key).toString());
}
gr.setParameters(params);
gr.executeAsync();
} else {
GodotLib.calldeferred(callbackObject, callbackMethod, new Object[]{"No token"});
}
}
public void set_push_token(final String token) {
Log.i(TAG, "Facebook set_push_token");
if (fbLogger == null) {
Log.w(TAG, "Facebook logger doesn't inited yet!");
return;
}
fbLogger.setPushNotificationsRegistrationId(token);
}
public void log_event(final String event) {
Log.i(TAG, "Facebook log_event");
if (fbLogger == null) {
Log.w(TAG, "Facebook logger doesn't inited yet!");
return;
}
fbLogger.logEvent(event);
}
public void log_event_value(final String event, double value) {
Log.i(TAG, "Facebook log_event_value");
if (fbLogger == null) {
Log.w(TAG, "Facebook logger doesn't inited yet!");
return;
}
fbLogger.logEvent(event, value);
}
public void log_event_params(final String event, final Dictionary params) {
Log.i(TAG, "Facebook log_event_params");
if (fbLogger == null) {
Log.w(TAG, "Facebook logger doesn't inited yet!");
return;
}
Bundle parameters = new Bundle();
for (String key : params.get_keys()) {
parameters.putString(key, params.get(key).toString());
}
fbLogger.logEvent(event, parameters);
}
public void log_event_value_params(final String event, double value, final Dictionary params) {
Log.i(TAG, "Facebook log_event_value_params");
if (fbLogger == null) {
Log.w(TAG, "Facebook logger doesn't inited yet!");
return;
}
Bundle parameters = new Bundle();
for (String key : params.get_keys()) {
if (params.get(key) != null)
parameters.putString(key, params.get(key).toString());
}
fbLogger.logEvent(event, value, parameters);
}
// Internal methods
public void callbackSuccess(String ticket, String signature, String sku) {
//GodotLib.callobject(facebookCallbackId, "purchase_success", new Object[]{ticket, signature, sku});
//GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[]{});
}
@Override
public void onMainActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@NonNull
@Override
public String getPluginName() {
return "GodotFacebook";
}
@NonNull
@Override
public List<String> getPluginMethods() {
return Arrays.asList(
"init",
"setFacebookCallbackId",
"getFacebookCallbackId",
"gameRequest",
"login",
"logout",
"isLoggedIn",
"userProfile",
"callApi",
"set_push_token",
"log_event",
"log_event_value",
"log_event_params",
"log_event_value_params"
);
}
}
|
package org.pentaho.di.pojo;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowSet;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaInteger;
import org.pentaho.di.core.row.value.ValueMetaString;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.pojo.annotation.ExcludeMeta;
import org.pentaho.di.pojo.annotation.NewField;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.BaseStepData.StepExecutionStatus;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.RowListener;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInjectionMetaEntry;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepListener;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInjectionInterface;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
public abstract class StepPluginPOJO extends BaseStepMeta implements StepMetaInterface, StepInterface {
protected MoreAccessibleBaseStep baseStep = null;
protected StepDataInterface stepDataInterface = null;
protected List<FieldMetadataBean> metaFields = null;
protected List<FieldMetadataBean> newFields = null;
// Helper fields
protected RowMetaInterface outputRowMeta = null;
// From BaseStep
/** if true then the row being processed is the first row */
public boolean first = true;
public StepPluginPOJO() {
generateMetaFields();
}
@Override
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
TransMeta transMeta, Trans trans ) {
// if ( baseStep == null ) {
baseStep = new MoreAccessibleBaseStep( stepMeta, stepDataInterface, copyNr, transMeta, trans );
// }
return this;
}
@Override
public StepDataInterface getStepData() {
/*
* if ( stepDataInterface == null ) { stepDataInterface = new BaseStepData() { }; } return stepDataInterface;
*/
return new BaseStepData() {
};
}
public List<FieldMetadataBean> getMetaFields() {
return metaFields;
}
public void setMetaFields( List<FieldMetadataBean> metaFields ) {
this.metaFields = metaFields;
}
protected void generateMetaFields() {
// Look for @ExcludeMeta, include all others
Field[] fields = this.getClass().getDeclaredFields();
if ( fields != null ) {
metaFields = new ArrayList<FieldMetadataBean>( fields.length );
newFields = new ArrayList<FieldMetadataBean>();
for ( Field field : fields ) {
if ( field.getAnnotation( ExcludeMeta.class ) == null ) {
FieldMetadataBean fieldMetadata = StepPluginUtils.generateFieldMetadata( field );
if ( fieldMetadata != null ) {
metaFields.add( fieldMetadata );
// Add to new fields list if new
if ( field.getAnnotation( NewField.class ) != null ) {
newFields.add( fieldMetadata );
// System.out.println( "Added new field: " + field.getName() );
}
}
} else {
System.out.println( "Excluded field: " + field.getName() );
}
}
}
}
// ******************
// Delegate methods
// ******************
public void addRowListener( RowListener arg0 ) {
baseStep.addRowListener( arg0 );
}
public void addStepListener( StepListener arg0 ) {
baseStep.addStepListener( arg0 );
}
public void batchComplete() throws KettleException {
baseStep.batchComplete();
}
public boolean canProcessOneRow() {
return baseStep.canProcessOneRow();
}
public void cleanup() {
baseStep.cleanup();
}
public void copyVariablesFrom( VariableSpace arg0 ) {
baseStep.copyVariablesFrom( arg0 );
}
public void dispose( StepMetaInterface arg0, StepDataInterface arg1 ) {
baseStep.dispose( arg0, arg1 );
}
public String environmentSubstitute( String arg0 ) {
return baseStep.environmentSubstitute( arg0 );
}
public String[] environmentSubstitute( String[] arg0 ) {
return baseStep.environmentSubstitute( arg0 );
}
public String fieldSubstitute( String arg0, RowMetaInterface arg1, Object[] arg2 ) throws KettleValueException {
return baseStep.fieldSubstitute( arg0, arg1, arg2 );
}
public boolean getBooleanValueOfVariable( String arg0, boolean arg1 ) {
return baseStep.getBooleanValueOfVariable( arg0, arg1 );
}
public int getCopy() {
return baseStep.getCopy();
}
public int getCurrentInputRowSetNr() {
return baseStep.getCurrentInputRowSetNr();
}
public int getCurrentOutputRowSetNr() {
return baseStep.getCurrentOutputRowSetNr();
}
public long getErrors() {
return baseStep.getErrors();
}
public List<RowSet> getInputRowSets() {
return baseStep.getInputRowSets();
}
public long getLinesInput() {
return baseStep.getLinesInput();
}
public long getLinesOutput() {
return baseStep.getLinesOutput();
}
public long getLinesRead() {
return baseStep.getLinesRead();
}
public long getLinesRejected() {
return baseStep.getLinesRejected();
}
public long getLinesUpdated() {
return baseStep.getLinesUpdated();
}
public long getLinesWritten() {
return baseStep.getLinesWritten();
}
public LogChannelInterface getLogChannel() {
return baseStep.getLogChannel();
}
public IMetaStore getMetaStore() {
return baseStep.getMetaStore();
}
public List<RowSet> getOutputRowSets() {
return baseStep.getOutputRowSets();
}
public VariableSpace getParentVariableSpace() {
return baseStep.getParentVariableSpace();
}
public String getPartitionID() {
return baseStep.getPartitionID();
}
public long getProcessed() {
return baseStep.getProcessed();
}
public Repository getRepository() {
return baseStep.getRepository();
}
public Map<String, ResultFile> getResultFiles() {
return baseStep.getResultFiles();
}
public Object[] getRow() throws KettleException {
return baseStep.getRow();
}
public List<RowListener> getRowListeners() {
return baseStep.getRowListeners();
}
public long getRuntime() {
return baseStep.getRuntime();
}
public StepExecutionStatus getStatus() {
return baseStep.getStatus();
}
public String getStepID() {
return baseStep.getStepID();
}
public StepMeta getStepMeta() {
return baseStep.getStepMeta();
}
public String getStepname() {
return baseStep.getStepname();
}
public Trans getTrans() {
return baseStep.getTrans();
}
public String getVariable( String arg0, String arg1 ) {
return baseStep.getVariable( arg0, arg1 );
}
public String getVariable( String arg0 ) {
return baseStep.getVariable( arg0 );
}
public void identifyErrorOutput() {
baseStep.identifyErrorOutput();
}
public boolean init( StepMetaInterface arg0, StepDataInterface arg1 ) {
return baseStep.init( arg0, arg1 );
}
public void initBeforeStart() throws KettleStepException {
baseStep.initBeforeStart();
}
public void initializeVariablesFrom( VariableSpace arg0 ) {
baseStep.initializeVariablesFrom( arg0 );
}
public void injectVariables( Map<String, String> arg0 ) {
baseStep.injectVariables( arg0 );
}
public boolean isMapping() {
return baseStep.isMapping();
}
public boolean isPartitioned() {
return baseStep.isPartitioned();
}
public boolean isPaused() {
return baseStep.isPaused();
}
public boolean isRunning() {
return baseStep.isRunning();
}
public boolean isStopped() {
return baseStep.isStopped();
}
public boolean isUsingThreadPriorityManagment() {
return baseStep.isUsingThreadPriorityManagment();
}
public String[] listVariables() {
return baseStep.listVariables();
}
public void markStart() {
baseStep.markStart();
}
public void markStop() {
baseStep.markStop();
}
public void pauseRunning() {
baseStep.pauseRunning();
}
public abstract boolean processRow( StepMetaInterface arg0, StepDataInterface arg1 ) throws KettleException;
public void putRow( RowMetaInterface arg0, Object[] arg1 ) throws KettleException {
baseStep.putRow( arg0, arg1 );
}
public void removeRowListener( RowListener arg0 ) {
baseStep.removeRowListener( arg0 );
}
public void resumeRunning() {
baseStep.resumeRunning();
}
public int rowsetInputSize() {
return baseStep.rowsetInputSize();
}
public int rowsetOutputSize() {
return baseStep.rowsetOutputSize();
}
public void setCurrentInputRowSetNr( int arg0 ) {
baseStep.setCurrentInputRowSetNr( arg0 );
}
public void setCurrentOutputRowSetNr( int arg0 ) {
baseStep.setCurrentOutputRowSetNr( arg0 );
}
public void setErrors( long arg0 ) {
baseStep.setErrors( arg0 );
}
public void setLinesRejected( long arg0 ) {
baseStep.setLinesRejected( arg0 );
}
public void setMetaStore( IMetaStore arg0 ) {
baseStep.setMetaStore( arg0 );
}
public void setOutputDone() {
baseStep.setOutputDone();
}
public void setParentVariableSpace( VariableSpace arg0 ) {
baseStep.setParentVariableSpace( arg0 );
}
public void setPartitionID( String arg0 ) {
baseStep.setPartitionID( arg0 );
}
public void setPartitioned( boolean arg0 ) {
baseStep.setPartitioned( arg0 );
}
public void setRepartitioning( int arg0 ) {
baseStep.setRepartitioning( arg0 );
}
public void setRepository( Repository arg0 ) {
baseStep.setRepository( arg0 );
}
public void setRunning( boolean arg0 ) {
baseStep.setRunning( arg0 );
}
public void setStopped( boolean arg0 ) {
baseStep.setStopped( arg0 );
}
public void setUsingThreadPriorityManagment( boolean arg0 ) {
baseStep.setUsingThreadPriorityManagment( arg0 );
}
public void setVariable( String arg0, String arg1 ) {
baseStep.setVariable( arg0, arg1 );
}
public void shareVariablesWith( VariableSpace arg0 ) {
baseStep.shareVariablesWith( arg0 );
}
public void stopAll() {
baseStep.stopAll();
}
public void stopRunning( StepMetaInterface arg0, StepDataInterface arg1 ) throws KettleException {
baseStep.stopRunning( arg0, arg1 );
}
public boolean isDisposed() {
return stepDataInterface.isDisposed();
}
public boolean isEmpty() {
return stepDataInterface.isEmpty();
}
public boolean isFinished() {
return stepDataInterface.isFinished();
}
public boolean isIdle() {
return stepDataInterface.isIdle();
}
public boolean isInitialising() {
return stepDataInterface.isInitialising();
}
public void setStatus( StepExecutionStatus arg0 ) {
stepDataInterface.setStatus( arg0 );
}
// TODO ?
public void check( List<CheckResultInterface> arg0, TransMeta arg1, StepMeta arg2, RowMetaInterface arg3,
String[] arg4, String[] arg5, RowMetaInterface arg6, VariableSpace arg7, Repository arg8, IMetaStore arg9 ) {
super.check( arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 );
}
public Object clone() {
// TODO
Object retval = super.clone();
return retval;
}
public String getDialogClassName() {
return StepPluginPOJODialog.class.getName();
}
public void getFields( RowMetaInterface rowMeta, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repo, IMetaStore metaStore ) throws KettleStepException {
// Add new fields
List<FieldMetadataBean> newFields = getNewFields();
if ( newFields != null ) {
for ( FieldMetadataBean fieldBean : newFields ) {
ValueMetaInterface v = fieldBean.getValueMeta();
v.setOrigin( name );
v.setName( fieldBean.getName() );
rowMeta.addValueMeta( v );
}
}
}
// TODO
public StepMetaInjectionInterface getStepMetaInjectionInterface() {
return super.getStepMetaInjectionInterface();
}
@Override
public String getXML() throws KettleException {
StringBuffer retval = new StringBuffer( 300 );
retval.append( " <fields>" ).append( Const.CR );
List<FieldMetadataBean> fieldBeans = getMetaFields();
if ( fieldBeans != null ) {
for ( FieldMetadataBean fieldBean : fieldBeans ) {
try {
Field field = fieldBean.getField();
Object value = StepPluginUtils.getValueOfFieldFromObject( this, field );
retval.append( " <field>" ).append( Const.CR );
retval.append( " " ).append( XMLHandler.addTagValue( "name", fieldBean.getName() ) );
retval.append( " " ).append(
XMLHandler
.addTagValue( "value", value == null ? "" : StepPluginUtils.getValueAsString( fieldBean, value ) ) );
retval.append( " </field>" ).append( Const.CR );
System.out
.println( "Saving field " + fieldBean.getName() + " = " + ( value == null ? "" : value.toString() ) );
} catch ( Exception e ) {
throw new KettleException( "Couldn't determine the value of field " + fieldBean.getName(), e );
}
}
}
retval.append( " </fields>" ).append( Const.CR );
return retval.toString();
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
List<FieldMetadataBean> fieldBeans = getMetaFields();
Node fields = XMLHandler.getSubNode( stepnode, "fields" );
int nrfields = XMLHandler.countNodes( fields, "field" );
HashMap<String, FieldMetadataBean> fieldMap = StepPluginUtils.getFieldMetadataBeansAsMap( fieldBeans );
if ( fieldMap != null ) {
for ( int i = 0; i < nrfields; i++ ) {
Node fnode = XMLHandler.getSubNodeByNr( fields, "field", i );
final String name = XMLHandler.getTagValue( fnode, "name" );
FieldMetadataBean fieldBean = fieldMap.get( name );
if ( fieldBean != null ) {
try {
Field field = fieldBean.getField();
ValueMetaInterface valueMeta = fieldBean.getValueMeta();
String valueString = XMLHandler.getTagValue( fnode, "value" );
if ( valueString != null ) {
Object convertedValue = valueMeta.convertData( new ValueMetaString(), valueString );
System.out.println( "Converted value from " + valueString + " to " + convertedValue );
// Check for Integer (java.Long) -> java int
if ( ValueMetaInteger.class.isAssignableFrom( valueMeta.getClass() ) ) {
if ( Integer.TYPE.isAssignableFrom( field.getType() ) ) {
convertedValue = ( (Long) convertedValue ).intValue();
} else if ( Short.TYPE.isAssignableFrom( field.getType() ) ) {
convertedValue = ( (Long) convertedValue ).shortValue();
}
}
// TODO Dates/times?
StepPluginUtils.setValueOfFieldToObject( this, field, convertedValue );
} else {
System.out.println( "No value in XML for " + field.getName() + ", using default" );
}
} catch ( KettleException e ) {
throw new KettleXMLException( "No such field: " + name, e );
}
} else {
System.out.println( "No such field: " + name + ", ignoring..." );
}
}
}
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
throws KettleException {
// TODO
super.readRep( rep, metaStore, id_step, databases );
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step )
throws KettleException {
// TODO
super.saveRep( rep, metaStore, id_transformation, id_step );
}
public boolean supportsErrorHandling() {
return super.supportsErrorHandling();
}
/**
* @return the rowMeta
*/
public RowMetaInterface getInputRowMeta() {
return baseStep.getInputRowMeta();
}
/**
* Checks if is basic.
*
* @return true, if is basic
*/
public boolean isBasic() {
return baseStep.isBasic();
}
/**
* Checks if is detailed.
*
* @return true, if is detailed
*/
public boolean isDetailed() {
return baseStep.isDetailed();
}
/**
* Checks if is debug.
*
* @return true, if is debug
*/
public boolean isDebug() {
return baseStep.isDebug();
}
/**
* Checks if is row level.
*
* @return true, if is row level
*/
public boolean isRowLevel() {
return baseStep.isRowLevel();
}
/**
* Log minimal.
*
* @param message
* the message
*/
public void logMinimal( String message ) {
baseStep.logMinimal( message );
}
/**
* Log minimal.
*
* @param message
* the message
* @param arguments
* the arguments
*/
public void logMinimal( String message, Object... arguments ) {
baseStep.logMinimal( message, arguments );
}
/**
* Log basic.
*
* @param message
* the message
*/
public void logBasic( String message ) {
baseStep.logBasic( message );
}
/**
* Log basic.
*
* @param message
* the message
* @param arguments
* the arguments
*/
public void logBasic( String message, Object... arguments ) {
baseStep.logBasic( message, arguments );
}
/**
* Log detailed.
*
* @param message
* the message
*/
public void logDetailed( String message ) {
baseStep.logDetailed( message );
}
/**
* Log detailed.
*
* @param message
* the message
* @param arguments
* the arguments
*/
public void logDetailed( String message, Object... arguments ) {
baseStep.logDetailed( message, arguments );
}
/**
* Log debug.
*
* @param message
* the message
*/
public void logDebug( String message ) {
baseStep.logDebug( message );
}
/**
* Log debug.
*
* @param message
* the message
* @param arguments
* the arguments
*/
public void logDebug( String message, Object... arguments ) {
baseStep.logDebug( message, arguments );
}
/**
* Log rowlevel.
*
* @param message
* the message
*/
public void logRowlevel( String message ) {
baseStep.logRowlevel( message );
}
/**
* Log rowlevel.
*
* @param message
* the message
* @param arguments
* the arguments
*/
public void logRowlevel( String message, Object... arguments ) {
baseStep.logRowlevel( message, arguments );
}
/**
* Log error.
*
* @param message
* the message
*/
public void logError( String message ) {
baseStep.logError( message );
}
/**
* Log error.
*
* @param message
* the message
* @param e
* the e
*/
public void logError( String message, Throwable e ) {
baseStep.logError( message, e );
}
/**
* Log error.
*
* @param message
* the message
* @param arguments
* the arguments
*/
public void logError( String message, Object... arguments ) {
baseStep.logError( message, arguments );
}
/**
* Check feedback.
*
* @param lines
* the lines
* @return true, if successful
*/
protected boolean checkFeedback( long lines ) {
return baseStep.checkFeedback( lines, true );
}
private class MoreAccessibleBaseStep extends BaseStep implements StepInterface {
public MoreAccessibleBaseStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
TransMeta transMeta, Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
public boolean checkFeedback( long lines, boolean dummy ) {
return this.checkFeedback( lines );
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return super.getName();
}
@Override
public List<StepInjectionMetaEntry> getStepInjectionMetadataEntries( Class<?> arg0 ) {
// TODO Auto-generated method stub
return super.getStepInjectionMetadataEntries( arg0 );
}
@Override
public String getTooltip( String attributeKey ) {
// TODO Auto-generated method stub
return super.getTooltip( attributeKey );
}
@Override
public void setDefault() {
// TODO Auto-generated method stub
}
public List<FieldMetadataBean> getNewFields() {
return newFields;
}
}
|
/* Composer.java
Purpose:
Description:
History:
Thu Oct 25 18:24:27 2007, Created by tomyeh
Copyright (C) 2007 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zk.ui.util;
import org.zkoss.zk.ui.Component;
/**
* Represents a composer to initialize a component (or a component of tree)
* when ZK loader is composing a component.
* It is the controller in the MVC pattern, while the component is the view.
*
* <p>To initialize a component, you can implement this interface
* and then specify the class or an instance of it with the apply attribute
* as follows.
*
*<pre><code><window apply="my.MyComposer"/>
*<window apply="${a_composer}"/></code></pre>
*
* <p>Then, ZK loader will
* <ol>
* <li>Invoke {@link ComposerExt#doBeforeCompose}, if the composer
* also implements {@link ComposerExt}.</li>
* <li>Create the component (by use of
* {@link org.zkoss.zk.ui.sys.UiFactory#newComponent}, which creates
* and initializes the component accordingly).
* <li>Invokes {@link ComposerExt#doBeforeComposeChildren}, if
* {@link ComposerExt} is also implemented.</li>
* <li>Composes all children, if any, of this component defined in
* the ZUML page.</li>
* <li>Invokes {@link #doAfterCompose} after all children are, if any,
* composed.</li>
* <li>Posts the onCreate event if necessary.</li>
* </ol>
*
* <p>To intercept the lifecycle of the creation of a page,
* implement {@link Initiator} and specify the class with the init directive.
*
* <p>Note: {@link org.zkoss.zk.ui.ext.AfterCompose} has to be implemented
* as part of a component, while {@link Composer} is a controller used
* to initialize a component (that might or might not implement
* {@link org.zkoss.zk.ui.ext.AfterCompose}).
*
* @author tomyeh
* @since 3.0.0
* @see org.zkoss.zk.ui.ext.AfterCompose
* @see ComposerExt
* @see FullComposer
* @see Initiator
*/
public interface Composer {
/** Invokes after ZK loader creates this component,
* initializes it and composes all its children, if any.
* @param comp the component has been composed
*/
public void doAfterCompose(Component comp) throws Exception;
}
|
package com.movietime.oauth2;
import com.movietime.entities.UsersEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Attila on 2015-05-06.
* A little note; MyAuthenticationProxy is the object used to authenticate the user with its credential.
* It’s not topic of this article describing how it works. If the user is valid, these steps will be completed:
* The framework will update object in the security context;
* The TokenServices will generate a new token object (with expire date of 120 seconds);
* The TokenStore will store the new token generated (stored with InMemoryTokenStore);
* Then, the token will be send to the client.
*/
@Repository
public class MyAuthenticationProxy {
@PersistenceContext
private EntityManager em;
public boolean isValidUser(String principal, String creditentials) {
List<UsersEntity> users = em.createQuery("SELECT u FROM UsersEntity u WHERE userName = :userName", UsersEntity.class)
.setParameter("userName", principal)
.getResultList();
if (users.isEmpty()) {
return false;
}
for(UsersEntity user : users) {
if (creditentials.equals(user.getPassword()) && principal.equals(user.getUserName())) {
return true;
}
}
return false;
}
public MyUserDetails detailsOfUser(String username) {
UsersEntity user = em.createQuery("SELECT u FROM UsersEntity u WHERE userName = :userName", UsersEntity.class)
.setParameter("userName", username)
.getSingleResult();
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return "ROLE_USER";
}
});
if ("A".equals(user.getRole())) {
authorities.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return "ROLE_ADMIN";
}
});
}
MyUserDetails userDetails = new MyUserDetails(user.getUserName(),
user.getPassword(), user.getEmail(), authorities);
return userDetails;
}
}
|
import java.util.Scanner;
class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = scanner.nextInt();
}
}
int min[] = Min(a, n, m);
for(int i = 0; i < m; i++) {
System.out.println("min in " + (i+1) + " line = " + min[i]);
}
}
public static int[] Min (int a[][], int n, int m) {
int arr[] = new int[m];
for (int i = 0; i < n; i++) {
arr[i] = a[i][0];
for(int j = 1; j < m; j++) {
if(a[i][j] < arr[i]) {
arr[i] = a[i][j];
}
}
}
return arr;
}
}
|
package com.mpower.parser;
public class querydataparser {
}
|
package com.lidaye.shopIndex.domain.vo;
import com.lidaye.shopIndex.domain.entity.Navigation;
import lombok.Data;
@Data
public class NavigationVo extends Navigation {
}
|
package com.studentDb.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Entity
@Table(name = "student")
public class Student {
// fields
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@NotNull(message = "Is required")
@Size(min = 1, message = "This field is required")
@Column(name = "first_name")
private String firstName;
@NotNull(message = "Is required")
@Size(min = 1, message = "This field is required")
@Column(name = "last_name")
private String lastName;
@Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$", message = "Invalid format")
@Column(name = "email")
private String email;
@NotNull(message = "This field is required")
@Min(value = 0, message = "Enter positive number")
@Max(value = 150, message = "Enter smaller number (max 150)")
@Column(name = "age")
private Integer age;
@NotNull(message = "This field is required")
@Size(min = 1, message = "This field is required")
@Column(name = "country")
private String country;
@NotNull(message = "This field is required")
@Size(min = 1, message = "This field is required")
@Column(name = "city")
private String city;
// default constructor
public Student() {
}
// getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
+ ", age=" + age + ", country=" + country + ", city=" + city + "]";
}
}
|
package test;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import net.sf.throughglass.glassware.R;
import net.sf.throughglass.network.clients.AuthClient;
import net.sf.throughglass.network.clients.PostClient;
import net.sf.throughglass.utils.BitmapUtils;
import net.sf.throughglass.utils.CameraUtils;
import net.sf.throughglass.utils.CustomTag;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by yowenlove on 14-8-20.
*/
public class TestActivity extends Activity {
private static final String TAG = CustomTag.make("TestActivity");
private static final int ACTION_CODE_IMAGE = 0x01;
private Uri mFile;
private ImageView mImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AuthClient.auth("test123", "test123", null);
}
});
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PostClient.prepare(null);
}
});
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePicture();
}
});
mImageView = (ImageView) findViewById(R.id.imageView);
}
private void takePicture() {
mFile = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
final Intent i = new Intent();
// i.setClass(this, PhotoActivity.class);
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, mFile); // set the image
// file name
startActivityForResult(i, ACTION_CODE_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_CODE_IMAGE:
if (resultCode == RESULT_OK) {
// final String path = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
// final String thumbnail = data.getStringExtra(Intents.EXTRA_THUMBNAIL_FILE_PATH);
// Toast.makeText(this, "path=" + path + ", thumb=" + thumbnail, Toast.LENGTH_LONG).show();
Bitmap bm = BitmapUtils.safeDecodeFile(mFile.getPath(), 640, 640);
mImageView.setImageBitmap(bm);
try {
OutputStream os = new FileOutputStream(mFile.getPath());
bm.compress(Bitmap.CompressFormat.JPEG, 85, os);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
PostClient.post(new String[]{mFile.getPath()}, new String[]{null}, "test");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
} |
package com.pichincha.prueba.bo;
import java.util.List;
import com.pichincha.prueba.dto.TransaccionDTO;
import com.pichincha.prueba.exceptions.BOException;
public interface ITransaccionBO {
/**
* Crea una nueva transaccion
*
* @author Bryan Zamora
* @param intSecuenciaPersona
* @param intSecuenciasCuenta
* @param lsTransaccionDTO
*/
public void crearTransaccion(Integer intSecuenciaPersona, Integer intSecuenciasCuenta,
List<TransaccionDTO> lsTransaccionDTO)throws BOException;
/**
* Consulta las transacciones por cuenta
*
* @author Bryan Zamora
* @param strFechaInicio
* @param strFechaFin
* @param intSecuenciaCuenta
*/
public List<TransaccionDTO> consultarTransacciones(String strFechaInicio, String strFechaFin, Integer intSecuenciaCuenta)throws BOException;
/**
* Elimina una transaccion existente
*
* @author Bryan Zamora
* @param intSecuenciaTransaccion
* @return
*/
public void eliminarTransaccion(Integer intSecuenciaTransaccion)throws BOException;
}
|
package com.xpecya.xds;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
/**
* graph api
* 会自动去重
* 对于任意 vertice A equals vertice B
* 在图中只保留vertice A
* 是否接受null对象取决于实现类
* Iterator遍历的是结点
* 对边的遍历请使用edgeIterator方法
* 不管哪个遍历,对于接口调用方而言,都可以认为是无序的
* @param <T> 结点数据类型
*/
public interface Graph<T> extends Iterable<T> {
/**
* 检查指定结点是否在图中
* @return 检查结果
*/
boolean contains(T vertice);
/**
* 检查指定边是否在图中
* 如果任意一点不在图中 返回false
* 如果在有向图中,只存在end指向start的边,返回false
* @param start 边开始结点
* @param end 边结束结点
* @return 检查结果
*/
boolean contains(T start, T end);
/**
* 检查两个结点是否连接
* 对于有向图,则检查从start到end的路径是否存在
* @param start 起始结点
* @param end 终止结点
* @return 检查结果
*/
boolean isConnect(T start, T end);
/**
* 向图中增加一个结点
* 此结点不与图中任何其他结点连接
* 如果图中已经存在该结点,则什么都不做
* @param vertice 结点
*/
void add(T vertice);
/**
* 向图中增加包含两个结点的一条边
* 对于有向图,生成的边从start结点指向end结点
* 图中不存在的结点将自动新增在图中
* 有向图中,如果已经存在end指向start的边
* 则将该单向边变为双向边
* 如果已经存在start指向end的边,则什么都不做
* @param start 线段开始结点
* @param end 线段结束结点
*/
void add(T start, T end);
/**
* 删除一个结点,同时删除该结点上所有的边
* @param vertice 被删除的结点
*/
void remove(T vertice);
/**
* 删除一条边
* 注意,只删除边,start和end两个结点将保留
* 在有向图中,只会删除指定方向的边
* 如果start和end已经有双向边连接的关系
* 则将双向边转化为单向边,方向为end指向start
* @param start 边起始结点
* @param end 边结束结点
*/
void removeEdge(T start, T end);
/**
* 获取边的遍历器
* @return 边的遍历器
*/
Iterator<Edge<T>> edgeIterator();
/**
* 获取边的并行遍历器
* 参考JDK默认设计
* @return 边的并行遍历器
*/
Spliterator<Edge<T>> edgeSpliterator();
/**
* 边的foreach遍历器
* 参考JDK默认设计
* @param edgeConsumer edge消费者
*/
void forEachEdge(Consumer<? super Edge<T>> edgeConsumer);
/**
* 图的边
* 边由两个点构成
* 分别称作start和end
* 对于有向图,该边从start指向end
* 双向边将由两条单向边表示
* 对于无向图,start 和 end 的顺序由实现类决定
* 对于调用方而言,可以认为是无序的
* @param <T> 结点类型
*/
interface Edge<T> {
/**
* 获取起始结点
* @return 起始结点
*/
T start();
/**
* 获取终止结点
* @return 终止结点
*/
T end();
}
}
|
package com.awstechguide.cms.springjpah2.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.awstechguide.cms.springjpah2.entity.Role;
import com.awstechguide.cms.springjpah2.repository.RoleRepository;
import com.awstechguide.cms.springjpah2.service.RoleService;
@Service
public class RoleServiceImpl implements RoleService{
@Autowired
private RoleRepository repository;
@Override
public Role saveRole(Role role) {
return repository.save(role);
}
}
|
/*
* 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 jc.fog.logic;
import jc.fog.logic.dto.CarportRequestDTO;
import jc.fog.logic.dto.MaterialDTO;
import jc.fog.logic.calculators.RulesCalculatorRafters;
import jc.fog.logic.calculators.RulesCalculatorPost;
import jc.fog.logic.calculators.RulesCalculatorHead;
import java.util.ArrayList;
import java.util.List;
import jc.fog.exceptions.FogException;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Claus
*/
public class CalculatorUTest
{
public CalculatorUTest()
{
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/** Tester udregningen af materialer for stolper. */
@Test
public void postCalculateMaterial() throws FogException
{
// Arrange
List<MaterialDTO> materials = new ArrayList();
// Opret stolpe
materials.add(new MaterialDTO(1, Rules.Materialtype.POST.getMaterialtypeId(), "stolpe", 20, "stk", "stolpetekst", 0, 25));
// Opret spær træ på 1 mtr, hvilket giver brud på rem og spær for hver meter.
materials.add(new MaterialDTO(1, Rules.Materialtype.RAFTERS.getMaterialtypeId(), "test bræt 1", 100, "stk", "bræt", 0, 25));
RulesCalculator.initializeMaterials(materials);
// Opret carport i 5 x 8 mtr, skur i 1.2 x 5 mtr.
CarportRequestDTO carportRequest = new CarportRequestDTO(2, 0, 500, 210, 800, "carport 500 x 800 cm, skur 500 x 120 cm, fladt tag.", 120, 500);
RulesCalculatorPost calculator = new RulesCalculatorPost();
// Act
MaterialCount mc = calculator.calculateMaterials(carportRequest);
// Assert
// Carport i 5 x 8 mtr giver 9 x 6 stolper + skurets (som er i fuld bredde) 3 => 57.
assertEquals(mc.getCount(), 57);
}
/** Tester fejlet udregning af materialer for stolper. Fejlårsag er at spærtræets længde er 0. */
@Test(expected = FogException.class)
public void postCalculateMaterialFail() throws FogException
{
// Arrange
List<MaterialDTO> materials = new ArrayList();
// Opret stolpe
materials.add(new MaterialDTO(1, Rules.Materialtype.POST.getMaterialtypeId(), "stolpe", 20, "stk", "stolpetekst", 0, 25));
// Opret spær træ på 0 mtr., som stolpeberegner skal bruge, for at beregne antal og placering af evt. ekstra stolper.
materials.add(new MaterialDTO(1, Rules.Materialtype.RAFTERS.getMaterialtypeId(), "test bræt 1", 0, "stk", "bræt", 0, 25));
// Initialiser materialer for beregnere.
RulesCalculator.initializeMaterials(materials);
// Opret carport forespørgsel og beregner.
CarportRequestDTO carportRequest = new CarportRequestDTO(2, 0, 500, 210, 800, "carport 500 x 800 cm, skur 500 x 120 cm, fladt tag.", 120, 500);
RulesCalculatorPost calculator = new RulesCalculatorPost();
// Act
MaterialCount mc = calculator.calculateMaterials(carportRequest);
// Assert - her skal vi have FogException.
assertEquals(mc.getCount(), 57);
}
/** Tester udregning af materialer for spær til fladt tag. */
@Test
public void raftersCalculateMaterialNoSlope() throws FogException
{
// Arrange.
List<MaterialDTO> materials = new ArrayList();
// Opret spær træ med længde på 100 cm.
materials.add(new MaterialDTO(1, Rules.Materialtype.RAFTERS.getMaterialtypeId(), "test bræt 2", 100, "stk", "bræt", 0, 12));
// Initialiser materialer for beregnere.
RulesCalculator.initializeMaterials(materials);
// Opret carport forespørgsel og beregner.
CarportRequestDTO carportRequest = new CarportRequestDTO(2,0,500,210,800,"carport 500 x 800 cm, skur 500 x 120 cm, fladt tag.",120,500);
RulesCalculatorRafters calculator = new RulesCalculatorRafters();
// Act.
MaterialCount mc = calculator.calculateMaterials(carportRequest);
// Assert.
/*
Tagets længde: 800 - 2 * udhæng => 740 cm.
Tagets bredde: 500 cm.
Brættets længde: 100 cm. => 5 brædder pr. spær.
Afstand ml. spær, fladt tag: max 55 cm => 14 mellemrum ml. 15 spær => 15 x 5 = 75 brædder.
*/
int expected = 75;
assertEquals(mc.getCount() * calculator.getRaftersCount(), expected);
}
/** Tester udregning af materialer for spær til tag med rejsning. */
@Test
public void raftersCalculateMaterialSlope() throws FogException
{
// Arrange.
List<MaterialDTO> materials = new ArrayList();
// Opret byg selv spær, længde er ligegyldig, da byg-selv spær kan spænde over alle vidder.
materials.add(new MaterialDTO(1, Rules.Materialtype.PRE_FAB_RAFTERS.getMaterialtypeId(), "byg selv spær", 0, "stk", "byg selv spær", 0, 12));
// Initialiser materialer for beregnere.
RulesCalculator.initializeMaterials(materials);
// Opret carport forespørgsel og beregner.
CarportRequestDTO carportRequest = new CarportRequestDTO(2,15,500,210,800,"carport 500 x 800 cm, skur 500 x 120 cm, tag m. rejsning.",120,500);
RulesCalculatorRafters calculator = new RulesCalculatorRafters();
// Act.
MaterialCount mc = calculator.calculateMaterials(carportRequest);
// Assert.
/*
Tagets længde: 800 - 2 * udhæng => 740 cm.
Tagets bredde: 500 cm.
Byg selv spær kan spænde over hele carportens bredde.
Afstand ml. spær, fladt tag: max 89 cm => 9 mellemrum ml. 10 spær.
*/
int expected = 10;
assertEquals(mc.getCount() * calculator.getRaftersCount(), expected);
}
/** Tester om udregning af materialer for spær til fladt tag fejler. Her pga. negativ længde. */
@Test(expected = FogException.class)
public void raftersCalculateMaterialFail() throws FogException
{
// Arrange.
List<MaterialDTO> materials = new ArrayList();
// Opret spær træ med negativ længde.
materials.add(new MaterialDTO(1, Rules.Materialtype.RAFTERS.getMaterialtypeId(), "test bræt 2", -100, "stk", "bræt", 0, 12));
// Initialiser materialer for beregnere.
RulesCalculator.initializeMaterials(materials);
// Opret carport forespørgsel og beregner.
CarportRequestDTO carportRequest = new CarportRequestDTO(2,0,500,210,800,"carport 500 x 800 cm, skur 500 x 120 cm, fladt tag.",120,500);
RulesCalculatorRafters calculator = new RulesCalculatorRafters();
// Act.
MaterialCount mc = calculator.calculateMaterials(carportRequest);
// Assert.
assertTrue(mc.getMaterialDTO() != null);
}
/** Tester om udregning af materialer fejler hvis ingen materialer findes. */
@Test(expected = FogException.class)
public void calculateMaterialFail() throws FogException
{
// Arrange
RulesCalculator.initializeMaterials(null);
// Opret carport forespørgsel og beregner.
CarportRequestDTO carportRequest = new CarportRequestDTO(2,0,500,210,800,"carport 500 x 800 cm, skur 500 x 120 cm, fladt tag.",120,500);
RulesCalculatorRafters calculator = new RulesCalculatorRafters();
// Act.
MaterialCount mc = calculator.calculateMaterials(carportRequest);
// Assert.
assertTrue(mc.getMaterialDTO() != null);
}
/** Tester udregning af hypotenusen, dvs. længden på den skrånende tagflade. */
@Test
public void calculateHypothenuse() throws FogException
{
// Arrange.
RulesCalculator calculator = new RulesCalculatorHead();
// Act.
double width = calculator.calculateSlopedWidth(500, 25); // 500 cm tagflade med 25 graders hældning.
// Assert.
assertEquals((int)Math.ceil(width), 552);
}
/** Tester udregning af hypotenusen med vinkel på 90 grader */
@Test(expected = FogException.class)
public void calculateHypothenuseFailAngleTooBig() throws FogException
{
// Arrange.
RulesCalculator calculator = new RulesCalculatorHead();
// Act.
double width = calculator.calculateSlopedWidth(500, 90); // Ugyldig vidde skal give FogException.
// Assert.
assertEquals((int)Math.ceil(width), 552);
}
/** Tester udregning af hypotenusen med vinkel på 0 grader */
@Test(expected = FogException.class)
public void calculateHypothenuseFailAngleTooSmall() throws FogException
{
// Arrange.
RulesCalculator calculator = new RulesCalculatorHead();
// Act.
double width = calculator.calculateSlopedWidth(500, 0); // Ugyldig vidde skal give FogException.
// Assert.
assertEquals((int)Math.ceil(width), 552);
}
} |
package JavaExe;
public class Recur4 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
if (n < 0) {
System.out.println("正の数を入力してください");
} else {
System.out.println("入力された数のフィボナッチ数列の値は" + fibonatti(n) + "です。");
}
}
static int fibonatti(int n) {
int element1 = 1;
int element2 = 1;
int result = 1;
if (n == 0) {
return element1;
} else if (n == 1) {
return element2;
} else {
for (int i = 0; i < n; i++) {
element1 = result;
result = element1 + element2;
element2 = result + element1;
}
return result;
}
}
}
|
package com.example.demo.util;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class StringDemoTest {
@Mock
StringDemo s;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
s = new StringDemo();
}
@Test
void concat() {
assertEquals("CoffeeBread",s.concat("Coffee","Bread"));
}
@Test
void substring() {
assertEquals("fee",s.substring("Coffee",3));
}
@Test
void testSubstring() {
assertEquals("ff",s.substring("Coffee",2,4));
}
@Test
void compareTa() {
assertEquals(0,s.compareTo("Lexicographically","Lexicographically"));
}
@Test
void compareToIgnoreCase() {
assertEquals(0,s.compareToIgnoreCase("Lexicographically","lexicographically"));
}
@Test
void removeHyponeInJuminBunha() {
assertEquals("990925 1012999",s.removeHyponeInJuminBunha("990925-1012999"));
}
} |
package com.bankerguy.bankerguy;
/**
* Created by nevin on 11/12/2017.
*/
public class Bank {
private String name;
private String bankHistory;
private String bankGroups;
private String bankQuestions;
}
|
package net.acomputerdog.BlazeLoader.util.time;
import net.acomputerdog.BlazeLoader.main.BlazeLoader;
/**
* A clock based on Minecraft's units of time. It is divided up into "days" and "ticks". 1 tick is 1/20 of a second and 1 day is 24000 ticks, or 20 minutes.
*/
public class MinecraftClock {
/**
* Gets the number of ticks of this day.
*
* @return Return the remainder of the total number of ticks divided by 24000.
*/
public int getTicks() {
return (int) (BlazeLoader.numTicks % 24000);
}
/**
* Gets the number of days since the game started.
*
* @return Return the total number of ticks divided by 24000.
*/
public int getDays() {
return (int) (BlazeLoader.numTicks / 24000);
}
}
|
package com.sinotech.settle.exception;
/**
* 业务禁止异常
*/
public class BusinessProhibitionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BusinessProhibitionException() {
super("业务禁止异常");
}
public BusinessProhibitionException(String messageKey, Throwable cause) {
super(messageKey, cause);
}
public BusinessProhibitionException(String messageKey) {
super(messageKey);
}
public BusinessProhibitionException(Throwable cause) {
super("业务禁止异常", cause);
}
}
|
package program.oops;
import java.util.Scanner;
public class Company extends Member{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter the enployee details");
String str = in.next();
Employee m= new Employee(str);
m.setName(in.next());
System.out.println(m.getName());
m.setAge(in.nextInt());
System.out.println(m.getAge());
m.setPhoneno(in.next());
System.out.println(m.getPhoneno());
m.setAddress(in.next());
System.out.println(m.getAddress());
m.setSalary(in.nextDouble());
System.out.println(m.getSalary());
System.out.println("Enter the manager details");
String str2= in.next();
Manager n= new Manager(str2);
n.setName(in.next());
System.out.println(n.getName());
n.setAge(in.nextInt());
System.out.println(n.getAge());
n.setPhoneno(in.next());
System.out.println(n.getPhoneno());
n.setAddress(in.next());
System.out.println(n.getAddress());
n.setSalary(in.nextDouble());
System.out.println(n.getSalary());
}
}
|
package ch6;
import java.util.Scanner;
public class FactorialTest2 {
static long factorial(int n) {
if(n<=0 || n>20) return -1;
if(n<=1) return 1;
return n * factorial(n-1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("값을 입력하세요. >");
int n = sc.nextInt();
long result = 0;
for(int i=1; i<=n; i++) {
result = factorial(i);
if(result==-1) {
System.out.printf("유효하지 않은 값입니다. (0<n<=20): %d%n", n);
break;
}
System.out.printf("%2d! = %20d%n", i, result);
}
}
} |
package com.uchain.cryptohash.bnsnark;
import java.math.BigInteger;
import static com.uchain.cryptohash.bnsnark.Params.B_Fp2;
public class BN128Fp2 extends BN128<Fp2> {
// the point at infinity
static final BN128<Fp2> ZERO = new BN128Fp2(Fp2.ZERO, Fp2.ZERO, Fp2.ZERO);
protected BN128Fp2(Fp2 x, Fp2 y, Fp2 z) {
super(x, y, z);
}
@Override
protected BN128<Fp2> zero() {
return ZERO;
}
@Override
protected BN128<Fp2> instance(Fp2 x, Fp2 y, Fp2 z) {
return new BN128Fp2(x, y, z);
}
@Override
protected Fp2 b() {
return B_Fp2;
}
@Override
protected Fp2 one() {
return Fp2._1;
}
protected BN128Fp2(BigInteger a, BigInteger b, BigInteger c, BigInteger d) {
super(Fp2.create(a, b), Fp2.create(c, d), Fp2._1);
}
public static BN128<Fp2> create(byte[] aa, byte[] bb, byte[] cc, byte[] dd) {
Fp2 x = Fp2.create(aa, bb);
Fp2 y = Fp2.create(cc, dd);
// check for point at infinity
if (x.isZero() && y.isZero()) {
return ZERO;
}
BN128<Fp2> p = new BN128Fp2(x, y, Fp2._1);
// check whether point is a valid one
if (p.isValid()) {
return p;
} else {
return null;
}
}
}
|
package io.github.aquerr.chestrefill;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
/**
* Created by Aquerr on 2018-02-09.
*/
public abstract class PluginInfo
{
public static final String Id = "chestrefiller";
public static final String Name = "Chest Refiller";
public static final String Version = "1.3.1";
public static final String Description = "Plugin for restoring contents of a container after the specified time.";
public static final String Url = "https://github.com/Florian262000/ChestRefill";
public static final Text PluginPrefix = Text.of(TextColors.GOLD, "[CR] ");
public static final String Authors = "Aquerr and Florian_26";
}
|
package com.juannarvaez.taskworkout.model.entily;
import java.io.Serializable;
import java.util.Date;
public class SeguimientoPeso implements Serializable {
double IMC ;
double peso;
String fecha;
double altura;
Date fechaDate;
public Date getFechaDate() {
return fechaDate;
}
public void setFechaDate(Date fechaDate) {
this.fechaDate = fechaDate;
}
public SeguimientoPeso(double IMC, double peso, String fecha, double altura,Date fechaDate) {
this.IMC = IMC;
this.peso = peso;
this.fecha = fecha;
this.altura = altura;
this.fechaDate=fechaDate;
}
public SeguimientoPeso() {
this.IMC = IMC;
this.peso = peso;
this.fecha = fecha;
this.altura = altura;
this.fechaDate=fechaDate;
}
public double getIMC() {
return IMC;
}
public void setIMC(double IMC) {
this.IMC = IMC;
}
public double getPeso() {
return peso;
}
public void setPeso(double peso) {
this.peso = peso;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public double getAltura() {
return altura;
}
public void setAltura(double altura) {
this.altura = altura;
}
public String toString() {
return " "+getPeso()+ " "+getIMC() ;
}
}
|
package com.pisen.ott.launcher.localplayer.image;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.izy.util.LogCat;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.volley.BitmapLruCache;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.pisen.ott.launcher.AppRecommendActivity;
import com.pisen.ott.launcher.R;
import com.pisen.ott.launcher.config.OnImageListener;
import com.pisen.ott.launcher.localplayer.MediaBrowserActivity;
import com.pisen.ott.launcher.localplayer.music.MusicPlayerActivity;
//import com.pisen.ott.launcher.config.ImageAsyncTask;
/**
* 图片浏览器Activity
*/
public class ImageViewerActivity extends Activity implements ViewFactory {
private static List<String> imgPathList;// 图片路径列表
private static int currIndex = -1;
private ImageSwitcher imgViewer;
private TextView txtStatus;
private BitmapLruCache cache;
private ImageAsyncTask newRequest;
Bitmap bm;
String filePath = "";
static final String DirectionLeft = "left";
static final String DirectionRight = "right";
public static void start(Context context, List<String> playbacklist, int currIndex) {
ImageViewerActivity.imgPathList = playbacklist;
ImageViewerActivity.currIndex = currIndex;
context.startActivity(new Intent(context, ImageViewerActivity.class));
}
@Override
protected void onDestroy() {
ImageViewerActivity.imgPathList = null;
ImageViewerActivity.currIndex = -1;
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_viewer_act);
imgViewer = (ImageSwitcher) findViewById(R.id.imgViewer);
imgViewer.setFactory(this);
imgViewer.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
imgViewer.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
txtStatus = (TextView) findViewById(R.id.txtStatus);
// 建立缓存
cache = BitmapLruCache.getInstance(this);
showImageView(currIndex);
}
// 获得系统可用内存信息
private String getSystemAvaialbeMemorySize() {
// 获得MemoryInfo对象
MemoryInfo memoryInfo = new MemoryInfo();
// 获得系统可用内存,保存在MemoryInfo对象上
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
mActivityManager.getMemoryInfo(memoryInfo);
long memSize = memoryInfo.availMem;
// 字符类型转换
String availMemStr = formateFileSize(memSize);
return availMemStr;
}
// 调用系统函数,字符串转换 long -String KB/MB
private String formateFileSize(long size) {
return Formatter.formatFileSize(this, size);
}
public void prevImage() {
currIndex = getCurrentIndex(--currIndex);
showImageView(currIndex);
}
public void nextImage() {
currIndex = getCurrentIndex(++currIndex);
showImageView(currIndex);
}
private int getCurrentIndex(int index) {
if (index < 0) {
index = imgPathList.size() - 1;
} else if (index > imgPathList.size() - 1) {
index = 0;
}
return index;
}
private void showImageView(int index) {
if (imgPathList == null || currIndex >= imgPathList.size()) {
Toast.makeText(this, "播放出错", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (index < 0) {
index = 0;
} else if (index > imgPathList.size() - 1) {
index = imgPathList.size() - 1;
}
LogCat.i("image index = %s", index);
final String filePath = imgPathList.get(index);
txtStatus.setText(String.format("%s/%s", index + 1, imgPathList.size()));
if (cache.get(filePath) != null) {
Bitmap cacheBm = cache.get(filePath);
setImg(cacheBm);
} else {
if (newRequest != null/*
* &&newRequest.getStatus() ==
* android.os.AsyncTask.Status.RUNNING
*/) {
newRequest.cancel(true);
// newRequest = null;
}
// imgViewer.setImageDrawable(null);
newRequest = new ImageAsyncTask(this, filePath, new OnImageListener() {
@Override
public void onSuccess(Bitmap response, boolean isCache) {
if (response != null) {
Log.i("testMsg", "add cache " + currIndex);
// WeakReference<Bitmap> wrf = new
// WeakReference<Bitmap>(response);
cache.put(filePath, response);
setImg(response);
}
}
});
// newRequest.executeExt();
newRequest.execute();
}
}
private void setImg(Bitmap b) {
BitmapDrawable id = new BitmapDrawable(getResources(), b);
imgViewer.setImageDrawable(id);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Toast.makeText(this, " cacheSize = "+cache.size(),
// Toast.LENGTH_SHORT).show();
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
prevImage();
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
nextImage();
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return i;
}
}
|
package com.fanfte.listener.mysync;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Created by tianen on 2018/11/6
*
* @author fanfte
* @date 2018/11/6
**/
public class MySyncMain {
public static void main(String[] args) {
MyPromise promise = new MyPromise();
Executor executor = Executors.newFixedThreadPool(1);
Task t = new Task();
executor.execute(new MyRunnable<String>(promise) {
@Override
public String doWork() {
return t.doTask("world");
}
});
promise.addListener(new MyListener() {
@Override
public void operationComplete(MyPromise promise) {
String result;
if(promise.isSuccess()) {
result = (String) promise.get();
System.out.println(result);
} else {
Exception e = (Exception) promise.get();
e.printStackTrace();
}
}
});
}
}
|
package com.company;
import javax.swing.*;
import org.json.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ThirdFrame extends JFrame {
SecondFrame secondFrame;
CommonResource commonResource;
JLabel label;
JTextField inputArea;
JTextArea resultArea;
JButton btnSubmit, btnClear, btnReturn;
JSONObject jsonObject;
public ThirdFrame(SecondFrame secondFrame, CommonResource commonResource) throws Exception {
super("Second Frame");
this.secondFrame = secondFrame;
this.commonResource = commonResource;
setSize(300, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
createComponents();
setVisible(true);
}
public void createComponents() throws Exception {
JSONArray array = new JSONArray(commonResource.buffer.toString());
jsonObject = new JSONObject(array.getJSONObject(commonResource.selectedID).toString());
label = new JLabel("Enter in " + jsonObject.getString("title"));
btnSubmit = new JButton("Submit");
btnReturn = new JButton("Return");
btnClear = new JButton("Clear");
inputArea = new JTextField();
resultArea = new JTextArea();
resultArea.setEditable(false);
JPanel mainPanel = new JPanel(new GridLayout(5, 1));
JPanel innerPanel = new JPanel(new GridLayout(1, 2));
innerPanel.add(btnSubmit);
innerPanel.add(btnClear);
mainPanel.add(label);
mainPanel.add(inputArea);
mainPanel.add(innerPanel);
mainPanel.add(resultArea);
mainPanel.add(btnReturn);
add(mainPanel);
addActions();
}
public void addActions()
{
btnReturn.addActionListener((event)->{
secondFrame.setVisible(true);
dispose();
});
btnClear.addActionListener((event)->{
inputArea.setText(null);
resultArea.setText(null);
});
btnSubmit.addActionListener((event)->{
try {
double curr = jsonObject.getDouble("cb_price");
double val = Double.parseDouble(String.valueOf(inputArea.getText()));
double res = curr * val;
resultArea.setText("Result : "+res + " sums");
}catch (Exception e)
{
System.out.println(e.getClass());
}
});
}
}
/**
* try {
* JSONArray array = new JSONArray(commonResource.buffer.toString());
* JSONObject object = new JSONObject(array.getJSONObject(commonResource.selectedID).toString());
* <p>
* double val = object.getDouble("cb_price");
* label.setText(object.getDouble("cb_price")+" , "+object.getString("title"));
* } catch (Exception e) {
* System.out.println(e.getClass());
* }
**/ |
package kr.co.people_gram.app;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by 광희 on 2015-09-18.
*/
public class SubGroupPeopleListAdapter extends BaseAdapter{
private Context mContext;
private int layout;
private final ArrayList<SubGroupPeopleListDTO> peoplelist;
LayoutInflater inf;
private ViewHolder viewHolder = null;
public String[] uid_check;
public String[] username_check;
public boolean[] isCheckedConfrim;
public SubGroupPeopleListAdapter(Context mContext, int layout, ArrayList<SubGroupPeopleListDTO> peoplelist)
{
this.mContext = mContext;
this.layout = layout;
this.peoplelist = peoplelist;
inf = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inf.inflate(layout, null);
this.isCheckedConfrim = new boolean[peoplelist.size()];
this.uid_check = new String[peoplelist.size()];
username_check = new String[peoplelist.size()];
}
@Override
public int getCount() {
return peoplelist.size();
}
@Override
public Object getItem(int position) {
return peoplelist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void setChecked(int position) {
SubGroupPeopleListDTO dto = peoplelist.get(position);
Log.d("people_gram", dto.get_profile_uid());
if(isCheckedConfrim[position] == true) {
uid_check[position] = "";
username_check[position] = "";
dto.set_checked(false);
isCheckedConfrim[position] = false;
} else {
uid_check[position] = dto.get_profile_uid();
username_check[position] = dto.get_profile_username();
dto.set_checked(true);
isCheckedConfrim[position] = !isCheckedConfrim[position];
}
for(int i = 0; i<isCheckedConfrim.length; i++) {
Log.d("people_gram", "그룹선택="+isCheckedConfrim[i] + "::::" + uid_check[i]);
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
viewHolder = new ViewHolder();
convertView = inf.inflate(layout, null);
viewHolder.cBox = (CheckBox) convertView.findViewById(R.id.chk_user);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.cBox.setClickable(false);
viewHolder.cBox.setFocusable(false);
viewHolder.cBox.setChecked(isCheckedConfrim[position]);
viewHolder.cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//setChecked(position);
//Log.d("people_gram", "선택="+isChecked);
}
});
SubGroupPeopleListDTO dto = peoplelist.get(position);
TextView listview_people_list_username = (TextView) convertView.findViewById(R.id.listview_people_list_username);
//TextView listview_people_list_email = (TextView) convertView.findViewById(R.id.listview_people_list_email);
ImageView listview_proplelist_img = (ImageView) convertView.findViewById(R.id.listview_proplelist_img);
listview_people_list_username.setText(dto.get_profile_username());
//listview_people_list_email.setText(dto.get_profile_email());
//CheckBox chk_user = (CheckBox) convertView.findViewById(R.id.chk_user);
//chk_user.setChecked(false);
//Log.d("people_gram", String.valueOf(dto.get_profile_new_cnt()));
String people_type = dto.get_profile_type();
switch (people_type) {
case "A":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_small_type_a);
break;
case "I":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_small_type_i);
break;
case "E":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_small_type_e);
break;
case "D":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_small_type_d);
break;
case "":
listview_proplelist_img.setImageResource(R.mipmap.peoplelist_small_type_defailt);
break;
/*
default:
listview_proplelist_img.setVisibility(View.GONE);
break;
*/
}
//listview_proplelist_img.setTag(position);
/*
listview_proplelist_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,SubMyType_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("mytype", people_type);
mContext.startActivity(intent);
}
});
*/
return convertView;
}
class ViewHolder {
// 새로운 Row에 들어갈 CheckBox
private CheckBox cBox = null;
}
}
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class LoginPage {
private WebDriver driver;
private By usernameField = By.id("user-name");
private By passwordField = By.id("password");
private By loginButton = By.id("login-button");
private By errorMsg = By.tagName("h3");
private By acceptedUsernames = By.cssSelector("#login_credentials h4");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void setUsername(String username){
driver.findElement(usernameField).sendKeys(username);
}
public void setPassword(String password){
driver.findElement(passwordField).sendKeys(password);
}
public HomePage clickOnLogin(){
driver.findElement(loginButton).click();
return new HomePage(driver);
}
public String getErrorMsgLogin(){
return driver.findElement(errorMsg).getText();
}
public String getLoginUsernames(){
return driver.findElement(acceptedUsernames).getText();
}
}
|
/*
* 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 nl.rkk.marktplaats.admin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.rkk.marktplaats.facades.AdFacadeLocal;
import nl.rkk.marktplaats.models.Ad;
import nl.rkk.marktplaats.models.MyUser;
import nl.rkk.marktplaats.models.UserRole;
/**
*
* @author Kaj
*/
public class DeleteAdServlet extends HttpServlet {
@EJB
private AdFacadeLocal ads;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DeleteAdServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DeleteAdServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MyUser user = (MyUser) request.getSession().getAttribute("currentUser");
String param = request.getParameter("adId");
if ( user == null ) {
response.sendRedirect("/marktplaats-war/login");
} else {
if ( user.getType() == UserRole.Admin ) {
if ( param != null ) {
Integer adId = Integer.parseInt(param);
Ad deleteAd = this.ads.find(adId);
if ( deleteAd == null ) {
request.setAttribute("errorMsg", "Geen advertentie gevonden met id = " + param + "!");
} else {
this.ads.remove(deleteAd);
request.setAttribute("notification", "Advertentie \"" + deleteAd.getTitle() + "\" is verwijderd!");
}
} else {
request.setAttribute("errorMsg", "Kan geen advertentie verwijderen: geen adId gevonden.");
}
request.getRequestDispatcher("/ads/ads.jsp").forward(request, response);
}
response.sendRedirect("/marktplaats-war");
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package gov.nih.mipav.view.renderer.WildMagic.Decimate;
import java.io.*;
import WildMagic.LibFoundation.Mathematics.*;
import WildMagic.LibGraphics.SceneGraph.Attributes;
import WildMagic.LibGraphics.SceneGraph.IndexBuffer;
import WildMagic.LibGraphics.SceneGraph.VertexBuffer;
public class TriangleMesh {
double maxX = 0.0;
double maxY = 0.0;
double maxZ = 0.0;
double minX = 0.0;
double minY = 0.0;
double minZ = 0.0;
Mesh myobj = null;
boolean dipli = false;
Vector3f[] point = null;
double aveH;
double sdviH;
double[] H = null;
double minarea = 1000.0;
double threshold = 1.5;
int[] index = null;
Vector3f[] laplace = null;
Vector3f[] bilaplace = null;
Vector3f[] KnotInit = null;
int numberV = 0;
int numberF = 0;
int numberE = 0;
int EulerC = 0;
double scaler = 1.0;
/* true is original, false is skeleton */
IDList BEHead = null;
IDList BETail = null;
int[][] FaceArray;
int[] neighborI = null;
int[] neighborF = null;
int[] neighborV = null;
IDList[] FHead = null;
IDList[] FTail = null;
IDList[] VHead = null;
IDList[] VTail = null;
IDList[] IHead = null;
IDList[] ITail = null;
int[] boundary = null;
int numboundary = 0;
/* Subdivide Attribute */
Vector3f[] subpoint = null;
int[][] subFace = null;
/* GH-Decimation Attribute */
LODMesh mydecimate = null;
Vector3f tmppoint3d1 = new Vector3f(0.0f, 0.0f, 0.0f);
Vector3f tmppoint3d2 = new Vector3f(0.0f, 0.0f, 0.0f);
Vector3f Wvex = new Vector3f(0.0f, 0.0f, 0.0f);
int[] ffR = null;
int numberVOrig, numberFOrig;
Vector3f[] pointOrig = null;
int[][] FaceOrig = null;
String meshName = null;
public TriangleMesh(VertexBuffer pkVBuffer, IndexBuffer pkIBuffer) {
int dnumV = 0, dnumF = 0;
dnumV = pkVBuffer.GetVertexQuantity();
numberVOrig = dnumV;
pointOrig = new Vector3f[numberVOrig];
dnumF = pkIBuffer.GetIndexQuantity() / 3;
numberFOrig = dnumF;
FaceOrig = new int[numberFOrig][3];
memoryallocation(dnumV, dnumF);
ffR = new int[dnumF];
int i;
double dx, dy, dz;
double maxvalue = 0.0;
maxX = 0.0;
maxY = 0.0;
maxZ = 0.0;
minX = 0.0;
minY = 0.0;
minZ = 0.0;
boolean firstcheck = true;
float[] vertex;
for (i = 0; i < numberV; i++) {
vertex = pkVBuffer.GetVertex(i);
dx = vertex[0];
dy = vertex[1];
dz = vertex[2];
InitializeData(i, dx, dy, dz);
pointOrig[i] = new Vector3f((float)dx, (float)dy, (float)dz);
if (firstcheck) {
firstcheck = false;
maxX = dx;
maxY = dy;
maxZ = dz;
minX = dx;
minY = dy;
minZ = dz;
} else {
if (maxX < dx)
maxX = dx;
if (maxY < dy)
maxY = dy;
if (maxZ < dz)
maxZ = dz;
if (minX > dx)
minX = dx;
if (minY > dy)
minY = dy;
if (minZ > dz)
minZ = dz;
}
if (maxvalue < Math.abs(dx))
maxvalue = Math.abs(dx);
if (maxvalue < Math.abs(dy))
maxvalue = Math.abs(dy);
if (maxvalue < Math.abs(dz))
maxvalue = Math.abs(dz);
}
if (maxvalue != 0.0) {
ReScale((1.0 / maxvalue));
}
int di, dj, dk;
int[] indexData = pkIBuffer.GetData();
for (i = 0; i < numberF; i++) {
di = indexData[3 * i];
dj = indexData[3 * i + 1];
dk = indexData[3 * i + 2];
ffR[i] = -1;
MakeFace(i, di, dj, dk);
FaceOrig[i][0] = di;
FaceOrig[i][1] = dj;
FaceOrig[i][2] = dk;
}
MakeArrayObj(3);
SetBoundaryStrips();
setEdgeN();
PropertyUpdate();
}
public void SetName(String name) {
meshName = name;
}
public String GetName() {
return meshName;
}
public void doDecimation(double dv) throws Exception {
try {
Decimation(dv);
} catch (Exception e) {
}
ffR = new int[numberF];
for (int i = 0; i < numberF; i++)
ffR[i] = -1;
}
public void ReScale(double dv) {
// scaler = dv;
scaler = 1.0;
}
public void setEdgeN() {
int i = 0;
numberE = 0;
for (i = 0; i < numberV; i++) {
numberE += (neighborI[i]);
}
numberE /= 2;
EulerC = numberV - numberE + numberF;
// System.out.println("V = " + numberV + ", F = " + numberF + ", E = " + numberE);
// System.out.println("EulerC = " + EulerC);
}
public void InitializeData(int di, double dx, double dy, double dz) {
index[di] = di;
point[di] = new Vector3f((float)dx, (float)dy, (float)dz);
laplace[di] = new Vector3f(0.0f, 0.0f, 0.0f);
bilaplace[di] = new Vector3f(0.0f, 0.0f, 0.0f);
H[di] = 0.0;
neighborV[di] = 0;
neighborF[di] = 0;
neighborI[di] = 0;
VHead[di] = new IDList();
VTail[di] = new IDList();
this.Init(VHead[di], VTail[di]);
FHead[di] = new IDList();
FTail[di] = new IDList();
this.Init(FHead[di], FTail[di]);
IHead[di] = new IDList();
ITail[di] = new IDList();
this.Init(IHead[di], ITail[di]);
KnotInit[di] = new Vector3f((float)dx, (float)dy, (float)dz);
}
public void memoryallocation(int dnumberV, int dnumberF) {
numberV = dnumberV;
numberF = dnumberF;
index = new int[numberV];
point = new Vector3f[numberV];
H = new double[numberV];
boundary = new int[numberV];
neighborV = new int[numberV];
neighborF = new int[numberV];
neighborI = new int[numberV];
VHead = new IDList[numberV];
VTail = new IDList[numberV];
FHead = new IDList[numberV];
FTail = new IDList[numberV];
IHead = new IDList[numberV];
ITail = new IDList[numberV];
KnotInit = new Vector3f[numberV];
laplace = new Vector3f[numberV];
bilaplace = new Vector3f[numberV];
FaceArray = new int[numberF][3];
}
/**
* Dispose the local memory.
*/
public void dispose() {
for ( int i = 0; i < numberV; i++ ) {
point[i] = null;
laplace[i] = null;
bilaplace[i] = null;
VHead[i] = null;
VTail[i] = null;
FHead[i] = null;
FTail[i] = null;
IHead[i] = null;
ITail[i] = null;
KnotInit[i] = null;
}
index = null;
point = null;
H = null;
boundary = null;
neighborV = null;
neighborF = null;
neighborI = null;
VHead = null;
VTail = null;
FHead = null;
FTail = null;
IHead = null;
ITail = null;
KnotInit = null;
laplace = null;
bilaplace = null;
FaceArray = null;
subpoint = null;
subFace = null;
if ( myobj != null ) {
myobj.dispose();
myobj = null;
}
if ( mydecimate != null ) {
mydecimate.dispose();
mydecimate = null;
}
}
public void Init(IDList h, IDList t) {
h.next = new IDList();
t.back = new IDList();
h.next = t;
t.back = h;
}
public IDList next(IDList now) {
return (now.next);
}
public IDList back(IDList now) {
return (now.back);
}
public void AppendVF(int myID, IDList dVTail) {
IDList now = new IDList(myID);
IDList dummy = dVTail.back;
now.next = dVTail;
dVTail.back = now;
now.back = dummy;
dummy.next = now;
}
private boolean SearchI(int dID, IDList dIHead, IDList dITail) {
IDList now = dIHead;
while (next(now) != dITail) {
now = next(now);
if ((now.ID == dID)) {
return true;
}
}
return false;
}
public void AppendI(int dID, IDList dIHead, IDList dITail, int nowID,
int[] dnum) {
if (dID != nowID) {
if (!SearchI(dID, dIHead, dITail)) {
IDList now = new IDList(dID);
IDList dummy = dITail.back;
now.next = dITail;
dITail.back = now;
now.back = dummy;
dummy.next = now;
dnum[nowID]++;
}
} else {
// // System.out.println("Check !!!");
}
}
public void MakeFace(int i, int di, int dj, int dk) {
FaceArray[i][0] = di;
FaceArray[i][1] = dj;
FaceArray[i][2] = dk;
/* One */
this.AppendVF(i, FTail[di]);
neighborF[di]++;
this.AppendI(dj, IHead[di], ITail[di], di, neighborI);
this.AppendI(dk, IHead[di], ITail[di], di, neighborI);
this.AppendVF(dj, VTail[di]);
neighborV[di]++;
this.AppendVF(dk, VTail[di]);
neighborV[di]++;
/* Two */
this.AppendVF(i, FTail[dj]);
neighborF[dj]++;
this.AppendI(di, IHead[dj], ITail[dj], dj, neighborI);
this.AppendI(dk, IHead[dj], ITail[dj], dj, neighborI);
this.AppendVF(dk, VTail[dj]);
neighborV[dj]++;
this.AppendVF(di, VTail[dj]);
neighborV[dj]++;
/* Three */
this.AppendVF(i, FTail[dk]);
neighborF[dk]++;
this.AppendI(di, IHead[dk], ITail[dk], dk, neighborI);
this.AppendI(dj, IHead[dk], ITail[dk], dk, neighborI);
this.AppendVF(di, VTail[dk]);
neighborV[dk]++;
this.AppendVF(dj, VTail[dk]);
neighborV[dk]++;
}
public void SetBoundaryStrips() {
int i = 0;
IDList now;
int[] dummyboundary = null;
numboundary = 0;
if (neighborI != null && neighborF != null && boundary != null) {
dummyboundary = new int[numberV];
for (i = 0; i < numberV; i++) {
if (((neighborI[i]) == neighborF[i]) && (neighborF[i] != 0)
&& (neighborI[i] != 0)) {
dummyboundary[i] = 0;
} else {
dummyboundary[i] = 1;
}
boundary[i] = 0;
}
for (i = 0; i < numberV; i++) {
if (dummyboundary[i] == 1) {
boundary[i] = 1;
// deeplevel[i] = 1;
numboundary++;
now = VHead[i];
while (next(now) != VTail[i]) {
now = next(now);
if (boundary[now.ID] != 1)
boundary[now.ID] = 2;
now = next(now);
}
}
}
}
}
public void MakeArrayObj(int dv) {
myobj = new Mesh(dv);
this.MakeArrayData();
}
public void MakeArrayData() {
int j = 0;
// myobj.reNew(numberV, numberF, scaler);
myobj.reNew(numberV, numberF, 1.0);
/* old shadings */
for (j = 0; j < numberF; j++) {
myobj.MakeFace(j, FaceArray[j][0], FaceArray[j][1], FaceArray[j][2], point);
}
// end new shading
}
public void UpdatePolygon() {
int j = 0;
for (j = 0; j < numberF; j++) {
myobj.MakeFace(j, FaceArray[j][0], FaceArray[j][1], FaceArray[j][2], point);
}
}
public void PropertyUpdate() {
int i, j;
Vector3f[] dv = new Vector3f[9];
IDList now;
boolean secondfirst = true;
for (i = 0; i < 9; i++)
dv[i] = new Vector3f(0.0f, 0.0f, 0.0f);
double tarea = 0.0;
double area = 0.0;
aveH = 0.0;
sdviH = 0.0;
double angle = 0.0;
double anglesum = 0.0;
double divisor = 0.0;
double dummytemp = 0.0;
double InnW1 = 0.0;
double InnW2 = 0.0;
double dl1 = 0.0;
double dl2 = 0.0;
for (i = 0; i < numberV; i++) {
if (boundary[i] != 1) {
divisor += 1.0;
now = VHead[i];
area = 0.0;
area = 0.0;
tarea = 0.0;
anglesum = 0.0;
for (j = 0; j < 9; j++) {
dv[j].X = 0.0f;
dv[j].Y = 0.0f;
dv[j].Z = 0.0f;
}
while (next(now) != VTail[i]) {
now = next(now);
this.makeVector(dv[0], point[i], point[next(now).ID]);
this.makeVector(dv[1], point[next(now).ID], point[now.ID]);
this.makeVector(dv[2], point[i], point[now.ID]);
this.makeVector(dv[3], point[now.ID], point[next(now).ID]);
this.CrossVector(dv[4], dv[2], dv[0]);
dl1 = Point3dSize(dv[2]);
dl2 = Point3dSize(dv[0]);
if (dl1 == 0.0)
dl1 = 1.0;
if (dl2 == 0.0)
dl2 = 1.0;
area = ((1.0 / 2.0) * (Point3dSize(dv[4])));
angle = Math
.acos((InnerProduct(dv[2], dv[0]) / (dl1 * dl2)));
anglesum += angle;
InnW1 = InnerProduct(dv[0], dv[1]);
InnW2 = InnerProduct(dv[2], dv[3]);
tarea += area;
this.ScalarVector(dv[5], InnW1, dv[2]);
this.ScalarVector(dv[6], InnW2, dv[0]);
if (area != 0.0) {
dv[7].X = (float)(dv[7].X + ((1.0 / (4.0 * area)) * (dv[5].X + dv[6].X)));
dv[7].Y = (float)(dv[7].Y + ((1.0 / (4.0 * area)) * (dv[5].Y + dv[6].Y)));
dv[7].Z = (float)(dv[7].Z + ((1.0 / (4.0 * area)) * (dv[5].Z + dv[6].Z)));
dv[8].X = dv[8].X + dv[4].X;
dv[8].Y = dv[8].Y + dv[4].Y;
dv[8].Z = dv[8].Z + dv[4].Z;
}
now = next(now);
}
dummytemp = Point3dSize(dv[8]);
if (dummytemp != 0.0) {
tmppoint3d1.X = (float)(((dv[8].X) / dummytemp));
tmppoint3d1.Y = (float)(((dv[8].Y) / dummytemp));
tmppoint3d1.Z = (float)(((dv[8].Z) / dummytemp));
}
if (tarea != 0.0) {
tmppoint3d2.X = (float)(-((dv[7].X) / (2.0 * tarea)));
tmppoint3d2.Y = (float)(-((dv[7].Y) / (2.0 * tarea)));
tmppoint3d2.Z = (float)(-((dv[7].Z) / (2.0 * tarea)));
}
// K[i] = 3.0*(2.0*Math.PI - anglesum)/(tarea);
H[i] = 3.0 * InnerProduct(tmppoint3d1, tmppoint3d2);
} else {
H[i] = 0.0;
}
if (secondfirst) {
secondfirst = false;
aveH = H[i];
sdviH = (H[i] * H[i]);
} else {
aveH += H[i];
sdviH += (H[i] * H[i]);
}
}
aveH /= divisor;
sdviH -= (aveH * aveH);
sdviH /= divisor;
sdviH = Math.sqrt(sdviH);
}
private void UpdatePolyStructure() {
memoryallocation(numberV, numberF);
int i;
// System.out.println("Init finish.");
double dx = 0.0;
double dy = 0.0;
double dz = 0.0;
double maxvalue = 0.0;
for (i = 0; i < numberV; i++) {
dx = subpoint[i].X;
dy = subpoint[i].Y;
dz = subpoint[i].Z;
if (maxvalue < Math.abs(dx))
maxvalue = Math.abs(dx);
if (maxvalue < Math.abs(dy))
maxvalue = Math.abs(dy);
if (maxvalue < Math.abs(dz))
maxvalue = Math.abs(dz);
InitializeData(i, dx, dy, dz);
}
// System.out.println("Now Finish Read Vertices.");
if (maxvalue != 0.0) {
// scaler = 1.0/maxvalue;
// System.out.println("scaler = " + scaler);
/*
* for(i=0;i<numberV;i++){ point[i].x *= scaler; point[i].y *=
* scaler; point[i].z *= scaler; KnotInit[i].x *= scaler;
* KnotInit[i].y *= scaler; KnotInit[i].z *= scaler; }
*/
}
// System.out.println("Finish Scaling");
int di, dj, dk;
for (i = 0; i < numberF; i++) {
di = subFace[i][0];
dj = subFace[i][1];
dk = subFace[i][2];
MakeFace(i, di, dj, dk);
}
// System.out.println("Finish Read Faces.");
this.SetBoundaryStrips();
MakeArrayData();
// System.out.println("Finish Update Data Section.");
}
private void UpdatePolyStructureToOrig() {
memoryallocation(numberVOrig, numberFOrig);
int i;
double dx = 0.0;
double dy = 0.0;
double dz = 0.0;
double maxvalue = 0.0;
for (i = 0; i < numberVOrig; i++) {
dx = pointOrig[i].X;
dy = pointOrig[i].Y;
dz = pointOrig[i].Z;
if (maxvalue < Math.abs(dx))
maxvalue = Math.abs(dx);
if (maxvalue < Math.abs(dy))
maxvalue = Math.abs(dy);
if (maxvalue < Math.abs(dz))
maxvalue = Math.abs(dz);
InitializeData(i, dx, dy, dz);
}
if (maxvalue != 0.0) {
// scaler = 1.0/maxvalue;
/*
* for(i=0;i<numberV;i++){ point[i].x *= scaler; point[i].y *=
* scaler; point[i].z *= scaler; KnotInit[i].x *= scaler;
* KnotInit[i].y *= scaler; KnotInit[i].z *= scaler; }
*/
}
int di, dj, dk;
for (i = 0; i < numberFOrig; i++) {
di = FaceOrig[i][0];
dj = FaceOrig[i][1];
dk = FaceOrig[i][2];
MakeFace(i, di, dj, dk);
}
// System.out.println("Finish Read Faces to Origin.");
SetBoundaryStrips();
MakeArrayData();
// System.out.println("Finish Update to Origin Data Section .");
}
public void makeVector(Vector3f out, Vector3f in1, Vector3f in2) {
out.X = (in2.X - in1.X);
out.Y = (in2.Y - in1.Y);
out.Z = (in2.Z - in1.Z);
}
public void CrossVector(Vector3f out, Vector3f in1, Vector3f in2) {
out.X = (in1.Y * in2.Z - in2.Y * in1.Z);
out.Y = (in1.Z * in2.X - in2.Z * in1.X);
out.Z = (in1.X * in2.Y - in2.X * in1.Y);
}
public double InnerProduct(Vector3f in1, Vector3f in2) {
return (in1.X * in2.X + in1.Y * in2.Y + in1.Z * in2.Z);
}
public void ScalarVector(Vector3f out, double dv, Vector3f in) {
out.X = (float)(dv * in.X);
out.Y = (float)(dv * in.Y);
out.Z = (float)(dv * in.Z);
}
public double Point3dSize(Vector3f in) {
return Math.sqrt(((in.X * in.X) + (in.Y * in.Y) + (in.Z * in.Z)));
}
public double Distance(Vector3f in1, Vector3f in2) {
return Math
.sqrt((((in1.X - in2.X) * (in1.X - in2.X))
+ ((in1.Y - in2.Y) * (in1.Y - in2.Y)) + ((in1.Z - in2.Z) * (in1.Z - in2.Z))));
}
public void Decimation(double ddrp) throws IOException {
int reduceN;
int i;
reduceN = ((int) ((double) ((ddrp / 100.0) * ((double) (numberV)))));
if (numberV - reduceN <= 3)
reduceN = numberV - 4;
numberVOrig = numberV;
numberFOrig = numberF;
// System.out.println("Reduction Ratio: " + ddrp + " %");
// System.out.println("May be V:" + numberV + " -> " + (numberV - reduceN));
/* Make Intermediate Data structure and priority box */
mydecimate = new LODMesh(numberV, numberF, FaceArray, point, boundary);
mydecimate.Decimation((numberV - reduceN));
/* Update Data Structure */
subpoint = new Vector3f[mydecimate.deciV];
subFace = new int[mydecimate.deciF][3];
// System.out.println("mydecimate.deciF = " + mydecimate.deciF);
// System.out.println("mydecimate.deciV = " + mydecimate.deciV);
int[] dddindex = new int[mydecimate.deciV];
for (i = 0; i < mydecimate.deciV; i++)
dddindex[i] = 0;
mydecimate.getVFace(subpoint, subFace, dddindex);
numberV = mydecimate.deciV;
numberF = mydecimate.deciF;
numberE = numberV + numberF - EulerC;
// System.out.println("");
// System.out.println("New V:" + numberV + " F:" + numberF);
UpdatePolyStructure();
for (i = 0; i < numberV; i++)
index[i] = dddindex[i];
PropertyUpdate();
dddindex = null;
UpdatePolygon();
UpdatePolyStructureToOrig();
}
public int getFaceQuatityOrig() {
return numberFOrig;
}
public int getFaceQuatity() {
return numberF;
}
public VertexBuffer getDecimatedVBuffer() {
VertexBuffer pkVBuffer;
Attributes kAttr = new Attributes();
kAttr.SetPChannels(3);
kAttr.SetNChannels(3);
kAttr.SetTChannels(0, 3);
kAttr.SetCChannels(0, 4);
pkVBuffer = new VertexBuffer(kAttr, mydecimate.deciV);
for (int i = 0; i < mydecimate.deciV; i++) {
pkVBuffer.SetPosition3(i, (float) subpoint[i].X,
(float) subpoint[i].Y, (float) subpoint[i].Z);
pkVBuffer.SetColor4(0, i, 1.0f, 1.0f, 1.0f, 1.0f);
}
return pkVBuffer;
}
public IndexBuffer getDecimatedIBuffer() {
IndexBuffer pkIBuffer;
int[] aiIndex = new int[mydecimate.deciF * 3];
for (int i = 0; i < mydecimate.deciF; i++) {
aiIndex[3 * i] = subFace[i][0];
aiIndex[3 * i + 1] = subFace[i][1];
aiIndex[3 * i + 2] = subFace[i][2];
}
pkIBuffer = new IndexBuffer(mydecimate.deciF * 3, aiIndex);
return pkIBuffer;
}
public Vector3f[] getDecimatedPoints() {
return subpoint;
}
public int[][] getDecimatedFace() {
return subFace;
}
public int getFace(int i, int j, int fi) {
IDList now = FHead[i];
int tID = -1;
while (next(now) != FTail[i]) {
now = next(now);
if (now.ID != fi) {
if ((FaceArray[now.ID][0] == i && FaceArray[now.ID][1] == j)
|| (FaceArray[now.ID][1] == i && FaceArray[now.ID][0] == j)
|| (FaceArray[now.ID][0] == i && FaceArray[now.ID][2] == j)
|| (FaceArray[now.ID][2] == i && FaceArray[now.ID][0] == j)
|| (FaceArray[now.ID][2] == i && FaceArray[now.ID][1] == j)
|| (FaceArray[now.ID][1] == i && FaceArray[now.ID][2] == j)) {
tID = now.ID;
break;
}
}
}
return tID;
}
}
|
package inf1010.assignment;
public class Subject {
private String courseCode;
Group group; //ifiCollection<Group>
Teacher lecturer;
Subject(String courseCode) {
this.courseCode = courseCode;
}
public int compareTo(Subject s) {
return s.getCourseCode().compareTo(courseCode);
}
public boolean enrollStudent(Student s, int group) {
return false;
}
public Teacher getLecturer() {
return null;
}
public int getStudentBodySize() {
return 0;
}
public Student[] getStudents() {
return null;
}
public Teacher[] getTeachers() {
return null;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
}
|
package com.winter.database;
import com.winter.model.User;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
public interface UserRepository extends PanacheRepository<User> {
User save(User user);
User findByLogin(String login);
}
|
package com.app.AdminUI.ControlsUI;
import com.app.DBConnection;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateScreen extends JFrame {
String ID;
private JPanel updatePanel;
private JTextField IDTextField;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JTextField textField4;
private JTextField textField5;
private JTextField textField6;
private JTextField textField7;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JLabel label7;
private JButton updateButton;
private JButton goButton;
public UpdateScreen(int choice) {
add(updatePanel);
setSize(400, 800);
setTitle("Music App / Admin UPDATE Data");
goButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ID = IDTextField.getText();
setScreen(choice);
}
});
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateRecord(choice, ID);
}
});
}
public void setScreen(int choice) {
if (choice == 1) {
label1.setText("Album ID: ");
label2.setText("Genre ID: ");
label3.setText("Artist ID: ");
label4.setText("Name: ");
label5.setText("Release Date: ");
label6.setText("Length: ");
label7.setText("Play Count: ");
textField1.setEnabled(true);
textField2.setEnabled(true);
textField3.setEnabled(true);
textField4.setEnabled(true);
textField5.setEnabled(true);
textField6.setEnabled(true);
textField7.setEnabled(true);
} else if (choice == 2) {
label1.setText("Name: ");
label2.setText("Country: ");
textField1.setEnabled(true);
textField2.setEnabled(true);
} else if (choice == 3) {
label1.setText("Genre ID: ");
label2.setText("Artist ID: ");
label3.setText("Name: ");
label4.setText("Release Date: ");
textField1.setEnabled(true);
textField2.setEnabled(true);
textField3.setEnabled(true);
textField4.setEnabled(true);
}
}
public void updateRecord(int choice, String ID) {
int Id = Integer.parseInt(ID);
try {
Connection connection = DBConnection.getConnection();
String sqlQuery = null;
if (choice == 1) {
String album = textField1.getText();
String genre = textField2.getText();
String artist = textField3.getText();
String name = textField4.getText();
String releaseDate = textField5.getText();
String length = textField6.getText();
String plays = textField7.getText();
sqlQuery = "UPDATE songs " +
"SET album_id = " + "'" + album + "'," +
"genre_id = " + "'" + genre + "'," +
"artist_song_id = " + "'" + artist + "'," +
"name = " + "'" + name + "'," +
"release_date = " + "'" + releaseDate + "'," +
"lenght = " + "'" + length + "'," +
"plays = " + "'" + plays + "'" +
"WHERE id =" + "'" + Id + "'";
PreparedStatement songStatement = connection.prepareStatement(sqlQuery);
int resultSet = songStatement.executeUpdate();
} else if (choice == 2) {
String name = textField1.getText();
String country = textField2.getText();
sqlQuery = "UPDATE artists " +
"SET name = " + "'" + name + "'," +
"country = " + "'" + country + "'" +
"WHERE id =" + "'" + Id + "'";
PreparedStatement artistStatement = connection.prepareStatement(sqlQuery);
int resultSet = artistStatement.executeUpdate();
} else if (choice == 3) {
String genre = textField1.getText();
String artist = textField2.getText();
String name = textField3.getText();
String releaseDate = textField4.getText();
sqlQuery = "UPDATE albums " +
"SET genre_id = " + "'" + genre + "'," +
"artist_song_id = " + "'" + artist + "'," +
"name = " + "'" + name + "'," +
"release_date = " + "'" + releaseDate + "'" +
"WHERE id =" + "'" + Id + "'";
PreparedStatement albumStatement = connection.prepareStatement(sqlQuery);
int resultSet = albumStatement.executeUpdate();
}
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
|
import java.util.Scanner;
public class CommonElements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
String input2 = scanner.nextLine();
String[] input1ToArray = input1.split("\\s+");
String[] input2ToArray = input2.split("\\s+");
String[] commonElements = new String[input2ToArray.length];
int counter = 0;
for (int i = 0; i < input2ToArray.length; i++) {
for (int j = 0; j < input1ToArray.length; j++) {
if (input2ToArray[i].equals(input1ToArray[j])){
commonElements[counter] = input2ToArray[i];
counter++;
}
}
}
//This is second solution by making new array.
//The original and required solution is by just printing the equal number
for (String common :
commonElements) {
if (common != null)
System.out.print(common + " ");
}
}
}
|
package analytics.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class AprioriHelper {
public static int[] getDataRow(List<Integer> products, List<Integer> codes) {
int[] row = new int[codes.size()];
Integer[] sortedProducts = new Integer[products.size()];
products.toArray(sortedProducts);
int currentProductIndex = 0,
maxProductIndex = sortedProducts.length - 1,
index = -1;
Arrays.sort(sortedProducts);
for(int code : codes) {
index ++;
if(currentProductIndex > maxProductIndex) {
break;
}
if(code == (Integer)sortedProducts[currentProductIndex]) {
row[index] = 1;
currentProductIndex++;
}
}
return row;
}
public static List<String> getAllFilteredCombinations (int totalColumns, int max, List<String> undesiredCombinations) {
List<String> allCombinations = new ArrayList<String>();
for(int i = 0; i < totalColumns - max + 1; i++) {
List<String> combinations = AprioriHelper.getFilteredRecursiveCombinations(i, totalColumns - 1, max, undesiredCombinations);
for(String combination : combinations) {
allCombinations.add(combination);
}
}
return allCombinations;
}
private static boolean listContainsToken(List<String> elements, String tokens) {
for(String element : elements) {
if(element.contains(tokens))
return true;
}
return false;
}
private static List<String> getFilteredRecursiveCombinations(int minIndex, int maxIndex,
int remainedLength, List<String> undesiredCombinations) {
List<String> combinations = new ArrayList<String>();
if(undesiredCombinations.contains(((Integer)minIndex).toString()) ||
remainedLength == 0)
return combinations;
remainedLength--;
String partialCombinationPrefix = minIndex + (remainedLength > 0 ? "," : "");
if(remainedLength == 0)
combinations.add(partialCombinationPrefix);
int nextRecursiveMinIndex = minIndex + 1;
while(undesiredCombinations.contains(((Integer)nextRecursiveMinIndex).toString()) ||
AprioriHelper.listContainsToken(undesiredCombinations, String.format("%s,%s", minIndex, nextRecursiveMinIndex)))
nextRecursiveMinIndex++;
while(nextRecursiveMinIndex <= maxIndex && remainedLength > 0) {
List<String> unprefixed = AprioriHelper.getFilteredRecursiveCombinations(nextRecursiveMinIndex,
maxIndex, remainedLength, undesiredCombinations);
for(String partialCombinationUnprefixed : unprefixed) {
combinations.add(partialCombinationPrefix + partialCombinationUnprefixed);
}
nextRecursiveMinIndex++;
while(undesiredCombinations.contains(((Integer)(nextRecursiveMinIndex)).toString()) ||
AprioriHelper.listContainsToken(undesiredCombinations, String.format("%s,%s", minIndex, nextRecursiveMinIndex)))
nextRecursiveMinIndex++;
}
return combinations;
}
public static List<String> getAllCustomCombinations(int totalColumns,
int max, List<Integer> customColumns, List<String> zeroSupp) {
List<String> allCombinations = new ArrayList<String>();
for(int i = 0; i < totalColumns - max + 1; i++) {
if(customColumns.contains(i))
continue;
List<String> combinations = AprioriHelper.getRecursiveCustomCombinations(
i, totalColumns - 1, max, customColumns, zeroSupp);
for(String combination : combinations) {
allCombinations.add(combination);
}
}
return allCombinations;
}
private static List<String> getRecursiveCustomCombinations(int minIndex, int maxIndex,
int remainedLength, List<Integer> customColumns, List<String> zeroSupp) {
List<String> combinations = new ArrayList<String>();
if(remainedLength == 0 ||
zeroSupp.contains(((Integer)minIndex).toString()))
return combinations;
remainedLength--;
String partialCombinationPrefix = minIndex + (remainedLength > 0 ? "," : "");
if(remainedLength == 0)
combinations.add(partialCombinationPrefix);
int nextRecursiveMinIndex = minIndex + 1;
while(zeroSupp.contains(((Integer)nextRecursiveMinIndex).toString()) ||
AprioriHelper.listContainsToken(zeroSupp, String.format("%s,%s", minIndex, nextRecursiveMinIndex)))
nextRecursiveMinIndex++;
while(nextRecursiveMinIndex <= maxIndex && remainedLength > 0) {
if(!customColumns.contains(nextRecursiveMinIndex)){
List<String> unprefixed = AprioriHelper.getRecursiveCustomCombinations(nextRecursiveMinIndex,
maxIndex, remainedLength, customColumns, zeroSupp);
for(String partialCombinationUnprefixed : unprefixed) {
combinations.add(partialCombinationPrefix + partialCombinationUnprefixed);
}
}
nextRecursiveMinIndex++;
while(zeroSupp.contains(((Integer)(nextRecursiveMinIndex)).toString()) ||
AprioriHelper.listContainsToken(zeroSupp, String.format("%s,%s", minIndex, nextRecursiveMinIndex)))
nextRecursiveMinIndex++;
}
return combinations;
}
public static List<String> removeColumnsCombination(List<String> oldList, String combination, List<String> belowSupp) {
List<String> newList = new ArrayList<String>();
for(String comb : oldList) {
if(!DataChanges.containsTokens(comb, combination))
newList.add(comb);
else
belowSupp.add(comb);
}
return newList;
}
public static double getColumnsSupport(int[][] data, int[] columns) {
double sum = 0;
short count = 0;
for(int i = 0; i < data.length; i++) {
count = 1;
for(int j = 0; j < columns.length; j++) {
if (data[i][columns[j]] != 1) {
count = 0;
break;
}
}
sum += count;
}
return sum / data.length;
}
public static double getColumnsSupport(int[][] data, List<Integer> columns) {
double sum = 0;
short count = 0;
for(int i = 0; i < data.length; i++) {
count = 1;
for(int j = 0; j < columns.size(); j++) {
if (data[i][columns.get(j).intValue()] != 1) {
count = 0;
break;
}
}
sum += count;
}
return sum / data.length;
}
public static List<String> filterBelowSuppColumns (List<String> combinations, List<String> belowSuppCombinations) {
List<String> filteredCols = new ArrayList<String> ();
for(String combination : combinations) {
if(!isContained(combination, belowSuppCombinations)) {
filteredCols.add(combination);
}
}
return filteredCols;
}
private static boolean isContained(String target, List<String> source) {
boolean isContained = false;
for(String belowSupp : source) {
if(DataChanges.containsTokens(target, belowSupp)) {
isContained = true;
break;
}
}
return isContained;
}
public static Integer[] getCodesAtIndexes(Integer[] indexes, List<Integer> codes) {
Integer[] filteredCodes = new Integer[indexes.length];
List<Integer> filteredCodesList = new ArrayList<Integer>();
for(Integer index : indexes) {
filteredCodesList.add(codes.get(index));
}
filteredCodesList.toArray(filteredCodes);
return filteredCodes;
}
public static double getSupportForProducts (List<String> selectedProducts,
HashMap<Integer, String> products, List<Integer> sortedCodes, int[][] allData) {
int columns[] = new int[selectedProducts.size()],
cols = 0;
for(String product : selectedProducts) {
if(!products.containsValue(product))
continue;
Integer key = DataChanges.getKeyForValue(products, product);
if(key != null && sortedCodes.contains(key)) {
int index = sortedCodes.indexOf(key);
if(index > -1 && index < allData[0].length) {
columns[cols++] = index;
}
}
}
return AprioriHelper.getColumnsSupport(allData, columns);
}
public static double getConfidenceWithNames(List<String> baseProducts, List<String> determinedProducts,
HashMap<Integer, String> products, List<Integer> sortedCodes, int[][] allData) {
double baseSupp = AprioriHelper.getSupportForProducts(baseProducts, products, sortedCodes, allData);
List<String> allProducts = new ArrayList<String>(baseProducts);
allProducts.addAll(determinedProducts);
double allSupp = AprioriHelper.getSupportForProducts(allProducts, products, sortedCodes, allData);
return baseSupp > 0.0 ? (allSupp / baseSupp) : 0;
}
public static double getConfidenceWithIndexes(List<Integer> baseProductsIndexes,
List<Integer> determinedProductsIndexes, int[][] allData) {
List<Integer> allProds = new ArrayList<Integer>();
allProds.addAll(baseProductsIndexes);
allProds.addAll(determinedProductsIndexes);
double allProdsSupport = AprioriHelper.getColumnsSupport(allData, allProds);
double baseProdsSupport = AprioriHelper.getColumnsSupport(allData, baseProductsIndexes);
return baseProdsSupport > 0.0 ? (allProdsSupport / baseProdsSupport) : 0;
}
public static void displaySupportResults(List<List<String>> results, Double support) {
if(results.isEmpty()) {
System.out.println("The support is too big and there are no products combinations for it!");
System.out.println("Please decrease it and run again.");
return;
}
System.out.println("RESULTS");
System.out.println("=======");
System.out.println();
System.out.println("***The following products combinations have a support grater than or equal to " + support);
System.out.println();
for(List<String> products : results) {
System.out.println();
System.out.println(" Products");
System.out.println(" --------");
for(int i = 0; i < products.size() - 1; i ++) {
System.out.println(" >>>" + products.get(i));
}
System.out.println(" ==>Support: " + products.get(products.size() - 1));
}
}
public static void displayConfidenceResults(List<List<String>> results, List<String> baseProds, Double confidence) {
if(results.isEmpty()) {
System.out.println("The confidence is too big and there are no determined products for it!");
System.out.println("Please decrease it and run again.");
return;
}
System.out.println("RESULTS");
System.out.println("=======");
System.out.println();
System.out.println("***The following products determination have a confidence grater than or equal to " + confidence);
System.out.println();
for(List<String> determined : results) {
for(String baseProd : baseProds) {
System.out.println();
System.out.println(" Products");
System.out.println(" --------");
System.out.println(" ###" + baseProd);
}
System.out.println(" Determined");
System.out.println(" ----------");
for(int i = 0; i < determined.size() - 1; i ++) {
System.out.println(" >>>" + determined.get(i));
}
System.out.println(" ==>Confidence: " + determined.get(determined.size() - 1));
}
}
public static List<Integer> getCodesForProducts(HashMap<Integer, String> products, List<String> names) {
List<Integer> codes = new ArrayList<Integer>();
int found = 0,
size = products.size();
for(Integer key : products.keySet()) {
if(names.contains(products.get(key))) {
codes.add(key);
if(++found == size) {
break;
}
}
}
return codes;
}
public static List<Integer> getIndexForCodes(List<Integer> codes, List<Integer> allSortedCodes) {
List<Integer> indexes = new ArrayList<Integer>();
for(Integer code : codes) {
indexes.add(allSortedCodes.indexOf(code));
}
return indexes;
}
}
|
package exercise4;
import exercise3.Calculator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class AnnotationAnalyzer implements Calculator {
private Calculator calculator = null;
private Map<Integer, Integer> map = new HashMap<>();
public AnnotationAnalyzer(Calculator calculator) {
this.calculator = calculator;
}
@Override
public int calculate(int value) throws InvocationTargetException, IllegalAccessException {
Class <?> clazz = calculator.getClass();
Integer result = 0;
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(MyCachedMethod.class)) {
if (map.containsKey(value)) {
result = map.get(value);
System.out.println("from cached (" + value + ")");
} else {
result = (Integer) method.invoke(calculator, value);
map.put((Integer) value, result);
System.out.println("calculate (" + value + ")");
}
}
}
return result;
}
}
|
package br.com.LoginSpringBootThymeleaf.controllers;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.LoginSpringBootThymeleaf.dto.Permissoes.PermissaoDTO;
import br.com.LoginSpringBootThymeleaf.services.Permissoes.PermissoesService;
@Controller
public class PermissoesController {
@Autowired
private PermissoesService permissoesService;
@GetMapping(value="/permissoes")
public ModelAndView consultarPermissoes(Model model) {
List<PermissaoDTO> permissoes = permissoesService.getAllPermissao();
model.addAttribute("PermissaoDTO", permissoes);
return new ModelAndView("permissao/ListagemPermissao");
}
@GetMapping(value="/permissoes/cadastro")
public ModelAndView cadastroPermissoes(Model model) {
model.addAttribute("permissaoDTO", new PermissaoDTO());
return new ModelAndView("permissao/CadastroPermissao");
}
@PostMapping(value="/permissoes/salvarPermissoes")
public ModelAndView salvarPermissoes(@ModelAttribute @Valid PermissaoDTO permissaoDTO, final BindingResult result, Model model, RedirectAttributes redirectAttributes) {
if(!result.hasErrors()){
permissoesService.savePermissao(permissaoDTO);
redirectAttributes.addFlashAttribute("msg_resultado", "Registro salvo com sucesso!");
return new ModelAndView("redirect:/permissoes");
}
model.addAttribute("permissaoDTO", permissaoDTO);
return new ModelAndView("permissao/CadastroPermissao");
}
@PostMapping(value="/permissoes/excluir/{codigoPermissao}")
public ModelAndView excluir(@PathVariable("codigoPermissao") Integer codigoUsuario){
permissoesService.delete(codigoUsuario);
return new ModelAndView("redirect:/permissoes");
}
@GetMapping(value="/permissoes/editar/{codigoPermissao}")
public ModelAndView getViewUpdatePermissao(@PathVariable("codigoPermissao") Integer codigoUsuario, Model model) {
PermissaoDTO permissaoDTO = permissoesService.getPermissaoById(codigoUsuario);
model.addAttribute("PermissaoDTO", permissaoDTO);
return new ModelAndView("permissao/UpdatePermissao");
}
@PostMapping(value="/permissoes/saveUpdatePermissoes")
public ModelAndView saveUpdatePermissoes(@ModelAttribute @Valid PermissaoDTO permissaoDTO) {
permissoesService.updatePermissao(permissaoDTO);
return new ModelAndView("redirect:/permissoes");
}
}
|
package Tests.TestNGTests.LoginTests;
import Tests.TestNGTests.BaseCLass;
import org.testng.annotations.Test;
import static Utils.ConfigReader.URL;
public class PasswordTests extends BaseCLass {
@Test
public void passwordLessMin(){
driver.get(URL + "#/login");
}
@Test
public void passwordMinLength(){
driver.get(URL + "#/login");
}
@Test
public void passwordMaxLength(){
driver.get(URL + "#/login");
}
@Test
public void passwordMoreMax(){
driver.get(URL + "#/login");
}
@Test
public void passwordCharsetTest(){
driver.get(URL + "#/login");
}
@Test
public void passwordNull(){
driver.get(URL + "#/login");
}
@Test
public void passwordUsernameRegistered(){
driver.get(URL + "#/login");
}
}
|
package symap.mapper;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.event.MouseEvent;
import java.awt.Color;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import symap.marker.MarkerTrack;
import symap.sequence.Annotation;
import symap.sequence.Sequence;
import symap.SyMAPConstants;
//public class FPCPseudoHits extends AbstractFPCPseudoHits implements Hits, SyMAPConstants { // mdb removed 7/25/07 #134
public class FPCPseudoHits extends AbstractHitData implements Hits, SyMAPConstants { // mdb added 7/25/07 #134
//private static final boolean METHOD_TRACE = false; // mdb added 2/27/07
private static final int MOUSE_PADDING = 3; // mdb added 3/1/07 #100
private Mapper mapper;
private MarkerTrack mt;
private Sequence st;
private PseudoMarkerHit[] markerHits;
private PseudoBESHit[] besHits;
public FPCPseudoHits(int project1, int contig, int project2, int group) {
super(project1,contig,project2,group,Mapper.FPC2PSEUDO,false);
}
public FPCPseudoHits(Mapper mapper, MarkerTrack mt, Sequence st, FPCPseudoData data) {
this(data.getProject1(),data.getContig(),data.getProject2(),data.getGroup());
this.mapper = mapper;
this.mt = mt;
this.st = st;
setHits(data);
}
public FPCPseudoData.PseudoMarkerData[] getPseudoMarkerHitData() {
FPCPseudoData.PseudoMarkerData[] mhd = new FPCPseudoData.PseudoMarkerData[markerHits == null ? 0 : markerHits.length];
for (int i = 0; i < mhd.length; i++) mhd[i] = markerHits[i].data;
return mhd;
}
public FPCPseudoData.PseudoBESData[] getPseudoBESHitData() {
FPCPseudoData.PseudoBESData[] bhd = new FPCPseudoData.PseudoBESData[besHits == null ? 0 : besHits.length];
for (int i = 0; i < bhd.length; i++) bhd[i] = besHits[i].data;
return bhd;
}
public boolean setHits(FPCPseudoData data) {
if (upgradeHitContent(data.getHitContent())) {
FPCPseudoData.PseudoMarkerData[] mhd = data.getPseudoMarkerData();
FPCPseudoData.PseudoBESData[] bhd = data.getPseudoBESData();
markerHits = new PseudoMarkerHit[data == null || mhd == null ? 0 : mhd.length];
for (int i = 0; i < markerHits.length; i++) {
markerHits[i] = new PseudoMarkerHit(mhd[i]);
markerHits[i].set();
}
besHits = new PseudoBESHit[data == null || bhd == null ? 0 : bhd.length];
for (int i = 0; i < besHits.length; i++) {
besHits[i] = new PseudoBESHit(bhd[i]);
besHits[i].set();
}
return true;
}
return false;
}
public boolean addHits(int newHitContent, Collection markerData, Collection besData) {
if (upgradeHitContent(newHitContent)) {
if (markerHits == null) markerHits = new PseudoMarkerHit[0];
if (besHits == null) besHits = new PseudoBESHit[0];
if (markerData == null) markerData = new LinkedList();
if (besData == null) besData = new LinkedList();
PseudoMarkerHit tmh[] = new PseudoMarkerHit[markerHits.length+markerData.size()];
System.arraycopy(markerHits,0,tmh,0,markerHits.length);
int i = markerHits.length;
markerHits = tmh;
for (Iterator iter = markerData.iterator(); i < markerHits.length; i++) {
markerHits[i] = new PseudoMarkerHit((FPCPseudoData.PseudoMarkerData)iter.next());
markerHits[i].set();
}
PseudoBESHit tbh[] = new PseudoBESHit[besHits.length+besData.size()];
System.arraycopy(besHits,0,tbh,0,besHits.length);
i = besHits.length;
besHits = tbh;
for (Iterator iter = besData.iterator(); i < besHits.length; i++) {
besHits[i] = new PseudoBESHit((FPCPseudoData.PseudoBESData)iter.next());
besHits[i].set();
}
return true;
}
return false;
}
public void clear() {
for (int i = 0; i < markerHits.length; i++) markerHits[i].clear();
for (int i = 0; i < besHits.length; i++) besHits[i].clear();
}
public void set(MarkerTrack mt, Sequence st) {
this.st = st;
this.mt = mt;
for (int i = 0; i < markerHits.length; i++) markerHits[i].set();
for (int i = 0; i < besHits.length; i++) besHits[i].set();
}
public void setMinMax(HitFilter hf) {
for (int i = 0; i < markerHits.length; i++) markerHits[i].setMinMax(hf);
for (int i = 0; i < besHits.length; i++) besHits[i].setMinMax(hf);
}
public void getSequenceMinMax(int[] minMax) {
for (int i = 0; i < markerHits.length; i++)
markerHits[i].getSequenceMinMax(minMax);
for (int i = 0; i < besHits.length; i++)
besHits[i].getSequenceMinMax(minMax);
}
/**
* Method <code>getHitData</code> adds an FPCPseudoData object to
* hits containing all the marker hit data and bes hit data for the
* hits that are visible, not filtered, and fall in the range of start and
* end. If no hits exist than an FPCPseudoData object is not added.
*
* @param hits a <code>List</code> value
* @param start an <code>int</code> value
* @param end an <code>int</code> value
*/
public void getHitsInRange(List<AbstractHitData> hits, int start, int end,
boolean swap) // mdb added swap 12/19/08 - for pseudo-pseudo, unused here
{
List<AbstractHitData> mh = new LinkedList<AbstractHitData>();
List<AbstractHitData> bh = new LinkedList<AbstractHitData>();
for (int i = 0; i < markerHits.length; i++)
markerHits[i].addHit(mh,start,end);
for (int i = 0; i < besHits.length; i++)
besHits[i].addHit(bh,start,end);
if (!mh.isEmpty() || !bh.isEmpty())
hits.add(new FPCPseudoData(getProject1(),getContig(),getProject2(),getGroup(),getHitContent(),mh,bh));
}
public void paintComponent(Graphics2D g2) {
int i;
Point mtLocation = mt.getLocation();
Point stLocation = st.getLocation();
int mtOrient = mapper.getOrientation(mt);
int stOrient = mapper.getOrientation(st);
List<PseudoMarkerHit> hMrkHits = new LinkedList<PseudoMarkerHit>();
List<PseudoBESHit> hBesHits = new LinkedList<PseudoBESHit>();
boolean showJoinDot = mapper.getHitFilter().getShowJoinDot();
for (i = 0; i < markerHits.length; i++) {
if (markerHits[i].isHighlighted()) hMrkHits.add(markerHits[i]);
else markerHits[i].paintComponent(g2,mtOrient,stOrient,mtLocation,stLocation,showJoinDot);
}
for (i = 0; i < besHits.length; i++) {
if (besHits[i].isHighlighted()) hBesHits.add(besHits[i]);
else besHits[i].paintComponent(g2,mtOrient,stOrient,mtLocation,stLocation);
}
for (PseudoMarkerHit h : hMrkHits)
h.paintComponent(g2,mtOrient,stOrient,mtLocation,stLocation,showJoinDot);
for (PseudoBESHit h : hBesHits)
h.paintComponent(g2,mtOrient,stOrient,mtLocation,stLocation);
}
public void mouseMoved(MouseEvent e) {
for (int i = 0; i < markerHits.length; i++)
markerHits[i].mouseMoved(e);
for (int i = 0; i < besHits.length; i++)
besHits[i].mouseMoved(e);
}
public void mouseExited(MouseEvent e) {
// Need to do this otherwise hits will stay highlighted when exited.
for (int i = 0; i < markerHits.length; i++)
markerHits[i].setHover(false);
for (int i = 0; i < besHits.length; i++)
besHits[i].setHover(false);
mapper.getDrawingPanel().repaint();
}
private class PseudoMarkerHit implements Hit {
private FPCPseudoData.PseudoMarkerData data;
private MarkerHit mh;
private Line2D.Double hitLine;
private boolean hover;
private boolean geneContained;
private boolean geneOverlap;
public PseudoMarkerHit(FPCPseudoData.PseudoMarkerData data) {
this.data = data;
mh = new MarkerHit();
hitLine = new Line2D.Double();
hover = false;
geneOverlap = (data.getOverlap() > 0);
}
public void addHit(List hits, int start, int end) {
if ( ( (data.getStart2() >= start && data.getStart2() <= end) ||
(data.getEnd2() >= start && data.getEnd2() <= end) ||
(start >= data.getStart2() && end <= data.getEnd2()) ) &&
isVisible() && !isFiltered() ) {
hits.add(data);
}
}
public void setMinMax(HitFilter hf) {
hf.condSetMrkEvalue(data.getEvalue(),data.getEvalue());
hf.condSetMrkPctid(data.getPctid(),data.getPctid());
}
public String getType() {
return MRK_TYPE;
}
public void set() {
mh.set(this,mt,data.getName(),getContig());
geneContained = isGeneContained(); // mdb added 3/9/07 #101
geneOverlap = isGeneOverlap(); // mdb added 3/9/07 #101
}
public boolean isBlockHit() {
return data.isBlockHit();
}
public boolean isGeneContained() {
return (data.getOverlap() > 0); // WN we don't make this distinction anymore
}
public boolean isGeneOverlap() {
return (data.getOverlap() > 0);
}
public boolean isFiltered() {
HitFilter hitfilter = mapper.getHitFilter();
return (hitfilter.getBlock() && !data.isBlockHit())
|| (hitfilter.getNonRepetitive() && data.isRepetitiveHit()
&& !data.isBlockHit()) || hitfilter.getMrkHide()
|| hitfilter.getMrkEvalue() < data.getEvalue()
|| hitfilter.getMrkPctid() > data.getPctid()
|| mh.isFiltered(mt, hitfilter.getOnlyShared())
|| isSequenceFiltered(data.getStart2(), data.getEnd2())
|| (hitfilter.getGeneContained() && !geneContained) // mdb added 3/9/07 #101
|| (hitfilter.getGeneOverlap() && !geneOverlap) // mdb added 3/9/07 #101
|| (hitfilter.getNonGene() && (geneOverlap || geneContained)); // mdb added 3/9/07 #101
}
public boolean isHighlighted() {
return mh.isHighlighted() || hover;
}
public boolean isVisible() {
return mh.isVisible(mt)
&& isSequenceVisible(data.getStart2(), data.getEnd2());
}
private boolean lineContains(Line2D.Double line, Point p) { // mdb added 3/1/07 #100
double lx1 = line.getX1();
double lx2 = line.getX2();
double ly1 = line.getY1();
double ly2 = line.getY2();
double delta;
delta = p.getY() - ly1 - ((ly2-ly1)/(lx2-lx1))*(p.getX()-lx1);
return (delta >= -MOUSE_PADDING && delta <= MOUSE_PADDING);
}
public boolean isHover(Point point) { // mdb added 3/1/07 #100
return isVisible() && lineContains(hitLine, point);
}
protected boolean setHover(Point point) { // mdb added 3/1/07 #100
return setHover(isHover(point));
}
protected boolean setHover(boolean hover) { // mdb added 3/1/07 #100
if (hover != this.hover) {
this.hover = hover;
return true;
}
return false;
}
public void getSequenceMinMax(int[] minMax) {
if (isVisible() && !isFiltered()) {
FPCPseudoHits.getSequenceMinMax(minMax, data.getStart2(), data
.getEnd2());
}
}
private Color getCColor() { // mdb added 3/1/07 #100
if (mh.isHighlighted() || isHighlighted())
return Mapper.markerLineHighlightColor;
if (mapper.getHitFilter().getColorByStrand())
return data.getOrientation() ? Mapper.posOrientLineColor : Mapper.negOrientLineColor;
return Mapper.markerLineColor;
}
// mdb added 8/22/07 #126
private void drawHitRibbon(Graphics2D g2, Point2D pStart, Point2D pEnd, int orient) {
String target_seq = data.getTargetSeq();
Rectangle2D.Double rect = new Rectangle2D.Double();
if (target_seq == null || target_seq.equals("")) {
g2.draw(new Line2D.Double(pStart,pEnd));
}
else {
g2.setPaint(Mapper.hitRibbonBackgroundColor);
rect.setRect(pStart.getX(),pStart.getY(),Mapper.hitRibbonWidth,pEnd.getY()-pStart.getY());
g2.fill(rect);
g2.draw(rect);
g2.setPaint(getCColor());
String[] subseq = target_seq.split(",");
for (int i = 0; i < subseq.length; i++) {
String[] pos = subseq[i].split(":");
long start = Long.parseLong(pos[0]);
long end = Long.parseLong(pos[1]);
Point2D p1 = st.getPoint(start, orient);
p1.setLocation(pStart.getX(),p1.getY());
Point2D p2 = st.getPoint(end, orient);
p2.setLocation(pStart.getX(),p2.getY());
rect.setRect(p1.getX(),p1.getY(),Mapper.hitRibbonWidth,p2.getY()-p1.getY());
g2.fill(rect);
g2.draw(rect);
}
}
}
public void paintComponent(Graphics2D g2, int mtOrient, int stOrient, Point mtLocation, Point stLocation, boolean showJoinDot) {
if (isVisible() && !isFiltered()) {
Point2D sp = getSequenceCPoint(data.getStart2(),data.getEnd2(),stOrient,stLocation);
Point2D mp = mh.getCPoint(mt,mtOrient,mtLocation,showJoinDot);
mh.paintComponent(g2,mt,mtLocation,sp,showJoinDot,mapper.getHitFilter().getColorByStrand(),data.getOrientation());
if (mp != null) {
//g2.setPaint(mh.getCColor(mapper.getHitFilter().getColorByStrand(),data.getOrientation())); // mdb removed 3/1/07 #100
g2.setPaint(getCColor()); // mdb added 3/1/07 #100
hitLine.setLine(sp,mp); // mdb added 3/1/07 #100
g2.draw(hitLine);
}
double lineLength = 0;
if (st.getShowScoreLine()) { // mdb added 2/28/07 #100
double pctid = data.getPctid();
double minPctid = Math.min(mapper.getHitFilter().getMinBesPctid(),
mapper.getHitFilter().getMinMrkPctid());
double x=sp.getX(), y=sp.getY();
lineLength = 30.0*(pctid-minPctid+1)/(100-minPctid+1);
if (mp != null && mp.getX() > x) lineLength = 0 - lineLength;
g2.setPaint(getCColor()/*mh.getCColor(mapper.getHitFilter().getColorByStrand(),data.getOrientation())*/); // mdb changed 3/1/07 #100
g2.draw(new Line2D.Double(x,y,x+lineLength,y));
}
if (st.getShowRibbon()) { // mdb added 8/7/07 #126
if (lineLength == 0) lineLength = 30;
Point2D rp1 = st.getPoint(data.getStart2(), stOrient);
rp1.setLocation(sp.getX()+lineLength,rp1.getY());
Point2D rp2 = st.getPoint(data.getEnd2(), stOrient);
rp2.setLocation(sp.getX()+lineLength,rp2.getY());
if (Math.abs(rp2.getY()-rp1.getY()) > 3) // only draw if it will be visible
drawHitRibbon(g2, rp1, rp2, stOrient);
}
if (st.getShowScoreValue() || isHighlighted()) { // mdb added 3/14/07 #100
double pctid = data.getPctid();
double textX;
textX = sp.getX();
if (mp != null && mp.getX() > sp.getX()) textX += lineLength-14-(pctid==100 ? -7 : 0);
else textX += lineLength;
g2.setPaint(Color.black);
g2.drawString(""+(int)pctid, (int)textX, (int)sp.getY());
}
}
}
public void clear() {
mh.clear(this);
}
public void mouseMoved(MouseEvent e) {
if (mh.isVisible(mt)) mh.mouseMoved(e);
if (setHover(e.getPoint()))
mapper.getDrawingPanel().repaint();
}
}
private class PseudoBESHit implements CloneHit {
private FPCPseudoData.PseudoBESData data;
private BESHit bh;
private Line2D.Double hitLine;
private boolean hover;
private boolean geneContained;
private boolean geneOverlap;
public PseudoBESHit(FPCPseudoData.PseudoBESData data) {
this.data = data;
bh = new BESHit();
hitLine = new Line2D.Double();
hover = false;
geneOverlap = (data.getOverlap() > 0);
}
public void addHit(List hits, int start, int end) {
if ( ( (data.getStart2() >= start && data.getStart2() <= end) ||
(data.getEnd2() >= start && data.getEnd2() <= end) ||
(start >= data.getStart2() && end <= data.getEnd2()) ) &&
isVisible() && !isFiltered() )
{
hits.add(data);
}
}
public int getPos2() {
return data.getPos2();
}
public void setMinMax(HitFilter hf) {
hf.condSetBesEvalue(data.getEvalue(),data.getEvalue());
hf.condSetBesPctid(data.getPctid(),data.getPctid());
}
public void getSequenceMinMax(int[] minMax) {
if (isVisible() && !isFiltered()) {
FPCPseudoHits.getSequenceMinMax(minMax,data.getStart2(),data.getEnd2());
}
}
public String getType() { return BES_TYPE; }
public byte getBES() { return data.getBES(); }
public boolean getOrientation() { return data.getOrientation(); }
public boolean isBlockHit() { return data.isBlockHit(); }
public void set() {
bh.set(this,mt,data.getName(),getContig());
geneContained = isGeneContained(); // mdb added 3/9/07 #101
geneOverlap = isGeneOverlap(); // mdb added 3/9/07 #101
}
public boolean isGeneContained() { // mdb added 3/8/07 #101
for (Annotation annot : st.getAnnotations()) {
if (annot.isGene() &&
data.getStart2() >= annot.getStart() &&
data.getEnd2() <= annot.getEnd())
{
return true;
}
}
return false;
}
public boolean isGeneOverlap() { // mdb added 3/8/07 #101
long h1 = data.getStart2();
long h2 = data.getEnd2();
for (Annotation annot : st.getAnnotations()) {
// mdb: this compare could be made more efficient:
if (annot.isGene() &&
// Is hit start inside gene?
((h1 >= annot.getStart() && h1 <= annot.getEnd()) ||
// Is hit end inside gene?
(h2 >= annot.getStart() && h2 <= annot.getEnd()) ||
// Is gene start inside hit?
(annot.getStart() >= h1 && annot.getStart() <= h2) ||
// Is gene end inside hit?
(annot.getEnd() >= h1 && annot.getEnd() <= h2)) &&
// Is hit NOT contained in gene?
!(h1 >= annot.getStart() && h2 <= annot.getEnd()))
{
return true;
}
}
return false;
}
public boolean isFiltered() {
HitFilter hitfilter = mapper.getHitFilter();
return hitfilter.getBesHide()
|| hitfilter.getBesEvalue() < data.getEvalue()
|| hitfilter.getBesPctid() > data.getPctid()
|| (hitfilter.getBlock() && !data.isBlockHit())
|| (hitfilter.getNonRepetitive() && data.isRepetitiveHit() && !data.isBlockHit())
|| bh.isFiltered(mt,hitfilter,getContig())
|| isSequenceFiltered(data.getStart2(),data.getEnd2())
|| (hitfilter.getGeneContained() && !geneContained) // mdb added 3/9/07 #101
|| (hitfilter.getGeneOverlap() && !geneOverlap) // mdb added 3/9/07 #101
|| (hitfilter.getNonGene() && (geneOverlap || geneContained)); // mdb added 3/9/07 #101
}
public boolean isHighlighted() {
return bh.isHighlighted() || hover;
}
public boolean isVisible() {
return bh.isVisible(mt,getContig()) && isSequenceVisible(data.getStart2(),data.getEnd2());
}
private boolean lineContains(Line2D.Double line, Point p) { // mdb added 3/1/07 #100
double lx1 = line.getX1();
double lx2 = line.getX2();
double ly1 = line.getY1();
double ly2 = line.getY2();
double delta;
delta = p.getY() - ly1 - ((ly2-ly1)/(lx2-lx1))*(p.getX()-lx1);
return (delta >= -MOUSE_PADDING && delta <= MOUSE_PADDING);
}
public boolean isHover(Point point) { // mdb added 3/1/07 #100
return isVisible() && lineContains(hitLine, point);
}
protected boolean setHover(Point point) { // mdb added 3/1/07 #100
return setHover(isHover(point));
}
protected boolean setHover(boolean hover) { // mdb added 3/1/07 #100
if (hover != this.hover) {
this.hover = hover;
return true;
}
return false;
}
private Color getCColor() { // mdb added 3/1/07 #100
if (bh.isHighlighted() || isHighlighted())
return Mapper.besLineHighlightColor;
if (mapper.getHitFilter().getColorByStrand())
return data.getOrientation() ? Mapper.posOrientLineColor : Mapper.negOrientLineColor;
return Mapper.besLineColor;
}
// mdb added 8/22/07 #126
private void drawHitRibbon(Graphics2D g2, Point2D pStart, Point2D pEnd, int orient) {
String target_seq = data.getTargetSeq();
Rectangle2D.Double rect = new Rectangle2D.Double();
if (target_seq == null || target_seq.equals("")) {
g2.draw(new Line2D.Double(pStart,pEnd));
}
else {
g2.setPaint(Mapper.hitRibbonBackgroundColor);
rect.setRect(pStart.getX(),pStart.getY(),Mapper.hitRibbonWidth,pEnd.getY()-pStart.getY());
g2.fill(rect);
g2.draw(rect);
g2.setPaint(getCColor());
String[] subseq = target_seq.split(",");
for (int i = 0; i < subseq.length; i++) {
String[] pos = subseq[i].split(":");
long start = Long.parseLong(pos[0]);
long end = Long.parseLong(pos[1]);
Point2D p1 = st.getPoint(start, orient);
p1.setLocation(pStart.getX(),p1.getY());
Point2D p2 = st.getPoint(end, orient);
p2.setLocation(pStart.getX(),p2.getY());
rect.setRect(p1.getX(),p1.getY(),Mapper.hitRibbonWidth,p2.getY()-p1.getY());
g2.fill(rect);
g2.draw(rect);
}
}
}
public void paintComponent(Graphics2D g2, int mtOrient, int stOrient, Point mtLocation, Point stLocation) {
if (isVisible() && !isFiltered()) {
Point2D sp = getSequenceCPoint(data.getStart2(),data.getEnd2(),stOrient,stLocation);
Point2D bp = bh.getCPoint(mt,mtOrient,mtLocation,getContig(),data.getPos(),data.getBES());
//g2.setPaint(bh.getCColor(mapper.getHitFilter().getColorByStrand(),data.getOrientation())); // mdb removed 3/1/07 #100
g2.setPaint(getCColor()); // mdb added 3/1/07 #100
hitLine.setLine(sp,bp); // mdb added 3/1/07 #100
g2.draw(hitLine/*new Line2D.Double(sp,bp)*/); // mdb changed 3/1/07 #100
int lineLength = 0;
if (st.getShowScoreLine()) { // mdb added 2/28/07 #100
int pctid = (int)data.getPctid();
int minPctid = (int)Math.min(mapper.getHitFilter().getMinBesPctid(),
mapper.getHitFilter().getMinMrkPctid());
g2.setPaint(getCColor());
lineLength = 30*(pctid-minPctid+1)/(100-minPctid+1);
if (lineLength > 1) { // mdb added 4/1/09 - don't bother drawing if too small
int x=(int)sp.getX(), y=(int)sp.getY();
if (bp.getX() > x) lineLength = 0 - lineLength;
g2.drawLine(x,y,x+lineLength,y);//g2.draw(new Line2D.Double(x,y,x+lineLength,y)); // mdb changed 4/1/09 - drawLine() is faster than draw()
}
}
if (st.getShowRibbon()) { // mdb added 8/7/07 #126
if (lineLength == 0) lineLength = 30;
Point2D rp1 = st.getPoint(data.getStart2(), stOrient);
Point2D rp2 = st.getPoint(data.getEnd2(), stOrient);
if (rp2.getY()-rp1.getY() > 3) { // only draw if it will be visible
rp1.setLocation(sp.getX()+lineLength,rp1.getY());
rp2.setLocation(sp.getX()+lineLength,rp2.getY());
drawHitRibbon(g2, rp1, rp2, stOrient);
}
}
if (st.getShowScoreValue() || isHighlighted()) { // mdb added 3/14/07 #100
double pctid = data.getPctid();
double textX;
textX = sp.getX();
if (bp.getX() > sp.getX()) textX += lineLength-14-(pctid==100 ? -7 : 0);
else textX += lineLength;
g2.setPaint(Color.black);
g2.drawString(""+(int)pctid, (int)textX, (int)sp.getY());
}
}
}
public void clear() {
bh.clear(this);
}
public void mouseMoved(MouseEvent e) { // mdb added 3/1/07 #100
if (setHover(e.getPoint()))
mapper.getDrawingPanel().repaint();
}
}
private boolean isSequenceFiltered(int start, int end) {
return !st.isInRange( (start+end)>>1 );
}
private static void getSequenceMinMax(int[] minMax, int start, int end) {
if (start < end) {
if (start < minMax[0]) minMax[0] = start;
if (end > minMax[1]) minMax[1] = end;
}
else {
if (end < minMax[0]) minMax[0] = end;
if (start > minMax[1]) minMax[1] = start;
}
}
private boolean isSequenceVisible(int start, int end) {
return st.isInRange( (start+end)>>1 );
}
public Point2D getSequenceCPoint(int start, int end, int orientation, Point loc) {
Point2D p = st.getPoint( (start+end)>>1 , orientation );
p.setLocation(p.getX()+loc.getX(),p.getY()+loc.getY());
return p;
}
}
|
package itemboard.dao;
import java.util.List;
import java.util.Map;
import itemboard.bean.ItemBasketDTO;
import itemboard.bean.ItemBasketListDTO;
import itemboard.bean.ItemboardDTO;
import user.bean.UserDTO;
import itemboard.bean.ReviewDTO;
public interface ItemboardDAO {
public void itemboardWrite(ItemboardDTO itemboardDTO);
public List<ItemboardDTO> getItemboardList(Map<String, Object> map);
public int getTotalA(Map<String, Object> map);
public ItemboardDTO getItemboardView(String itemCode);
public void itemBasket(ItemBasketDTO itemBasketDTO);
public List<ItemBasketListDTO> getItembasketList(Map<String, Object> map);
public ItemboardDTO getSize(Map<String, String> map);
public void basketFlush(String id);
public void basketDelete(int seq);
public List<ItemBasketListDTO> getSideBarList(String id);
public void SideBarDeleteItem(int seq);
public void reviewWrite(ReviewDTO reviewDTO);
public List<ItemBasketListDTO> getStayItemList(String id);
public List<ItemBasketListDTO> getIngItemList(String id);
public List<ItemBasketListDTO> getReItemList(String id);
public List<ItemBasketListDTO> getEdItemList(String id);
public void StayItemDelete(Map<String,String> map);
public UserDTO getUserDTO(String id);
public void refundItem(int seq);
public List<ItemBasketListDTO> orderList(String stus);
public void sendItem(int seq, String stus);
public ItemBasketListDTO getSeqId(int seq);
public void refund(Map<String, Object> map);
public void qtyChg(Map<String, Object> map);
public int getCash(String id);
public void cashChg(Map<String, Object> map);
public void itemBasket2(Map<String, Object> map);
public void setAddimp(Map<String, Object> map);
}
|
package com.legaoyi.protocol.messagebody.decoder;
import org.springframework.stereotype.Component;
import com.legaoyi.protocol.exception.IllegalMessageException;
import com.legaoyi.protocol.message.MessageBody;
import com.legaoyi.protocol.message.decoder.MessageBodyDecoder;
import com.legaoyi.protocol.up.messagebody.JTT808_0003_MessageBody;
/**
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2015-01-30
*/
@Component(MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_PREFIX+"0003_2011"+MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_SUFFIX)
public class JTT808_0003_MessageBodyDecoder implements MessageBodyDecoder {
@Override
public MessageBody decode(byte[] messageBody) throws IllegalMessageException {
return new JTT808_0003_MessageBody();
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
//=====================================================================================================================================================================
class ThreadPool {
private Map<Long, PoolThread> pool = new ConcurrentHashMap<>();
final private int capacity;
public ThreadPool(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity should be greater than zero");
}
this.capacity = capacity;
}
public void submitTask(Runnable task) throws InterruptedException {
synchronized (this) {
while (pool.size() >= capacity) {
this.wait();
}
PoolThread th = new PoolThread(task, this);
pool.put(th.getId(), th);
th.start();
}
}
public void join() throws InterruptedException {
synchronized (this) {
while (pool.size() > 0) {
wait(0);
}
}
}
private class PoolThread extends Thread {
public PoolThread(Runnable task, ThreadPool threadPool) {
this.task = task;
this.threadPool = threadPool;
}
final private Runnable task;
final private ThreadPool threadPool;
@Override
public void run() {
try {
task.run();
pool.remove(this.getId());
} catch (Exception ex) {
ex.printStackTrace();
pool.remove(this.getId());
try {
this.join();
} catch (InterruptedException ex1) {
Logger.getLogger(ThreadPool.class.getName()).log(Level.SEVERE, null, ex1);
}
}
synchronized (threadPool) {
threadPool.notify();
}
}
}
}
//=====================================================================================================================================================================
class KMP {
private int[] failure = null;
private char[] pattern = null;
public KMP(char[] pattern) {
this.pattern = new char[pattern.length];
System.arraycopy(pattern, 0, this.pattern, 0, pattern.length);
this.failure = new int[pattern.length];
int firstIndex = 0;
int lastIndex = this.pattern.length - 1;
int index = firstIndex;
int i = index + 1;
this.failure[index] = index;
while (i <= lastIndex) {
if (this.pattern[index] == this.pattern[i]) {
this.failure[i++] = ++index;
} else if (index == firstIndex) {
this.failure[i++] = firstIndex;
} else {
index = this.failure[index - 1];
}
}
}
public boolean contains(char[] text) {
int patternFirstIndex = 0;
int patternLength = this.pattern.length;
int textFirstIndex = 0;
int textLen = text.length;
int i = textFirstIndex;
int index = patternFirstIndex;
while (i < textLen) {
if (text[i] == this.pattern[index]) {
i++;
index++;
} else if (index == patternFirstIndex) {
i++;
} else {
index = this.failure[index - 1];
}
if (index >= patternLength) {
return true;
}
}
return false;
}
}
//=====================================================================================================================================================================
public class FindSubstring {
final private List<Long> result = Collections.synchronizedList(new LinkedList<>());
private int threadCount = 10;
private ThreadPool pool;
private KMP patternKMP = null;
public FindSubstring(char[] pattern) {
this.patternKMP = new KMP(pattern);
this.pool = new ThreadPool(this.threadCount);
}
public FindSubstring(char[] pattern, int threadCount) {
this.patternKMP = new KMP(pattern);
this.threadCount = threadCount;
}
private class Node {
char[] str = null;
long line = -1L;
public Node(char[] str, long line) {
this.str = new char[str.length];
System.arraycopy(str, 0, this.str, 0, str.length);
this.line = line;
}
@Override
public String toString() {
return line + ", " + new String(str);
}
}
private class FindSubStringTask implements Runnable {
Node node;
public FindSubStringTask(Node node) {
this.node = node;
}
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(FindSubstring.class.getName()).log(Level.SEVERE, null, ex);
}
if (patternKMP.contains(node.str)) {
result.add(node.line);
}
}
}
public List<Long> find(File file) throws FileNotFoundException, IOException, InterruptedException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
long lineNum = 0;
while ((line = br.readLine()) != null) {
System.out.println(lineNum);
pool.submitTask(new FindSubStringTask(new Node(line.toCharArray(), lineNum++)));
}
}
pool.join();
return new LinkedList<>(this.result);
}
}
//=====================================================================================================================================================================
class Test {
final static char[] abc = "abcdefghijklmnopqrstuvwxyz".toCharArray();
static String generateALineWithNLength(int n) {
StringBuilder sb = new StringBuilder();
Random rand = new Random();
while (n > 0) {
int x = rand.nextInt(26);
sb.append(abc[x]);
n--;
}
return sb.toString();
}
static public void createFile(File file) throws IOException {
FileWriter fw = new FileWriter(file);
try (BufferedWriter bw = new BufferedWriter(fw)) {
int numLines = 100;
for (int i = 0; i < numLines; i++) {
String line = generateALineWithNLength(100000000);
bw.write(line);
bw.newLine();
if (i == numLines - 1) {
System.out.println(line);
}
}
}
}
static public void readFile(File file, String pattern) throws IOException, FileNotFoundException, InterruptedException {
FindSubstring fs = new FindSubstring(pattern.toCharArray());
System.out.println(fs.find(file).toString());
}
static public void test() throws IOException, FileNotFoundException, InterruptedException {
File file = new File("C:\\Users\\KH2246\\Desktop\\test.txt");
createFile(file);
readFile(file, "adumymap");
}
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
test();
// KMP kmp = new KMP("parveen".toCharArray());
// System.out.println(kmp.contains("adumymap".toCharArray()));
}
}
|
package com.bot.handlers;
import com.bot.enums.City;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class KeyboardSupplier {
public static String newCurrencyRequestMessage;
public static String other;
public static String usd;
public static String eur;
public static String rub;
public static String btc;
public static String calc;
private static String cities;
public static String sellUsd;
public static String buyUsd;
public static String sellEur;
public static String buyEur;
public static String sellRub;
public static String buyRub;
public static String exit;
public static String noCurrency;
public KeyboardSupplier() {
try {
loadProperties();
} catch (IOException e) {
e.printStackTrace();
}
}
public static SendMessage getStandartKeyboard(Update update) {
SendMessage keybordMessage = new SendMessage()
.setChatId(update.getMessage().getChatId())
.setText(newCurrencyRequestMessage);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
KeyboardRow first = new KeyboardRow();
first.add(usd);
first.add(eur);
KeyboardRow second = new KeyboardRow();
second.add(rub);
second.add(btc);
KeyboardRow third = new KeyboardRow();
third.add(other);
KeyboardRow fourth = new KeyboardRow();
fourth.add(calc);
List<KeyboardRow> rows = new ArrayList<>(Arrays.asList(first, second, third, fourth));
/*InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
List<List<InlineKeyboardButton>> rows = new ArrayList<>();
List<InlineKeyboardButton> firstLine = new ArrayList<>();
firstLine.add(new InlineKeyboardButton().setText(usd).setCallbackData("usd"));
firstLine.add(new InlineKeyboardButton().setText(eur).setCallbackData("eur"));
List<InlineKeyboardButton> secondLine = new ArrayList<>();
secondLine.add(new InlineKeyboardButton().setText(rub).setCallbackData("rub"));
secondLine.add(new InlineKeyboardButton().setText(btc).setCallbackData("btc"));
rows.add(firstLine);
rows.add(secondLine);
rows.add(Collections.singletonList(new InlineKeyboardButton().setText(other).setCallbackData("other")));
rows.add(Collections.singletonList(new InlineKeyboardButton().setText(calc).setCallbackData("calc")));
markupInline.setKeyboard(rows);*/
keyboardMarkup.setKeyboard(rows);
keybordMessage.setReplyMarkup(keyboardMarkup);
return keybordMessage;
}
public static SendMessage getCalcKeyboard(Update update) {
SendMessage keybordMessage = new SendMessage()
.setChatId(update.getMessage().getChatId())
.setText(calc);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
keyboardMarkup.setOneTimeKeyboard(true);
KeyboardRow first = new KeyboardRow();
first.add(sellUsd);
first.add(buyUsd);
KeyboardRow second = new KeyboardRow();
second.add(sellEur);
second.add(buyEur);
KeyboardRow third = new KeyboardRow();
third.add(sellRub);
third.add(buyRub);
KeyboardRow fourth = new KeyboardRow();
fourth.add(exit);
List<KeyboardRow> rows = new ArrayList<>(Arrays.asList(first, second, third, fourth));
keyboardMarkup.setKeyboard(rows);
keybordMessage.setReplyMarkup(keyboardMarkup);
/*InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
List<List<InlineKeyboardButton>> rows = new ArrayList<>();
List<InlineKeyboardButton> firstLine = new ArrayList<>();
firstLine.add(new InlineKeyboardButton().setText(sellUsd).setCallbackData("sellUsd"));
firstLine.add(new InlineKeyboardButton().setText(buyUsd).setCallbackData("buyUsd"));
List<InlineKeyboardButton> secondLine = new ArrayList<>();
secondLine.add(new InlineKeyboardButton().setText(sellEur).setCallbackData("sellEur"));
secondLine.add(new InlineKeyboardButton().setText(buyEur).setCallbackData("buyEur"));
List<InlineKeyboardButton> thirdLine = new ArrayList<>();
thirdLine.add(new InlineKeyboardButton().setText(sellRub).setCallbackData("sellRub"));
thirdLine.add(new InlineKeyboardButton().setText(buyRub).setCallbackData("buyRub"));
rows.add(firstLine);
rows.add(secondLine);
rows.add(thirdLine);
rows.add(Collections.singletonList(new InlineKeyboardButton().setText(exit).setCallbackData("exit")));
markupInline.setKeyboard(rows);
keybordMessage.setReplyMarkup(markupInline);*/
return keybordMessage;
}
public static SendMessage getCityKeyboard(Update update) {
SendMessage keybordMessage = new SendMessage()
.setChatId(update.getMessage().getChatId())
.setText(cities);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
keyboardMarkup.setOneTimeKeyboard(true);
KeyboardRow first = new KeyboardRow();
first.add(City.KIEV.getName());
first.add(City.KHARKOV.getName());
first.add(City.ODESSA.getName());
KeyboardRow second = new KeyboardRow();
second.add(City.DNIPRO.getName());
second.add(City.LVOV.getName());
second.add(City.DONETSK.getName());
KeyboardRow third = new KeyboardRow();
third.add(City.ZAPOROZHYE.getName());
third.add(City.NIKOLAEV.getName());
third.add(City.VINNITSA.getName());
KeyboardRow fourth = new KeyboardRow();
fourth.add(City.POLTAVA.getName());
fourth.add(City.KHMENTISKIY.getName());
fourth.add(City.CHERNIGOV.getName());
KeyboardRow fifth = new KeyboardRow();
fifth.add(City.SUMY.getName());
fifth.add(City.MARIUPOL.getName());
fifth.add(City.ZHITOMIR.getName());
KeyboardRow sixth = new KeyboardRow();
sixth.add(City.DEFAULT.getName());
List<KeyboardRow> rows = new ArrayList<>(Arrays.asList(first, second, third, fourth, fifth, sixth));
keyboardMarkup.setKeyboard(rows);
keybordMessage.setReplyMarkup(keyboardMarkup);
return keybordMessage;
}
private void loadProperties() throws IOException {
Properties propsMessage = new Properties();
InputStream in = getClass().getResourceAsStream("/ru_message.properties");
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8.name()));
propsMessage.load(reader);
usd = propsMessage.getProperty("usd");
eur = propsMessage.getProperty("eur");
rub = propsMessage.getProperty("rub");
btc = propsMessage.getProperty("btc");
newCurrencyRequestMessage = propsMessage.getProperty("newreq");
other = propsMessage.getProperty("other");
calc = propsMessage.getProperty("calc");
calc = propsMessage.getProperty("calc");
sellUsd = propsMessage.getProperty("sellUsd");
buyUsd = propsMessage.getProperty("buyUsd");
sellEur = propsMessage.getProperty("sellEur");
buyEur = propsMessage.getProperty("buyEur");
sellRub = propsMessage.getProperty("sellRub");
buyRub = propsMessage.getProperty("buyRub");
exit = propsMessage.getProperty("exit");
cities = propsMessage.getProperty("cities");
noCurrency = propsMessage.getProperty("nocurrency");
}
}
|
package solo;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import cern.colt.Swapper;
import cern.colt.list.ObjectArrayList;
public class FastMap<K,V> implements SortedMap<K, V> {
final static int INITIAL_SIZE = 50;
final static int MAX_VALUE = Integer.MAX_VALUE;
public int BIT_PER_PAGE = 17;
public int NUM_PAGE = MAX_VALUE/(2 << (BIT_PER_PAGE-1));
public int PAGE_SIZE = 2<<BIT_PER_PAGE;
int START_PAGE = NUM_PAGE >> 1;
Object minKey = null;
Object maxKey = null;
ObjectArrayList keys = null;
ObjectArrayList values = null;
Object[] k;
Object[] v;
@SuppressWarnings("rawtypes")
Comparator c =null;
int size = 0;
int len = 0;
Object[][] map = null;
boolean sorted = true;
public final Swapper swapper = new Swapper(){
@Override
public void swap(int i, int j) {
// TODO Auto-generated method stub
Object tmp = k[i];
k[i] = k[j];
k[j] = tmp;
Object vv = v[i];
v[i] = v[j];
v[j] = vv;
}
};
public FastMap() {
map = new Object[NUM_PAGE][];
// keys = new ObjectArrayList(INITIAL_SIZE);
// values = new ObjectArrayList(INITIAL_SIZE);
// TODO Auto-generated constructor stub
}
public FastMap(int initsize) {
map = new Object[NUM_PAGE][];
// keys = new ObjectArrayList(initsize);
// values = new ObjectArrayList(initsize);
// TODO Auto-generated constructor stub
}
//this constructor will not copy the array but use as backing array
public FastMap(K[] ks,V[] vs){
map = new Object[NUM_PAGE][];
// keys = new ObjectArrayList(ks);
// values = new ObjectArrayList(vs);
size = ks.length;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public final static int compare(Object a, Object b,Comparator c){
if (c!=null) return c.compare(a, b);
if (a instanceof Comparable)
return ((Comparable) a).compareTo(b);
if (b instanceof Comparable)
return -((Comparable) b).compareTo(a);
return 0;
}
public void setBitsPerPage(int v){
if (v!=BIT_PER_PAGE){
BIT_PER_PAGE = v;
NUM_PAGE = MAX_VALUE/(2 << (BIT_PER_PAGE-1));
START_PAGE = NUM_PAGE >> 1;
map = new Object[NUM_PAGE][];
}
}
@Override
public void clear() {
// TODO Auto-generated method stub
size = 0;
}
@Override
public final boolean containsKey(Object arg0) {
// TODO Auto-generated method stub
int hash = arg0.hashCode();
int id = hash >> BIT_PER_PAGE;
int offset = hash - (int)(id<<BIT_PER_PAGE);
id += START_PAGE;
return (map!=null && map[id]!=null && map[id][offset]!=null);
}
@Override
public boolean containsValue(Object arg0) {
// TODO Auto-generated method stub
return values.contains(arg0, false);
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
// TODO Auto-generated method stub
return null;
}
@SuppressWarnings("unchecked")
@Override
public final V get(Object key) {
// TODO Auto-generated method stub
if (size==0 || map==null) return null;
int hash = key.hashCode();
int id = hash >> BIT_PER_PAGE;
int offset = hash - (int)(id<<BIT_PER_PAGE);
id += START_PAGE;
if (map[id]!=null)
return (V)map[id][offset];
return null;
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return (size==0);
}
@Override
public Set<K> keySet() {
// TODO Auto-generated method stub
return null;
}
@SuppressWarnings("unchecked")
@Override
public final V put(K key, V val) {
// TODO Auto-generated method stub
int hash = key.hashCode();
int id = hash >> BIT_PER_PAGE;
int offset = hash - (int)(id<<BIT_PER_PAGE);
id += START_PAGE;
if (map[id]==null)
map[id] = new Object[PAGE_SIZE];
V old = (V)map[id][offset];
if (old==null) size++;
map[id][offset] = val;
return old;
}
@Override
public void putAll(Map<? extends K, ? extends V> arg0) {
// TODO Auto-generated method stub
}
@Override
public V remove(Object arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Collection<V> values() {
// TODO Auto-generated method stub
return null;
}
@Override
public Comparator<? super K> comparator() {
// TODO Auto-generated method stub
return null;
}
@Override
public K firstKey() {
// TODO Auto-generated method stub
return null;
}
@Override
public SortedMap<K, V> headMap(K arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public K lastKey() {
// TODO Auto-generated method stub
return null;
}
@Override
public SortedMap<K, V> subMap(K arg0, K arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public SortedMap<K, V> tailMap(K arg0) {
// TODO Auto-generated method stub
return null;
}
}
|
package edu.mit.needlstk;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.Token;
import java.util.List;
import java.util.Iterator;
/// Check if the columns used in groupby operators contain a specified field.
public class ColumnChecker extends PerfQueryBaseVisitor<Boolean> {
private String field;
public ColumnChecker (String tField) {
field = tField;
}
@Override public Boolean visitColumn (PerfQueryParser.ColumnContext ctx) {
return ctx.getText().equals(field);
}
@Override public Boolean visitOneColsList (PerfQueryParser.OneColsListContext ctx) {
return visit(ctx.column());
}
@Override public Boolean visitNoColsList (PerfQueryParser.NoColsListContext ctx) {
return new Boolean("false");
}
@Override public Boolean visitMulColsList (PerfQueryParser.MulColsListContext ctx) {
PerfQueryParser.ColumnContext firstCol = ctx.column();
Boolean found = visit(firstCol);
List<PerfQueryParser.ColumnWithCommaContext> otherCols = ctx.columnWithComma();
for (PerfQueryParser.ColumnWithCommaContext newColWithComma : otherCols) {
found = found || visit(newColWithComma.column());
}
return found;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projetobanco;
import java.util.ArrayList;
/**
*
* @author Codification
*/
public interface IDAO {
public ArrayList<Cliente> pesquisaCliente(String texto) throws Exception;
public Cliente carregaCliente(int codigoCliente) throws Exception;
public Conta carregaConta(int codigoCliente) throws Exception;
public void deletaContaCorrente(int codigoConta) throws Exception;
public void deletaContaInvestimento(int codigoConta) throws Exception;
public void atualizaConta(Conta conta) throws Exception;
public void atualizaCliente(Cliente cliente) throws Exception;
public void deletaCliente(Cliente cliente) throws Exception;
public void criaContaCorrente(Conta conta) throws Exception;
public void criaContaInvestimento(Conta conta) throws Exception;
void criaCliente(Cliente cliente) throws Exception;
}
|
package by.client.android.railwayapp.support.common;
import java.util.HashMap;
import java.util.Map;
/**
* Билдер для упрощения построения {@link Map} на этапе объявления
*
* <pre>
* Пример использования:
*
* private static final Map<Integer, String> TEST_MAP = new MapBuilder<Integer, String>()
* .put(0, "0")
* .build();
* </pre>
*
* @author PRV
*/
public class MapBuilder<K, V> {
private Map<K, V> map;
public MapBuilder() {
this.map = new HashMap<>();
}
/**
* Помещает значение в {@link Map}
*
* @param key ключ параметра
* @param value значение параметра
*/
public MapBuilder<K, V> put(K key, V value) {
map.put(key, value);
return this;
}
/**
* Выполняет построение {@link Map} путем возвращения сформированного словаря
*/
public Map<K, V> build() {
return map;
}
}
|
/*
* 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 IHM;
import data.ExportSQL;
import data.ImportSQL;
import javax.swing.JOptionPane;
import myObject.*;
/**
*
* @author Dreux
*/
public class ImportExport extends javax.swing.JFrame {
/**
* Creates new form ImportExport
*/
MetaModelObject object = new Segment();
public ImportExport() {
initComponents();
buttonGroup1.add(jRadioButtonExport);
buttonGroup1.add(jRadioButtonImport);
jPanelList.setVisible(false);
jPanelFile.setVisible(false);
jButtonNext.setEnabled(false);
pack();
}
/**
* 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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanelRadio = new javax.swing.JPanel();
jRadioButtonImport = new javax.swing.JRadioButton();
jRadioButtonExport = new javax.swing.JRadioButton();
jPanelList = new javax.swing.JPanel();
jLabelList = new javax.swing.JLabel();
jComboBoxTypeObject = new javax.swing.JComboBox();
jPanelFile = new javax.swing.JPanel();
jLabelFile = new javax.swing.JLabel();
jFileChooserImport = new javax.swing.JFileChooser();
jPanelButton = new javax.swing.JPanel();
jButtonNext = new javax.swing.JButton();
jButtonCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jRadioButtonImport.setText("Importer des objets dans la base de données");
jRadioButtonImport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonImportActionPerformed(evt);
}
});
jRadioButtonExport.setText("Exporter des objets de la base de données");
jRadioButtonExport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonExportActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelRadioLayout = new javax.swing.GroupLayout(jPanelRadio);
jPanelRadio.setLayout(jPanelRadioLayout);
jPanelRadioLayout.setHorizontalGroup(
jPanelRadioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelRadioLayout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanelRadioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonImport)
.addComponent(jRadioButtonExport))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelRadioLayout.setVerticalGroup(
jPanelRadioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelRadioLayout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jRadioButtonImport)
.addGap(18, 18, 18)
.addComponent(jRadioButtonExport)
.addContainerGap(48, Short.MAX_VALUE))
);
jLabelList.setText("Seléctionnez le type d'objet à ");
jComboBoxTypeObject.setModel(new javax.swing.DefaultComboBoxModel(object.getListOfTypeObject()));
javax.swing.GroupLayout jPanelListLayout = new javax.swing.GroupLayout(jPanelList);
jPanelList.setLayout(jPanelListLayout);
jPanelListLayout.setHorizontalGroup(
jPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListLayout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(jPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxTypeObject, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelListLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jLabelList)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelListLayout.setVerticalGroup(
jPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListLayout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabelList)
.addGap(18, 18, 18)
.addComponent(jComboBoxTypeObject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(63, Short.MAX_VALUE))
);
jLabelFile.setText("Seléctionnez le fichier à importer");
jFileChooserImport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooserImportActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelFileLayout = new javax.swing.GroupLayout(jPanelFile);
jPanelFile.setLayout(jPanelFileLayout);
jPanelFileLayout.setHorizontalGroup(
jPanelFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFileLayout.createSequentialGroup()
.addGroup(jPanelFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFileLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jFileChooserImport, javax.swing.GroupLayout.PREFERRED_SIZE, 593, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanelFileLayout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(jLabelFile)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelFileLayout.setVerticalGroup(
jPanelFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFileLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabelFile)
.addGap(18, 18, 18)
.addComponent(jFileChooserImport, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
.addGap(4, 4, 4))
);
jButtonNext.setText("Suivant");
jButtonNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonNextActionPerformed(evt);
}
});
jButtonCancel.setText("Annuler");
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelButtonLayout = new javax.swing.GroupLayout(jPanelButton);
jPanelButton.setLayout(jPanelButtonLayout);
jPanelButtonLayout.setHorizontalGroup(
jPanelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonLayout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButtonNext)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonCancel)
.addGap(139, 139, 139))
);
jPanelButtonLayout.setVerticalGroup(
jPanelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonNext)
.addComponent(jButtonCancel))
.addContainerGap(66, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelRadio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelButton, 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(jPanelRadio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(jPanelFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNextActionPerformed
// TODO add your handling code here:
if(jPanelRadio.isVisible()){
jPanelRadio.setVisible(false);
jPanelList.setVisible(true);
if(jRadioButtonImport.isSelected())
jLabelList.setText(jLabelList.getText() + " importer");
else
jLabelList.setText(jLabelList.getText() + " exporter");
}else if(jPanelList.isVisible() && jRadioButtonImport.isSelected()){
jPanelList.setVisible(false);
jPanelFile.setVisible(true);
}else{
if(jPanelFile.isVisible()){
if(jComboBoxTypeObject.getSelectedItem().equals("Responsible")){
ImportSQL.importResponsible(jFileChooserImport.getSelectedFile());
JOptionPane.showMessageDialog(null,"Import Responsable Effectué");
}
else{
JOptionPane.showMessageDialog(null,"Fonctionalité non implémentée");
}
}else{
if(jComboBoxTypeObject.getSelectedItem().equals("Zone")){
ExportSQL.exportSegment();
JOptionPane.showMessageDialog(null, "Fichier export zone créé");
}else if(jComboBoxTypeObject.getSelectedItem().equals("Quartier")){
ExportSQL.exportProcess();
JOptionPane.showMessageDialog(null, "Fichier export quartier créé");
}else if(jComboBoxTypeObject.getSelectedItem().equals("Ilot")){
ExportSQL.exportCapabilities();
JOptionPane.showMessageDialog(null, "Fichier export ilot créé");
}else
JOptionPane.showMessageDialog(null, "Fonctionnalité non implémentée");
}
}
pack();
}//GEN-LAST:event_jButtonNextActionPerformed
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void jFileChooserImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooserImportActionPerformed
// TODO add your handling code here:
ImportSQL.importResponsible(jFileChooserImport.getSelectedFile());
JOptionPane.showMessageDialog(null,"Import Responsable Effectué");
this.dispose();
}//GEN-LAST:event_jFileChooserImportActionPerformed
private void jRadioButtonImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonImportActionPerformed
// TODO add your handling code here:
jButtonNext.setEnabled(true);
}//GEN-LAST:event_jRadioButtonImportActionPerformed
private void jRadioButtonExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonExportActionPerformed
// TODO add your handling code here:
jButtonNext.setEnabled(true);
}//GEN-LAST:event_jRadioButtonExportActionPerformed
/**
* @param args the command line arguments
*/
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(ImportExport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImportExport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImportExport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImportExport.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 ImportExport().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonNext;
private javax.swing.JComboBox jComboBoxTypeObject;
private javax.swing.JFileChooser jFileChooserImport;
private javax.swing.JLabel jLabelFile;
private javax.swing.JLabel jLabelList;
private javax.swing.JPanel jPanelButton;
private javax.swing.JPanel jPanelFile;
private javax.swing.JPanel jPanelList;
private javax.swing.JPanel jPanelRadio;
private javax.swing.JRadioButton jRadioButtonExport;
private javax.swing.JRadioButton jRadioButtonImport;
// End of variables declaration//GEN-END:variables
}
|
/*
* Copyright (C) 2008-12 Bernhard Hobiger
*
* This file is part of HoDoKu.
*
* HoDoKu is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HoDoKu is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HoDoKu. If not, see <http://www.gnu.org/licenses/>.
*/
package sudoku;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.math.BigInteger;
import java.util.List;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author hobiwan
*/
public class SudokuUtil {
/** The correct line separator for the current platform */
public static String NEW_LINE = System.getProperty("line.separator");
/** A global PrinterJob; is here and not in {@link Options} because it needs a getter but should not be written to a configuration file. */
private static PrinterJob printerJob;
/** A global PageFormat; is here and not in {@link Options} because it needs a getter but should not be written to a configuration file. */
private static PageFormat pageFormat;
/**
* Clears the list. To avoid memory leaks all steps in the list
* are explicitly nullified.
* @param steps
*/
public static void clearStepListWithNullify(List<SolutionStep> steps) {
if (steps != null) {
for (int i = 0; i < steps.size(); i++) {
steps.get(i).reset();
steps.set(i, null);
}
steps.clear();
}
}
/**
* Clears the list. The steps are not nullfied, but the list items are.
* @param steps
*/
public static void clearStepList(List<SolutionStep> steps) {
if (steps != null) {
for (int i = 0; i < steps.size(); i++) {
steps.set(i, null);
}
steps.clear();
}
}
/**
* Calculates n over k
*
* @param n
* @param k
* @return
*/
public static int combinations(int n, int k) {
if (n <= 167) {
double fakN = 1;
for (int i = 2; i <= n; i++) {
fakN *= i;
}
double fakNMinusK = 1;
for (int i = 2; i <= n - k; i++) {
fakNMinusK *= i;
}
double fakK = 1;
for (int i = 2; i <= k; i++) {
fakK *= i;
}
return (int) (fakN / (fakNMinusK * fakK));
} else {
BigInteger fakN = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
fakN = fakN.multiply(new BigInteger(i + ""));
}
BigInteger fakNMinusK = BigInteger.ONE;
for (int i = 2; i <= n - k; i++) {
fakNMinusK = fakNMinusK.multiply(new BigInteger(i + ""));
}
BigInteger fakK = BigInteger.ONE;
for (int i = 2; i <= k; i++) {
fakK = fakK.multiply(new BigInteger(i + ""));
}
fakNMinusK = fakNMinusK.multiply(fakK);
fakN = fakN.divide(fakNMinusK);
return fakN.intValue();
}
}
/**
* @return the printerJob
*/
public static PrinterJob getPrinterJob() {
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
return printerJob;
}
/**
* @return the pageFormat
*/
public static PageFormat getPageFormat() {
if (pageFormat == null) {
pageFormat = getPrinterJob().defaultPage();
}
return pageFormat;
}
/**
* HiRes printing in Java is difficult: The whole printing engine
* (except apparently text printing) is scaled down to 72dpi. This is
* done by applying an AffineTransform object with a scale to the Graphics2D
* object of the printer. To make things more complicated just reversing
* the scale is not enough: for Landscape printing a rotation is applied
* after the scale.<br><br>
*
* The easiest way to really achieve hires printing is to directly manipulate
* the transformation matrix. The default matrix looks like this:<br>
* <pre>
* Portrait Landscape
* [ d 0 x ] [ 0 d x ]
* [ 0 d y ] [ -d 0 y ]
* [ 0 0 1 ] [ 0 0 1 ]
*
* d = printerResolution / 72.0
* </pre>
* x and y are set by the printer engine and should not be changed.<br><br>
*
* The values from the {@link PageFormat} object are scaled down to 72dpi
* as well and have to be multiplied with d to get the correct hires values.
*
* @param g2
* @return The scale factor
*/
public static double adjustGraphicsForPrinting(Graphics2D g2) {
AffineTransform at = g2.getTransform();
double[] matrix = new double[6];
at.getMatrix(matrix);
//System.out.println("matrix: " + Arrays.toString(matrix));
double scale = matrix[0];
if (scale != 0) {
// Portrait
matrix[0] = 1;
matrix[3] = 1;
} else {
// Landscape
scale = matrix[2];
matrix[1] = -1;
matrix[2] = 1;
}
// int resolution = (int)(72.0 * scale);
AffineTransform newAt = new AffineTransform(matrix);
g2.setTransform(newAt);
return scale;
}
/**
* Sets the Look and Feel to the class stored in {@link Options#laf}. To make
* HoDoKu behave nicely for visually impaired users, a non standard font size
* {@link Options#customFontSize} can be used for all GUI elements, if
* {@link Options#useDefaultFontSize} is set to <code>false</code>.<br><br>
*
* This is where the problems starts: On most LaFs (GTK excluded, nothing can
* be changed in GTK LaF) changing the font size works by changing all Font
* instances in <code>UIManager.getDefaults()</code>. Not with Nimbus though:
* Due to late initialization issues the standard method leads to unpredictable results
* (see http://stackoverflow.com/questions/949353/java-altering-ui-fonts-nimbus-doesnt-work
* for details).<br><br>
*
* Changing the font size in Nimbus can be done in one of two ways:
*
* <ul>
* <li>Subclass <code>NimbusLookAndFeel</code> and override <code>getDefaults()</code></li>
* <li>Obtain an instance of <code>NimbusLookAndFeel</code> and set the <code>defaultFont</code>
* option on the instance directly (<b>not</b> on <code>UIManager.getDefaults()</code>).</li>
* </ul>
*
* Although both methods seem to be simple enough, there is a slight complication: The package
* of the <code>NimbusLookAndFeel</code> class changed between Java 1.6 (<code>sun.swing.plaf.nimbus</code>)
* and 1.7 (<code>javax.swing.plaf.nimbus</code>). That means, that if the class is subclassed
* or instantiated directly, code compiled with 1.7 will not start on 1.6 and vice versa
* (and of course the program will not start on all JRE versions, that dont have Nimbus included).
* And we have to think of the possiblilty, that the class stored in {@link Options#laf} doesnt
* exist at all, if the hcfg file is moved between platforms.<br><br>
*
*/
// public static void setLookAndFeel() {
// // ok: start by getting the correct AND existing LaF class
// LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
// boolean found = false;
// String className = Options.getInstance().getLaf();
// String oldClassName = className;
// if (!className.isEmpty()) {
// String lafName = className.substring(className.lastIndexOf('.') + 1);
// for (int i = 0; i < lafs.length; i++) {
// if (lafs[i].getClassName().equals(className)) {
// found = true;
// break;
// } else if (lafs[i].getClassName().endsWith(lafName)) {
// // same class, different package
// className = lafs[i].getClassName();
// Logger.getLogger(Main.class.getName()).log(Level.CONFIG, "laf package changed from {0} to {1}", new Object[]{oldClassName, className});
// found = true;
// break;
// }
// }
// }
// if (!found) {
// // class not present or default requested
// Options.getInstance().setLaf("");
// className = UIManager.getSystemLookAndFeelClassName();
// } else {
// if (!oldClassName.equals(className)) {
// Options.getInstance().setLaf(className);
// }
// }
//
// // ok, the correct class name is now in className
// // -> obtain an instance of the LaF class
// ClassLoader classLoader = MainFrame.class.getClassLoader();
// Class<?> lafClass = null;
// try {
// lafClass = classLoader.loadClass(className);
// } catch (ClassNotFoundException e) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Error changing LaF 1", e);
// return;
// }
// LookAndFeel instance = null;
// try {
// instance = (LookAndFeel) lafClass.newInstance();
// } catch (Exception ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Error changing LaF 2", ex);
// return;
// }
//
// // we have a LaF instance: try setting it
// try {
// int fontSize = Options.getInstance().getCustomFontSize();
// if (!Options.getInstance().isUseDefaultFontSize()) {
// // first change the defaults for Nimbus
// UIDefaults def = instance.getDefaults();
// Object value = null;
// if ((value = def.get("defaultFont")) != null) {
// // exists on Nimbus and triggers inheritance
// Font font = (Font) value;
// if (font.getSize() != fontSize) {
//// System.out.println("Changing fontSize (1) from " + font.getSize() + " to " + fontSize);
// def.put("defaultFont", new FontUIResource(font.getName(), font.getStyle(), fontSize));
// }
// }
// }
//
// // set the new LaF
// UIManager.setLookAndFeel(instance);
// Logger.getLogger(Main.class.getName()).log(Level.CONFIG, "laf={0}", UIManager.getLookAndFeel().getName());
//
// if (!Options.getInstance().isUseDefaultFontSize()) {
// // change the defaults for all other LaFs
// UIDefaults def = UIManager.getDefaults();
// // def.keySet() doesnt seem to work -> use def.keys() instead!
// Enumeration<Object> keys = def.keys();
// while (keys.hasMoreElements()) {
// Object key = keys.nextElement();
// Font font = def.getFont(key);
// if (font != null) {
// if (font.getSize() != fontSize) {
//// System.out.println("Changing fontSize (2) from " + font.getSize() + " to " + fontSize);
// def.put(key, new FontUIResource(font.getName(), font.getStyle(), fontSize));
// }
// }
// }
// }
// } catch (Exception ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Error changing LaF 3", ex);
// }
// }
/**
* Prints the default font settings to stdout. Used for
* debugging only.
*/
public static void printFontDefaults() {
System.out.println("Default font settings: UIManager");
UIDefaults def = UIManager.getDefaults();
SortedMap<String,String> items = new TreeMap<String,String>();
// def.keySet() doesnt seem to work -> use def.keys() instead!
Enumeration<Object> keys = def.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Font font = def.getFont(key);
if (font != null) {
items.put(key.toString(), font.getName() + "/" + font.getStyle() + "/" + font.getSize());
}
}
Set<Entry<String,String>> entries = items.entrySet();
for (Entry<String,String> act : entries) {
System.out.println(" " + act.getKey() + ": " + act.getValue());
}
}
/**
* Reformat a sudoku given by a 81 character string to
* SimpleSudoku format.
*
* @param values
* @return
*/
public static String getSSFormatted(String values) {
StringBuilder tmp = new StringBuilder();
values = values.replace('0', '.');
tmp.append(" *-----------*");
tmp.append(NEW_LINE);
writeSSLine(tmp, values, 0);
writeSSLine(tmp, values, 9);
writeSSLine(tmp, values, 18);
tmp.append(" |---+---+---|");
tmp.append(NEW_LINE);
writeSSLine(tmp, values, 27);
writeSSLine(tmp, values, 36);
writeSSLine(tmp, values, 45);
tmp.append(" |---+---+---|");
tmp.append(NEW_LINE);
writeSSLine(tmp, values, 54);
writeSSLine(tmp, values, 63);
writeSSLine(tmp, values, 72);
tmp.append(" *-----------*");
tmp.append(NEW_LINE);
return tmp.toString();
}
/**
* Build one line of a sudoku defined by <code>clues</code>
* in SimpleSudoku format.
*
* @param tmp
* @param clues
* @param startIndex
*/
private static void writeSSLine(StringBuilder tmp, String clues, int startIndex) {
tmp.append(" |");
tmp.append(clues.substring(startIndex + 0, startIndex + 3));
tmp.append("|");
tmp.append(clues.substring(startIndex + 3, startIndex + 6));
tmp.append("|");
tmp.append(clues.substring(startIndex + 6, startIndex + 9));
tmp.append("|");
tmp.append(NEW_LINE);
}
/**
* Reformat a HoDoKu PM grid to SimpleSudoku format.
*
* @param grid
* @return
*/
public static String getSSPMGrid(String grid) {
// .---------------.------------.-------------.
// | 1 78 38 | 2 49 6 | 47 39 5 |
// | 9 67 5 | 3 8 14 | 47 16 2 |
// | 36 4 2 | 19 7 5 | 8 36 19 |
// :---------------+------------+-------------:
// | 8 9 7 | 5 6 2 | 13 4 13 |
// | 25 25 1 | 4 3 8 | 9 7 6 |
// | 4 3 6 | 7 1 9 | 5 2 8 |
// :---------------+------------+-------------:
// | 36 16 4 | 8 5 7 | 2 19 139 |
// | 7 158 89 | 19 2 3 | 6 58 4 |
// | 25 1258 389 | 6 49 14 | 3 58 7 |
// '---------------'------------'-------------'
// parse the grid
String[] parts = grid.split(" ");
String[] cells = new String[81];
int maxLength = 0;
for (int i = 0, j = 0; i < parts.length; i++) {
if (parts[i].isEmpty()) {
continue;
}
char ch = parts[i].charAt(0);
if (Character.isDigit(ch)) {
cells[j++] = parts[i];
if (parts[i].length() > maxLength) {
maxLength = parts[i].length();
}
}
}
// now make all cells equally long
for (int i = 0; i < cells.length; i++) {
if (cells[i].length() < maxLength) {
int anz = maxLength - cells[i].length();
for (int j = 0; j < anz; j++) {
cells[i] += " ";
}
}
}
// build the grid
StringBuilder tmp = new StringBuilder();
writeSSPMFrameLine(tmp, maxLength, true);
writeSSPMLine(tmp, cells, 0);
writeSSPMLine(tmp, cells, 9);
writeSSPMLine(tmp, cells, 18);
writeSSPMFrameLine(tmp, maxLength, false);
writeSSPMLine(tmp, cells, 27);
writeSSPMLine(tmp, cells, 36);
writeSSPMLine(tmp, cells, 45);
writeSSPMFrameLine(tmp, maxLength, false);
writeSSPMLine(tmp, cells, 54);
writeSSPMLine(tmp, cells, 63);
writeSSPMLine(tmp, cells, 72);
writeSSPMFrameLine(tmp, maxLength, true);
return tmp.toString();
}
/**
* Write one line containing cells for a SimpleSudoku PM grid.
* @param tmp
* @param cells
* @param index
*/
private static void writeSSPMLine(StringBuilder tmp, String[] cells, int index) {
tmp.append(" | ");
tmp.append(cells[index + 0]);
tmp.append(" ");
tmp.append(cells[index + 1]);
tmp.append(" ");
tmp.append(cells[index + 2]);
tmp.append(" | ");
tmp.append(cells[index + 3]);
tmp.append(" ");
tmp.append(cells[index + 4]);
tmp.append(" ");
tmp.append(cells[index + 5]);
tmp.append(" | ");
tmp.append(cells[index + 6]);
tmp.append(" ");
tmp.append(cells[index + 7]);
tmp.append(" ");
tmp.append(cells[index + 8]);
tmp.append(" |");
tmp.append(NEW_LINE);
}
/**
* Write one frame line for a SimpleSudoku PM grid.
* @param tmp
* @param maxLength
* @param outer
*/
private static void writeSSPMFrameLine(StringBuilder tmp, int maxLength, boolean outer) {
tmp.append(" *");
for (int i = 0; i < 3 * maxLength + 7; i++) {
tmp.append("-");
}
if (outer) {
tmp.append("-");
} else {
tmp.append("+");
}
for (int i = 0; i < 3 * maxLength + 7; i++) {
tmp.append("-");
}
if (outer) {
tmp.append("-");
} else {
tmp.append("+");
}
for (int i = 0; i < 3 * maxLength + 7; i++) {
tmp.append("-");
}
if (outer) {
tmp.append("*");
} else {
tmp.append("|");
}
tmp.append(NEW_LINE);
}
/**
* STUB!!
*
* Is meant for replacing candidate numbers with colors for colorKu.
* Doesnt do anything meaningful right now.
*
* @param candidate
* @return
*/
public static String getCandString(int candidate) {
if (Options.getInstance().isShowColorKuAct()) {
// return some color name here
return String.valueOf(candidate);
} else {
return String.valueOf(candidate);
}
}
/**
* testing...
*
* @param args
*/
public static void main(String[] args) {
String grid =
".---------------.------------.-------------." +
"| 1 78 38 | 2 49 6 | 47 39 5 |" +
"| 9 67 5 | 3 8 14 | 47 16 2 |" +
"| 36 4 2 | 19 7 5 | 8 36 19 |" +
":---------------+------------+-------------:" +
"| 8 9 7 | 5 6 2 | 13 4 13 |" +
"| 25 25 1 | 4 3 8 | 9 7 6 |" +
"| 4 3 6 | 7 1 9 | 5 2 8 |" +
":---------------+------------+-------------:" +
"| 36 16 4 | 8 5 7 | 2 19 139 |" +
"| 7 158 89 | 19 2 3 | 6 58 4 |" +
"| 25 1258 389 | 6 49 14 | 3 58 7 |" +
"'---------------'------------'-------------'";
getSSPMGrid(grid);
}
}
|
package com.rhino.taskManager;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.rhino.taskManager.agent.TaskAgentInterface;
import com.rhino.taskManager.error.TypeNotFoundException;
import com.rhino.userAttributesServic.data.UserDataInterface;
public class TaskManagerImpl implements TaskManagerInterface{
private Map<String, TaskAgentInterface> agentMap ;
public Collection<UserDataInterface> getNextJob(String type) throws TypeNotFoundException, IOException, ClassNotFoundException{
TaskAgentInterface worker = agentMap.get(type);
if(worker !=null){
return worker.getNextJob();
}
Set<String> keys = agentMap.keySet();
throw new TypeNotFoundException("The type "+type+" did not found in the workers list!!!("+keys+")");
}
public void finishworkingOnJob(String type,Collection<UserDataInterface> job) throws TypeNotFoundException, IOException{
TaskAgentInterface worker = agentMap.get(type);
if(worker !=null){
worker.finishWorkingOnJob(job);
return;
}
Set<String> keys = agentMap.keySet();
throw new TypeNotFoundException("The type "+type+" did not found in the workers list!!!("+keys+")");
}
public Map<String, TaskAgentInterface> getAgentMap() {
return agentMap;
}
public void setAgentMap(Map<String, TaskAgentInterface> workersMap) {
this.agentMap = workersMap;
}
}
|
package edu.cricket.api.cricketscores.rest.source.model;
public class CompetitionClass {
private int internationalClassId;
private int generalClassId;
private String name;
private String eventType;
public int getInternationalClassId() {
return internationalClassId;
}
public void setInternationalClassId(int internationalClassId) {
this.internationalClassId = internationalClassId;
}
public int getGeneralClassId() {
return generalClassId;
}
public void setGeneralClassId(int generalClassId) {
this.generalClassId = generalClassId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
}
|
package com.jgermaine.fyp.rest.controller;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.persistence.NoResultException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.jgermaine.fyp.rest.config.WebApplication;
import com.jgermaine.fyp.rest.model.Citizen;
import com.jgermaine.fyp.rest.model.Report;
import com.jgermaine.fyp.rest.model.User;
import com.jgermaine.fyp.rest.service.impl.CitizenServiceImpl;
import com.jgermaine.fyp.rest.service.impl.CouncilAlertUserDetailsService;
import com.jgermaine.fyp.rest.util.ResponseMessageUtil;
import com.jgermaine.fyp.rest.util.TestUtil;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebApplication.class)
public class CitizenControllerTest {
@Autowired
private WebApplicationContext context;
@InjectMocks
CitizenController controller;
@Mock
private CouncilAlertUserDetailsService councilAlertUserService;
@Mock
private CitizenServiceImpl citizenService;
private MockMvc mvc;
private Citizen citizen;
private Report report;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(controller).build();
citizen = TestUtil.getDefaultCitizen();
report = TestUtil.getDefaultReport();
}
@Test
public void testAddCitizenSuccess() throws Exception {
Mockito.doNothing().when(councilAlertUserService).createNewUser(Mockito.any(User.class));
// @formatter:off
mvc.perform(
post("/api/citizen/").contentType(
new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"))).content(TestUtil.convertObjectToJsonBytes(citizen)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.message", is(ResponseMessageUtil.SUCCESS_USER_CREATION)));
// @formatter:on
}
@Test
public void testAddInvalidCitizenFailure() throws Exception {
Citizen citz = TestUtil.getDefaultCitizen();
citz.setEmail("1234-Invalid");
// @formatter:off
mvc.perform(
post("/api/citizen/").contentType(
new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"))).content(TestUtil.convertObjectToJsonBytes(citz)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message", is("1 " + ResponseMessageUtil.ERROR_INVALID_DATA)));
// @formatter:on
}
@Test
public void testNonUniqueCitizenFailure() throws Exception {
Mockito.doThrow(DataIntegrityViolationException.class).when(councilAlertUserService)
.createNewUser(Mockito.any(Citizen.class));
// @formatter:off
mvc.perform(
post("/api/citizen/").contentType(
new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"))).content(TestUtil.convertObjectToJsonBytes(citizen)))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.message", is(ResponseMessageUtil.ERROR_USER_EXIST)));
// @formatter:on
}
@Test
public void testGetReportForCitizenSuccess() throws Exception {
when(citizenService.getReportsForCitizen(Mockito.anyString())).thenReturn(Arrays.asList(report));
// @formatter:off
mvc.perform(
get("/api/citizen/report/sample@email.com"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id", is(report.getId())));
// @formatter:on
}
@SuppressWarnings("unchecked")
@Test
public void testGetReportForCitizenFailure() throws Exception {
when(citizenService.getReportsForCitizen(Mockito.anyString())).thenThrow(NoResultException.class);
// @formatter:off
mvc.perform(
get("/api/citizen/report/sample@email.com"))
.andExpect(status().isBadRequest());
// @formatter:on
}
@Test
public void testGetCitizenByEmailSuccess() throws Exception {
when(citizenService.getCitizen(anyString())).thenReturn(citizen);
// @formatter:off
mvc.perform(get("/api/citizen/sample@email.com")).andExpect(status().isOk())
.andExpect(jsonPath("$.email", is(citizen.getEmail())));
// @formatter:on
}
@SuppressWarnings("unchecked")
@Test
public void testGetEmployeesByEmailFailure() throws Exception {
when(citizenService.getCitizen(anyString())).thenThrow(NoResultException.class);
// @formatter:off
mvc.perform(get("/api/citizen/sample@email.com")).andExpect(status().isBadRequest());
// @formatter:on
}
}
|
package iaraliev.rashid.bigbroserver;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableScheduling
public class BigbroserverApplication {
public static void main(String[] args) {
SpringApplication.run(BigbroserverApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build()));
}
}
|
public class AreaCalculator {
public static double area(double radius){
if(radius < 0){
return -1.0;
}
double pi = Math.PI;
double areaOfCircle = radius * radius * pi;
System.out.println("Radius of circle is "+ areaOfCircle);
return areaOfCircle;
}
public static double area(double x,double y){
if(x<0 || y<0){
return -1.0;
}
double areaOfRect = x * y;
System.out.println("area of reactangle is "+ areaOfRect);
return areaOfRect;
}
}
|
/*
* 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 Testing.SeleniumTesting;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
*
* @author User
*/
/**
*
* @author User
*/
public class IngSearcgOnlineTest {
@Test
public void successfulLSearchTest() throws InterruptedException {
//Open firefox
WebDriver driver = new FirefoxDriver();
//Go to the page specified
driver.get("http://www.kitchenhuntr.com/KitchenHunt/index.jsp");
//Click on get started button
driver.findElement(By.xpath("//*[@id=\"getStarted\"]/button")).click();
//Enter ingredient
driver.findElement(By.xpath("//*[@id=\"recipe_inc_ing\"]")).sendKeys("pineapple");
//Click on search button
driver.findElement(By.xpath("//*[@id=\"testform\"]/button")).click();
Thread.sleep(2000);
}
public static void main(String[] args) throws InterruptedException {
IngSearcgOnlineTest test = new IngSearcgOnlineTest();
test.successfulLSearchTest();
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2014 Squawkers13 <Squawkers13@pekkit.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.pekkit.feathereconomy.vault;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.milkbowl.vault.economy.Economy;
import net.pekkit.feathereconomy.FeatherEconomy;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
public class VaultImport {
private final List<Economy> economies;
private FeatherEconomy plugin;
public VaultImport(FeatherEconomy pl) {
this.economies = new ArrayList();
FeatherEconomy plugin = pl;
Collection<RegisteredServiceProvider<Economy>> providers = plugin.getServer().getServicesManager().getRegistrations(Economy.class);
if (providers == null) {
return;
}
for (RegisteredServiceProvider<Economy> econProvider : providers) {
Economy provider = econProvider.getProvider();
if (!(provider instanceof Economy_FeatherEcon)) {
this.economies.add(provider);
}
}
}
public void doImport(String pluginName) {
if (this.economies.size() <= 0) {
plugin.getLogger().warning("No plugins to import!");
return;
}
for (Economy economy : this.economies) {
if (economy.getName().equalsIgnoreCase(pluginName)) {
doImport(economy);
return;
}
}
if (this.economies.size() <= 0) {
plugin.getLogger().warning("Cannot find plugin '" + pluginName + "' to import.");
}
}
public void doImport() {
if (this.economies.size() <= 0) {
plugin.getLogger().warning("No plugins to import!");
return;
}
for (Economy economy : this.economies) {
doImport(economy);
}
}
public boolean canImport(String pluginName) {
for (Economy economy : this.economies) {
if (economy.getName().equalsIgnoreCase(pluginName)) {
return true;
}
}
return false;
}
public void doImport(final Economy economy) {
if (economy != null) {
plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
public void run() {
plugin.getLogger().info("[Plugin: " + economy.getName() + "] Iterating over all offline players...");
OfflinePlayer[] players = plugin.getServer().getOfflinePlayers();
int lastPercent = -1;
for (int i = 0; i < players.length; i++) {
int balance = (int) economy.getBalance(players[i]);
plugin.getAPI().setBalance(players[i].getUniqueId(), balance);
int percent = (int) (i / players.length * 100.0D);
if ((percent % 10 == 0) && (percent != lastPercent)) {
plugin.getLogger().info("[Plugin: " + economy.getName() + "]" + i + "/" + players.length + " imported. (" + percent + "%)");
lastPercent = percent;
}
}
plugin.getLogger().info("[Plugin: " + economy.getName() + "] Import complete!");
}
});
}
}
}
|
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import com.example.controller.ControllerClass;
@SpringBootApplication
@EnableJpaAuditing
@ComponentScan(basePackageClasses=ControllerClass.class)
public class FirstBootProApplication {
public static void main(String[] args) {
SpringApplication.run(FirstBootProApplication.class, args);
}
}
|
package com.getkhaki.api.bff.web;
import com.getkhaki.api.bff.BaseMvcIntegrationTest;
import com.getkhaki.api.bff.config.interceptors.models.SessionTenant;
import com.getkhaki.api.bff.web.models.DepartmentStatisticsResponseDto;
import com.getkhaki.api.bff.web.models.DepartmentsStatisticsResponseDto;
import com.getkhaki.api.bff.web.models.IntervalDte;
import com.getkhaki.api.bff.web.models.StatisticsFilterDte;
import com.getkhaki.api.bff.web.models.TimeBlockSummaryResponseDto;
import com.getkhaki.api.bff.web.models.TrailingStatisticsResponseDto;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class StatisticsControllerIntegrationTests extends BaseMvcIntegrationTest {
public StatisticsControllerIntegrationTests(WebApplicationContext webApplicationContext) {
super(webApplicationContext);
this.webApplicationContext = webApplicationContext;
}
@Test
public void testOrganizersStatisticsDefault() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-08T00:00:00.000Z");
String url = String.format("/statistics/organizers/%s/%s", start, end);
mvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionTenant.HEADER_KEY, "s56_net")
.with(jwt().jwt(getJWT("bob@s56.net")).authorities(new SimpleGrantedAuthority("admin"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()").value(2))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')].totalSeconds").value(9 * 3600))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')].totalMeetings").value(1))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')].totalSeconds").value(18000))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')].totalMeetings").value(2));
}
@Test
public void testOrganizersStatisticsInternal() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-30T00:00:00.000Z");
String url = String.format("/statistics/organizers/%s/%s?filter=" + StatisticsFilterDte.Internal, start, end);
mvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionTenant.HEADER_KEY, "s56_net")
.with(jwt().jwt(getJWT("bob@s56.net")).authorities(new SimpleGrantedAuthority("admin"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()").value(2))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerLastName == 'Smith')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')].totalSeconds").value(32400))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')].totalMeetings").value(1))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerLastName == 'Jones')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')].totalSeconds").value(7200))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')].totalMeetings").value(1));
}
@Test
public void testOrganizersStatisticsAll() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-30T00:00:00.000Z");
String url = String.format("/statistics/organizers/aggregate/%s/%s", start, end);
mvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionTenant.HEADER_KEY, "s56_net")
.with(jwt().jwt(getJWT("bob@s56.net")).authorities(new SimpleGrantedAuthority("admin"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()").value(2))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerLastName == 'Smith')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')].internalMeetingSeconds").value(32400))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Betty')].internalMeetingCount").value(1))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerLastName == 'Jones')]").exists())
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')].externalMeetingSeconds").value(25200))
.andExpect(jsonPath("$.content[?(@.organizerFirstName == 'Bob')].externalMeetingCount").value(2));
}
@Test
public void testDepartmentStatisticsDefault() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-30T00:00:00.000Z");
String url = String.format("/statistics/department/%s/%s", start, end);
DepartmentsStatisticsResponseDto stats = getTypedResult(url, DepartmentsStatisticsResponseDto.class);
DepartmentStatisticsResponseDto itDepartment = stats.getDepartmentsStatistics()
.stream()
.filter(stat -> stat.getDepartment().equals("IT"))
.findFirst()
.orElseThrow();
assertThat(itDepartment.getTotalSeconds()).isEqualTo(32400);
assertThat(itDepartment.getInventorySecondsAvailable()).isEqualTo(1152000);
DepartmentStatisticsResponseDto hrDepartment = stats.getDepartmentsStatistics()
.stream()
.filter(stat -> stat.getDepartment().equals("HR"))
.findFirst()
.orElseThrow();
assertThat(hrDepartment.getTotalSeconds()).isEqualTo(25200);
assertThat(hrDepartment.getInventorySecondsAvailable()).isEqualTo(576000);
}
@Test
public void testDepartmentStatisticsInternal() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-30T00:00:00.000Z");
String url = String.format("/statistics/department/%s/%s?filter=" + StatisticsFilterDte.Internal, start, end);
DepartmentsStatisticsResponseDto stats = getTypedResult(url, DepartmentsStatisticsResponseDto.class);
DepartmentStatisticsResponseDto itDepartment = stats.getDepartmentsStatistics()
.stream()
.filter(stat -> stat.getDepartment().equals("IT"))
.findFirst()
.orElseThrow();
assertThat(itDepartment.getTotalSeconds()).isEqualTo(25200);
assertThat(itDepartment.getInventorySecondsAvailable()).isEqualTo(1152000);
DepartmentStatisticsResponseDto hrDepartment = stats.getDepartmentsStatistics()
.stream()
.filter(stat -> stat.getDepartment().equals("HR"))
.findFirst()
.orElseThrow();
assertThat(hrDepartment.getTotalSeconds()).isEqualTo(14400);
assertThat(hrDepartment.getInventorySecondsAvailable()).isEqualTo(576000);
}
@Test
public void testTrailingStatisticsDefault() throws Exception {
Instant start = Instant.parse("2020-11-02T00:00:00.000Z");
int count = 2;
String url = String.format("/statistics/trailing/%s/%s/%d", start, IntervalDte.Day, count);
TrailingStatisticsResponseDto stats = getTypedResult(url, TrailingStatisticsResponseDto.class);
assertThat(stats.getTimeBlockSummaries()).hasSize(2);
List<TimeBlockSummaryResponseDto> summaries = stats.getTimeBlockSummaries();
assertThat(summaries.get(0).getNumEmployees()).isEqualTo(3);
assertThat(summaries.get(0).getMeetingCount()).isEqualTo(0);
assertThat(summaries.get(1).getTotalSeconds()).isEqualTo(18000L);
assertThat(summaries.get(1).getMeetingCount()).isEqualTo(2);
}
@Test
public void testTrailingStatisticsInternal() throws Exception {
Instant start = Instant.parse("2020-11-02T00:00:00.000Z");
int count = 2;
String url = String.format("/statistics/trailing/%s/%s/%d?filter=%s", start, IntervalDte.Day, count,
StatisticsFilterDte.Internal);
TrailingStatisticsResponseDto stats = getTypedResult(url, TrailingStatisticsResponseDto.class);
assertThat(stats.getTimeBlockSummaries()).hasSize(2);
List<TimeBlockSummaryResponseDto> summaries = stats.getTimeBlockSummaries();
assertThat(summaries.get(0).getTotalSeconds()).isEqualTo(32400L);
assertThat(summaries.get(0).getMeetingCount()).isEqualTo(1);
assertThat(summaries.get(1).getTotalSeconds()).isNull();
assertThat(summaries.get(1).getMeetingCount()).isEqualTo(0);
}
@Test
public void testTimeBlockSummaryDefault() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-18T00:00:00.000Z");
String url = String.format("/statistics/summary/%s/%s", start, end);
val stats = getTypedResult(url, TimeBlockSummaryResponseDto.class);
assertThat(stats.getMeetingCount()).isEqualTo(2);
assertThat(stats.getTotalSeconds()).isEqualTo(18000);
}
@Test
public void testTimeBlockSummaryInternal() throws Exception {
Instant start = Instant.parse("2020-11-01T00:00:00.000Z");
Instant end = Instant.parse("2020-11-18T00:00:00.000Z");
String url = String.format("/statistics/summary/%s/%s?filter=%s", start, end, StatisticsFilterDte.Internal);
val stats = getTypedResult(url, TimeBlockSummaryResponseDto.class);
assertThat(stats.getMeetingCount()).isEqualTo(2);
assertThat(stats.getTotalSeconds()).isEqualTo(39600);
}
@Test
public void getIndividualStatistics() throws Exception {
var employeeId = UUID.fromString("f66d66d7-7b40-4ffe-a38a-aae70919a1ef");
var start = Instant.parse("2020-11-01T00:00:00.000Z");
var end = Instant.parse("2020-11-08T00:00:00.000Z");
var url = String.format("/statistics/individual/%s/%s/%s", employeeId, start, end);
mvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionTenant.HEADER_KEY, "s56_net")
.with(jwt().jwt(getJWT("bob@s56.net")).authorities(new SimpleGrantedAuthority("admin"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.totalSeconds").exists())
.andExpect(jsonPath("$.totalSeconds").value(21600))
.andExpect(jsonPath("$.meetingCount").exists())
.andExpect(jsonPath("$.meetingCount").value(3))
.andExpect(jsonPath("$.start").exists())
.andExpect(jsonPath("$.start").value(start.toString()))
.andExpect(jsonPath("$.end").exists())
.andExpect(jsonPath("$.end").value(end.toString()));
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server.reactive;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.PooledByteBufAllocator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.core.testfixture.io.buffer.LeakAwareDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link HttpHeadResponseDecorator}.
*
* @author Rossen Stoyanchev
*/
class HttpHeadResponseDecoratorTests {
private final LeakAwareDataBufferFactory bufferFactory =
new LeakAwareDataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT));
private final ServerHttpResponse response =
new HttpHeadResponseDecorator(new MockServerHttpResponse(this.bufferFactory));
@AfterEach
void tearDown() {
this.bufferFactory.checkForLeaks();
}
@Test
void writeWithFlux() {
Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2"));
this.response.writeWith(body).block();
assertThat(this.response.getHeaders().getContentLength()).isEqualTo(-1);
}
@Test
void writeWithMono() {
Mono<DataBuffer> body = Mono.just(toDataBuffer("data1,data2"));
this.response.writeWith(body).block();
assertThat(this.response.getHeaders().getContentLength()).isEqualTo(11);
}
@Test // gh-23484
void writeWithGivenContentLength() {
int length = 15;
this.response.getHeaders().setContentLength(length);
this.response.writeWith(Flux.empty()).block();
assertThat(this.response.getHeaders().getContentLength()).isEqualTo(length);
}
@Test // gh-25908
void writeWithGivenTransferEncoding() {
Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2"));
this.response.getHeaders().add(HttpHeaders.TRANSFER_ENCODING, "chunked");
this.response.writeWith(body).block();
assertThat(this.response.getHeaders().getContentLength()).isEqualTo(-1);
}
private DataBuffer toDataBuffer(String s) {
DataBuffer buffer = this.bufferFactory.allocateBuffer(256);
buffer.write(s.getBytes(StandardCharsets.UTF_8));
return buffer;
}
}
|
package com.esum.web.apps.hotdeploy.controller;
import java.util.List;
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 com.esum.appetizer.config.Configurer;
import com.esum.appetizer.controller.AbstractController;
import com.esum.appetizer.util.PageUtil;
import com.esum.web.apps.hotdeploy.service.HotDeployService;
import com.esum.web.apps.hotdeploy.vo.NodeInfo;
import com.esum.web.apps.hotdeploy.vo.UserAppsInfo;
@Controller
public class HotDeployController extends AbstractController{
@Autowired
private HotDeployService hotDeployService;
//리스트
@RequestMapping("/system/hotDeploy/appList")
public String hotDeployAppList(Model model,
String nodeId,
String appName,
String status,
String currentPage,
String pageType,
String P_currentPage, //부모 검색 파라미터
String P_nodeId,
String P_appName,
String P_status
){
if(currentPage == null){
currentPage = "1";
status = "ALL";
}
if(pageType != null){
currentPage = P_currentPage;
nodeId = P_nodeId;
appName = P_appName;
status = P_status;
}
UserAppsInfo userAppsInfo = new UserAppsInfo();
//파라미터 셋팅
userAppsInfo.setNodeId(nodeId);
userAppsInfo.setAppName(appName);
userAppsInfo.setStatus(status);
int totalCount=hotDeployService.getTotalCountUserAppsInfo(userAppsInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<UserAppsInfo> list = hotDeployService.selectListUserAppsInfo(userAppsInfo,pageUtil);
model.addAttribute("list",list);
model.addAttribute("userAppsInfo",userAppsInfo);
model.addAttribute("pageUtil",pageUtil);
return "/system/hotDeploy/hotDeployAppList";
}
//상세보기
@RequestMapping("/system/hotDeploy/info")
public String appInfo(
String nodeId,
String appName,
String appVersion,
String result,
String P_currentPage, //부모 검색 파라미터
String P_nodeId,
String P_appName,
String P_status,
Model model
){
UserAppsInfo param = new UserAppsInfo();
param.setNodeId(nodeId);
param.setAppName(appName);
param.setAppVersion(appVersion);
UserAppsInfo info = hotDeployService.selectUserAppsInfo(param);
if(result != null)
model.addAttribute("result", result);
model.addAttribute("info",info);
model.addAttribute("P_nodeId", P_nodeId);
model.addAttribute("P_appName", P_appName);
model.addAttribute("P_status", P_status);
model.addAttribute("P_currentPage", P_currentPage);
return "/system/hotDeploy/hotDeployInfo";
}
//수정하기 실행
@RequestMapping("/system/hotDeploy/appInfoUpdate")
public String appInfoUpdate(
String nodeId,
String appName,
String appVersion,
String description,
String P_currentPage, //부모 검색 파라미터
String P_nodeId,
String P_appName,
String P_status
){
UserAppsInfo userAppsInfo = new UserAppsInfo();
userAppsInfo.setNodeId(nodeId);
userAppsInfo.setAppName(appName);
userAppsInfo.setAppVersion(appVersion);
userAppsInfo.setDescription(description);
boolean result = false;
if(hotDeployService.updateUserAppsInfo(userAppsInfo) > 0){
result = true;
}
return "redirect:/system/hotDeploy/info?nodeId="+nodeId+"&appName="+appName+"&appVersion="+appVersion+"&result="+result+"&P_currentPage="+P_currentPage+"&P_nodeId="+P_nodeId+"&P_appName="+P_appName+"&P_status="+P_status;
}
//신규등록 화면
@RequestMapping("/system/hotDeploy/appAdd")
public String appAdd(){
return "/system/hotDeploy/hotDeployAdd";
}
//노드 선택 팝업창
@RequestMapping("/system/hotDeploy/nodeInfoListPopup")
public String nodeInfoList(Model model,
String currentPage,
String fieldId
){
if(currentPage == null) currentPage = "1";
int totalCount=hotDeployService.getTotalCountNodeInfo();
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), 5, 5, totalCount);
List<NodeInfo> list = hotDeployService.selecListNodeInfo(pageUtil);
model.addAttribute("list",list);
model.addAttribute("pageUtil",pageUtil);
model.addAttribute("fieldId",fieldId);
return "/system/hotDeploy/nodeInfoListPopup";
}
//버전관리 화면
@RequestMapping("/system/hotDeploy/versionUpdate")
public String versionUpdate(){
return "/system/hotDeploy/hotDeployUpdate";
}
//App선택 팝업창
@RequestMapping("/system/hotDeploy/appListPopup")
public String hotDeployAppListPopup(Model model,
String nodeId,
String appName,
String status,
String currentPage){
if(currentPage == null){
currentPage = "1";
status = "ALL";
}
UserAppsInfo userAppsInfo = new UserAppsInfo();
//파라미터 셋팅
userAppsInfo.setNodeId(nodeId);
userAppsInfo.setAppName(appName);
userAppsInfo.setStatus(status);
int totalCount=hotDeployService.getTotalCountHotDeployAppListPopup(userAppsInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<UserAppsInfo> list = hotDeployService.selectListHotDeployAppListPopup(userAppsInfo,pageUtil);
model.addAttribute("list",list);
model.addAttribute("userAppsInfo",userAppsInfo);
model.addAttribute("pageUtil",pageUtil);
return "/system/hotDeploy/hotDeployAppListPopup";
}
//App 중복체크
@RequestMapping("/system/hotDeploy/appDupCheck")
public String appDupCheck(Model model,
String appName,
String appVersion){
int returnCode = hotDeployService.appDupCheck(appName, appVersion);
model.addAttribute("appName",appName);
model.addAttribute("appVersion",appVersion);
model.addAttribute("returnCode",returnCode);
return "/system/hotDeploy/appDupCheck";
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server;
import java.io.IOException;
import java.io.OutputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.util.Assert;
/**
* Implementation of {@code ServerHttpResponse} that delegates all calls to a
* given target {@code ServerHttpResponse}.
*
* @author Arjen Poutsma
* @since 5.3.2
*/
public class DelegatingServerHttpResponse implements ServerHttpResponse {
private final ServerHttpResponse delegate;
/**
* Create a new {@code DelegatingServerHttpResponse}.
* @param delegate the response to delegate to
*/
public DelegatingServerHttpResponse(ServerHttpResponse delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
/**
* Returns the target response that this response delegates to.
* @return the delegate
*/
public ServerHttpResponse getDelegate() {
return this.delegate;
}
@Override
public void setStatusCode(HttpStatusCode status) {
this.delegate.setStatusCode(status);
}
@Override
public void flush() throws IOException {
this.delegate.flush();
}
@Override
public void close() {
this.delegate.close();
}
@Override
public OutputStream getBody() throws IOException {
return this.delegate.getBody();
}
@Override
public HttpHeaders getHeaders() {
return this.delegate.getHeaders();
}
}
|
package jhotel;
import java.util.*;
import java.text.*;
import java.util.regex.*;
/**
* Class ini merupakan class yang digunakan untuk mengeset data Customer
*
* @author Whisnu Samudra
* @version 1/3/2018
*/
public class Customer
{
// instance variables - replace the example below with your own
private int id;
private String nama;
private String email;
private Date dob;
private String password;
SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy");
/**
* Constructor for objects of class Customer
*/
public Customer (String nama, int year, int month, int date, String email, String password)
{
this.id=DatabaseCustomer.getLastCustomerId()+1;
this.nama=nama;
this.dob=new GregorianCalendar(year,month,date).getTime();
this.email=email;
this.password=password;
}
public Customer (String nama,Date dob, String email)
{
this.id=DatabaseCustomer.getLastCustomerId()+1;
this.nama=nama;
this.dob=dob;
this.email=email;
}
/**
* Method untuk mendapatkan ID yang telah diset
*
*
* @return id type integer
*/
public int getID()
{
return id;
}
/**
* Method untuk mendapatkan nama yang telah diset
*
*
* @return nama type String
*/
public String getNama()
{
return nama;
}
/**
* Method untuk mendapatkan email yang telah diset
*
*
* @return email type String
*/
public String getEmail()
{
return email;
}
/**
* Method untuk mendapatkan tanggal lahir yang telah diset
*
*
* @return dob type Date
*/
public Date getDOB()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
System.out.println("DOB: " + dateFormat.format(dob));
return dob;
}
public String getPassword()
{
return password;
}
/**
* Method untuk mengeset ID
*
* @param id type integer
*
*/
public void setID (int id)
{
this.id=id; //untuk mengeset ID Customer
}
/**
* Method untuk mengeset nama
*
* @param nama type String
*
*/
public void setNama(String nama)
{
this.nama=nama;
}
/**
* Method untuk mengeset email
*
* @param email type String
*
*/
public void setEmail(String email)
{
Pattern ptr = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
System.out.println(email + " is " + (ptr.matcher(email).matches() ? "valid" : "invalid"));
}
public void setPassword(String password)
{
this.password=password;
}
/**
* Method untuk mengeset tanggal lahir
*
* @param dob type Date
*
*/
public void setDOB(Date dob)
{
this.dob=dob;
}
/**
* Method untuk mencetak identitas pelanggan
*
* @param
*
*/
public String toString()
{
if(DatabasePesanan.getPesananAktif(this)==null)
{
return("\nCustomer ID : " +getID() +
"\nName: " + getNama() +
"\nEmail: " + getEmail() +
"\nDOB = " + df.format(getDOB()));
}
else
{
return("\nCustomer ID : " +getID() +
"\nName: " + getNama() +
"\nEmail: " + getEmail() +
"\nDOB = " + df.format(getDOB()) +
"\nBooking order is in progress");
}
}
}
|
package com.roundarch.entity;
import java.util.Map;
public class TotalStatistic {
private Map<String, Integer> values;
public Map<String, Integer> getValues() {
return values;
}
public void setValues(Map<String, Integer> values) {
this.values = values;
}
}
|
package com.example.coronavirus;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void mostrarPaciente(View view){
Intent intentMostrarPaciente = new Intent(this, MostrarPaciente.class);
startActivity(intentMostrarPaciente);
}
public void verEstatisticas (View view){
Intent intentEstatistica = new Intent(this, DisplayVerEstatistica.class);
startActivity(intentEstatistica);
}
public void mostrarSuspeito(View view){
Intent intentMostrarSuspeitos = new Intent(this, MostrarSuspeito.class);
startActivity(intentMostrarSuspeitos);
}
}
|
package com.u_anywhere.mappers;
import com.u_anywhere.base.MultipleIdMapper;
import com.u_anywhere.model.TestPrintexpressno;
public interface TestPrintexpressnoMapper extends MultipleIdMapper<TestPrintexpressno> {
} |
/*
* File : NameItem.java
* Created : 24 nov. 2003
* By : Olivier
*
* Copyright (C) 2004, 2005, 2006 Aelitis SAS, All rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* AELITIS, SAS au capital de 46,603.30 euros,
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*/
package com.aelitis.azureus.ui.swt.columns.torrent;
import java.io.File;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.gudy.azureus2.core3.config.COConfigurationManager;
import org.gudy.azureus2.core3.config.ParameterListener;
import org.gudy.azureus2.core3.disk.DiskManagerFileInfo;
import org.gudy.azureus2.core3.download.DownloadManager;
import org.gudy.azureus2.core3.download.DownloadManagerState;
import org.gudy.azureus2.core3.torrent.TOTorrent;
import org.gudy.azureus2.core3.util.Constants;
import org.gudy.azureus2.core3.util.Debug;
import org.gudy.azureus2.plugins.download.Download;
import org.gudy.azureus2.plugins.ui.UIInputReceiver;
import org.gudy.azureus2.plugins.ui.UIInputReceiverListener;
import org.gudy.azureus2.plugins.ui.menus.MenuItem;
import org.gudy.azureus2.plugins.ui.menus.MenuItemFillListener;
import org.gudy.azureus2.plugins.ui.menus.MenuItemListener;
import org.gudy.azureus2.plugins.ui.tables.*;
import org.gudy.azureus2.ui.swt.ImageRepository;
import org.gudy.azureus2.ui.swt.SimpleTextEntryWindow;
import org.gudy.azureus2.ui.swt.debug.ObfusticateCellText;
import org.gudy.azureus2.ui.swt.shells.GCStringPrinter;
import org.gudy.azureus2.ui.swt.views.table.CoreTableColumnSWT;
import org.gudy.azureus2.ui.swt.views.table.TableCellSWT;
import org.gudy.azureus2.ui.swt.views.table.TableCellSWTPaintListener;
import com.aelitis.azureus.ui.common.table.TableCellCore;
import com.aelitis.azureus.ui.common.table.TableRowCore;
import com.aelitis.azureus.ui.swt.imageloader.ImageLoader;
import com.aelitis.azureus.ui.swt.utils.TorrentUIUtilsV3;
import com.aelitis.azureus.ui.swt.utils.TorrentUIUtilsV3.ContentImageLoadedListener;
/** Torrent name cell for My Torrents.
*
* @author Olivier
* @author TuxPaper (2004/Apr/17: modified to TableCellAdapter)
*/
public class ColumnThumbAndName
extends CoreTableColumnSWT
implements TableCellLightRefreshListener, ObfusticateCellText,
TableCellDisposeListener, TableCellSWTPaintListener,
TableCellClipboardListener, TableCellMouseMoveListener
{
public static final Class<?>[] DATASOURCE_TYPES = {
Download.class,
org.gudy.azureus2.plugins.disk.DiskManagerFileInfo.class
};
public static final String COLUMN_ID = "name";
private static final String ID_EXPANDOHITAREA = "expandoHitArea";
private static final String ID_EXPANDOHITAREASHOW = "expandoHitAreaShow";
private static final boolean NEVER_SHOW_TWISTY =
!COConfigurationManager.getBooleanParameter("Table.useTree");
private boolean showIcon;
public void fillTableColumnInfo(TableColumnInfo info) {
info.addCategories(new String[] {
CAT_ESSENTIAL,
CAT_CONTENT
});
info.setProficiency(TableColumnInfo.PROFICIENCY_BEGINNER);
}
/**
*
* @param sTableID
*/
public ColumnThumbAndName(String sTableID) {
super(COLUMN_ID, 250, sTableID);
setAlignment(ALIGN_LEAD);
addDataSourceTypes(DATASOURCE_TYPES);
setObfustication(true);
setRefreshInterval(INTERVAL_LIVE);
initializeAsGraphic(250);
setMinWidth(100);
TableContextMenuItem menuItem = addContextMenuItem("MyTorrentsView.menu.rename.displayed");
menuItem.addMultiListener(new MenuItemListener() {
public void selected(MenuItem menu, Object target) {
if (target == null) {
return;
}
Object[] o = (Object[]) target;
for (Object object : o) {
if (object instanceof DownloadManager) {
final DownloadManager dm = (DownloadManager) object;
String msg_key_prefix = "MyTorrentsView.menu.rename.displayed.enter.";
SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow(
msg_key_prefix + "title", msg_key_prefix + "message");
entryWindow.setPreenteredText(dm.getDisplayName(), false);
entryWindow.prompt(new UIInputReceiverListener() {
public void UIInputReceiverClosed(UIInputReceiver entryWindow) {
if (!entryWindow.hasSubmittedInput()) {
return;
}
String value = entryWindow.getSubmittedInput();
if (value != null && value.length() > 0) {
dm.getDownloadState().setDisplayName(value);
}
}
});
}
}
}
});
TableContextMenuItem menuShowIcon = addContextMenuItem(
"ConfigView.section.style.showProgramIcon", MENU_STYLE_HEADER);
menuShowIcon.setStyle(TableContextMenuItem.STYLE_CHECK);
menuShowIcon.addFillListener(new MenuItemFillListener() {
public void menuWillBeShown(MenuItem menu, Object data) {
menu.setData(new Boolean(showIcon));
}
});
final String CFG_SHOWPROGRAMICON = "NameColumn.showProgramIcon."
+ getTableID();
menuShowIcon.addMultiListener(new MenuItemListener() {
public void selected(MenuItem menu, Object target) {
COConfigurationManager.setParameter(CFG_SHOWPROGRAMICON,
((Boolean) menu.getData()).booleanValue());
}
});
COConfigurationManager.addAndFireParameterListener(CFG_SHOWPROGRAMICON,
new ParameterListener() {
public void parameterChanged(String parameterName) {
setShowIcon(COConfigurationManager.getBooleanParameter(
CFG_SHOWPROGRAMICON,
COConfigurationManager.getBooleanParameter("NameColumn.showProgramIcon")));
}
});
}
public void reset() {
super.reset();
COConfigurationManager.removeParameter("NameColumn.showProgramIcon."
+ getTableID());
}
public void refresh(TableCell cell) {
refresh(cell, false);
}
public void refresh(TableCell cell, boolean sortOnlyRefresh) {
String name = null;
Object ds = cell.getDataSource();
if (ds instanceof DiskManagerFileInfo) {
DiskManagerFileInfo fileInfo = (DiskManagerFileInfo) ds;
if (fileInfo.isSkipped()
&& (fileInfo.getStorageType() == DiskManagerFileInfo.ST_COMPACT || fileInfo.getStorageType() == DiskManagerFileInfo.ST_REORDER_COMPACT)) {
TableRowCore row = (TableRowCore) cell.getTableRow();
if (row != null) {
row.getParentRowCore().removeSubRow(ds);
}
}
return;
}
DownloadManager dm = (DownloadManager) ds;
if (dm != null) {
name = dm.getDisplayName();
}
if (name == null) {
name = "";
}
cell.setSortValue(name);
}
public void cellPaint(GC gc, final TableCellSWT cell) {
Object ds = cell.getDataSource();
if (ds instanceof DiskManagerFileInfo) {
cellPaintFileInfo(gc, cell, (DiskManagerFileInfo) ds);
return;
}
Rectangle cellBounds = cell.getBounds();
int textX = cellBounds.x;
TableRowCore rowCore = cell.getTableRowCore();
if (rowCore != null) {
int numSubItems = rowCore.getSubItemCount();
int paddingX = 3;
int width = 7;
boolean show_twisty;
if ( NEVER_SHOW_TWISTY ){
show_twisty = false;
}else if (numSubItems > 1 ){
show_twisty = true;
}else{
Boolean show = (Boolean)rowCore.getData( ID_EXPANDOHITAREASHOW );
if ( show == null ){
DownloadManager dm = (DownloadManager)ds;
TOTorrent torrent = dm.getTorrent();
show_twisty = torrent != null && !dm.getTorrent().isSimpleTorrent();
rowCore.setData( ID_EXPANDOHITAREASHOW, new Boolean( show_twisty ));
}else{
show_twisty = show;
}
}
if (show_twisty) {
int middleY = cellBounds.y + (cellBounds.height / 2) - 1;
int startX = cellBounds.x + paddingX;
int halfHeight = 2;
Color bg = gc.getBackground();
gc.setBackground(gc.getForeground());
gc.setAntialias(SWT.ON);
gc.setAdvanced(true);
if (rowCore.isExpanded()) {
gc.fillPolygon(new int[] {
startX,
middleY - halfHeight,
startX + width,
middleY - halfHeight,
startX + (width / 2),
middleY + (halfHeight * 2) + 1
});
} else {
gc.fillPolygon(new int[] {
startX,
middleY - halfHeight,
startX + width,
middleY + halfHeight,
startX,
middleY + (halfHeight * 2) + 1
});
}
gc.setBackground(bg);
Rectangle hitArea = new Rectangle(paddingX, middleY - halfHeight
- cellBounds.y, width, (halfHeight * 4) + 1);
rowCore.setData(ID_EXPANDOHITAREA, hitArea);
}
if (!NEVER_SHOW_TWISTY) {
cellBounds.x += paddingX * 2 + width;
cellBounds.width -= paddingX * 2 + width;
}
}
if (!showIcon) {
cellBounds.x += 2;
cellBounds.width -= 4;
cellPaintName(cell, gc, cellBounds, cellBounds.x);
return;
}
Image[] imgThumbnail = TorrentUIUtilsV3.getContentImage(ds,
cellBounds.height >= 20, new ContentImageLoadedListener() {
public void contentImageLoaded(Image image, boolean wasReturned) {
if (!wasReturned) {
// this may be triggered many times, so only invalidate and don't
// force a refresh()
cell.invalidate();
}
}
});
if (imgThumbnail != null && ImageLoader.isRealImage(imgThumbnail[0])) {
try {
if (cellBounds.height > 30) {
cellBounds.y += 1;
cellBounds.height -= 3;
}
Rectangle imgBounds = imgThumbnail[0].getBounds();
int dstWidth;
int dstHeight;
if (imgBounds.height > cellBounds.height) {
dstHeight = cellBounds.height;
dstWidth = imgBounds.width * cellBounds.height / imgBounds.height;
} else if (imgBounds.width > cellBounds.width) {
dstWidth = cellBounds.width - 4;
dstHeight = imgBounds.height * cellBounds.width / imgBounds.width;
} else {
dstWidth = imgBounds.width;
dstHeight = imgBounds.height;
}
if (cellBounds.height <= 18) {
dstWidth = Math.min(dstWidth, cellBounds.height);
dstHeight = Math.min(dstHeight, cellBounds.height);
if (imgBounds.width > 16) {
cellBounds.y++;
dstHeight -= 2;
}
}
try {
gc.setAdvanced(true);
gc.setInterpolation(SWT.HIGH);
} catch (Exception e) {
}
int x = cellBounds.x;
textX = x + dstWidth + 3;
int minWidth = dstHeight * 7 / 4;
int imgPad = 0;
if (dstHeight > 25) {
if (dstWidth < minWidth) {
imgPad = ((minWidth - dstWidth + 1) / 2);
x = cellBounds.x + imgPad;
textX = cellBounds.x + minWidth + 3;
}
}
if (cellBounds.width - dstWidth - (imgPad * 2) < 100 && dstHeight > 18) {
dstWidth = Math.min(32, dstHeight);
x = cellBounds.x + ((32 - dstWidth + 1) / 2);
dstHeight = imgBounds.height * dstWidth / imgBounds.width;
textX = cellBounds.x + dstWidth + 3;
}
int y = cellBounds.y + ((cellBounds.height - dstHeight + 1) / 2);
if (dstWidth > 0 && dstHeight > 0 && !imgBounds.isEmpty()) {
//Rectangle dst = new Rectangle(x, y, dstWidth, dstHeight);
Rectangle lastClipping = gc.getClipping();
try {
gc.setClipping(cellBounds);
boolean hack_adv = Constants.isWindows8OrHigher && gc.getAdvanced();
if ( hack_adv ){
// problem with icon transparency on win8
gc.setAdvanced( false );
}
for (int i = 0; i < imgThumbnail.length; i++) {
Image image = imgThumbnail[i];
if (image == null || image.isDisposed()) {
continue;
}
Rectangle srcBounds = image.getBounds();
if (i == 0) {
int w = dstWidth;
int h = dstHeight;
if (imgThumbnail.length > 1) {
w = w * 9 / 10;
h = h * 9 / 10;
}
gc.drawImage(image, srcBounds.x, srcBounds.y, srcBounds.width,
srcBounds.height, x, y, w, h);
} else {
int w = dstWidth * 3 / 8;
int h = dstHeight * 3 / 8;
gc.drawImage(image, srcBounds.x, srcBounds.y, srcBounds.width,
srcBounds.height, x + dstWidth - w, y + dstHeight - h, w, h);
}
}
if ( hack_adv ){
gc.setAdvanced( true );
}
} catch (Exception e) {
Debug.out(e);
} finally {
gc.setClipping(lastClipping);
}
}
TorrentUIUtilsV3.releaseContentImage(ds);
} catch (Throwable t) {
Debug.out(t);
}
}
cellPaintName(cell, gc, cellBounds, textX);
}
private void cellPaintFileInfo(GC gc, final TableCellSWT cell,
DiskManagerFileInfo fileInfo) {
Rectangle cellBounds = cell.getBounds();
//System.out.println(cellArea);
int padding = 5 + (true ? cellBounds.height : 0);
cellBounds.x += padding;
cellBounds.width -= padding;
int textX = cellBounds.x;
Image[] imgThumbnail = { ImageRepository.getPathIcon(fileInfo.getFile(true).getPath(),
cellBounds.height >= 20, false) };
if (imgThumbnail != null && ImageLoader.isRealImage(imgThumbnail[0])) {
try {
if (cellBounds.height > 30) {
cellBounds.y += 1;
cellBounds.height -= 3;
}
Rectangle imgBounds = imgThumbnail[0].getBounds();
int dstWidth;
int dstHeight;
if (imgBounds.height > cellBounds.height) {
dstHeight = cellBounds.height;
dstWidth = imgBounds.width * cellBounds.height / imgBounds.height;
} else if (imgBounds.width > cellBounds.width) {
dstWidth = cellBounds.width - 4;
dstHeight = imgBounds.height * cellBounds.width / imgBounds.width;
} else {
dstWidth = imgBounds.width;
dstHeight = imgBounds.height;
}
if (cellBounds.height <= 18) {
dstWidth = Math.min(dstWidth, cellBounds.height);
dstHeight = Math.min(dstHeight, cellBounds.height);
if (imgBounds.width > 16) {
cellBounds.y++;
dstHeight -= 2;
}
}
try {
gc.setAdvanced(true);
gc.setInterpolation(SWT.HIGH);
} catch (Exception e) {
}
int x = cellBounds.x;
textX = x + dstWidth + 3;
int minWidth = dstHeight;
int imgPad = 0;
if (dstHeight > 25) {
if (dstWidth < minWidth) {
imgPad = ((minWidth - dstWidth + 1) / 2);
x = cellBounds.x + imgPad;
textX = cellBounds.x + minWidth + 3;
}
}
if (cellBounds.width - dstWidth - (imgPad * 2) < 100 && dstHeight > 18) {
dstWidth = Math.min(32, dstHeight);
x = cellBounds.x + ((32 - dstWidth + 1) / 2);
dstHeight = imgBounds.height * dstWidth / imgBounds.width;
textX = cellBounds.x + dstWidth + 3;
}
int y = cellBounds.y + ((cellBounds.height - dstHeight + 1) / 2);
if (dstWidth > 0 && dstHeight > 0 && !imgBounds.isEmpty()) {
//Rectangle dst = new Rectangle(x, y, dstWidth, dstHeight);
Rectangle lastClipping = gc.getClipping();
try {
gc.setClipping(cellBounds);
boolean hack_adv = Constants.isWindows8OrHigher && gc.getAdvanced();
if ( hack_adv ){
// problem with icon transparency on win8
gc.setAdvanced( false );
}
for (int i = 0; i < imgThumbnail.length; i++) {
Image image = imgThumbnail[i];
if (image == null || image.isDisposed()) {
continue;
}
Rectangle srcBounds = image.getBounds();
if (i == 0) {
int w = dstWidth;
int h = dstHeight;
if (imgThumbnail.length > 1) {
w = w * 9 / 10;
h = h * 9 / 10;
}
gc.drawImage(image, srcBounds.x, srcBounds.y, srcBounds.width,
srcBounds.height, x, y, w, h);
} else {
int w = dstWidth * 3 / 8;
int h = dstHeight * 3 / 8;
gc.drawImage(image, srcBounds.x, srcBounds.y, srcBounds.width,
srcBounds.height, x + dstWidth - w, y + dstHeight - h, w, h);
}
}
if ( hack_adv ){
gc.setAdvanced( true );
}
} catch (Exception e) {
Debug.out(e);
} finally {
gc.setClipping(lastClipping);
}
}
} catch (Throwable t) {
Debug.out(t);
}
}
String prefix = fileInfo.getDownloadManager().getSaveLocation().toString();
String s = fileInfo.getFile(true).toString();
if (s.startsWith(prefix)) {
s = s.substring(prefix.length() + 1);
}
if ( fileInfo.isSkipped()){
String dnd_sf = fileInfo.getDownloadManager().getDownloadState().getAttribute( DownloadManagerState.AT_DND_SUBFOLDER );
if ( dnd_sf != null ){
dnd_sf = dnd_sf.trim();
if ( dnd_sf.length() > 0 ){
dnd_sf += File.separatorChar;
int pos = s.indexOf( dnd_sf );
if ( pos != -1 ){
s = s.substring( 0, pos ) + s.substring( pos + dnd_sf.length());
}
}
}
}
cellBounds.width -= (textX - cellBounds.x);
cellBounds.x = textX;
boolean over = GCStringPrinter.printString(gc, s, cellBounds, true, false,
SWT.LEFT | SWT.WRAP);
cell.setToolTip(over ? null : s);
}
private void cellPaintName(TableCell cell, GC gc, Rectangle cellBounds,
int textX) {
String name = null;
Object ds = cell.getDataSource();
if (ds instanceof DiskManagerFileInfo) {
return;
}
DownloadManager dm = (DownloadManager) ds;
if (dm != null)
name = dm.getDisplayName();
if (name == null)
name = "";
boolean over = GCStringPrinter.printString(gc, name, new Rectangle(textX,
cellBounds.y, cellBounds.x + cellBounds.width - textX,
cellBounds.height), true, true, getTableID().endsWith( ".big" )?SWT.WRAP:SWT.NULL );
cell.setToolTip(over ? null : name);
}
public String getObfusticatedText(TableCell cell) {
String name = null;
Object ds = cell.getDataSource();
if (ds instanceof DiskManagerFileInfo) {
return null;
}
DownloadManager dm = (DownloadManager) ds;
if (dm != null) {
name = dm.toString();
int i = name.indexOf('#');
if (i > 0) {
name = name.substring(i + 1);
}
}
if (name == null)
name = "";
return name;
}
public void dispose(TableCell cell) {
}
/**
* @param showIcon the showIcon to set
*/
public void setShowIcon(boolean showIcon) {
this.showIcon = showIcon;
invalidateCells();
}
/**
* @return the showIcon
*/
public boolean isShowIcon() {
return showIcon;
}
public String getClipboardText(TableCell cell) {
String name = null;
Object ds = cell.getDataSource();
if (ds instanceof DiskManagerFileInfo) {
return null;
}
DownloadManager dm = (DownloadManager) ds;
if (dm != null)
name = dm.getDisplayName();
if (name == null)
name = "";
return name;
}
public void cellMouseTrigger(TableCellMouseEvent event) {
if (event.eventType == TableCellMouseEvent.EVENT_MOUSEMOVE
|| event.eventType == TableRowMouseEvent.EVENT_MOUSEDOWN) {
TableRow row = event.cell.getTableRow();
if (row == null) {
return;
}
Object data = row.getData(ID_EXPANDOHITAREA);
if (data instanceof Rectangle) {
Rectangle hitArea = (Rectangle) data;
boolean inExpando = hitArea.contains(event.x, event.y);
if (event.eventType == TableCellMouseEvent.EVENT_MOUSEMOVE) {
((TableCellCore) event.cell).setCursorID(inExpando ? SWT.CURSOR_HAND
: SWT.CURSOR_ARROW);
} else if (inExpando) { // mousedown
if (row instanceof TableRowCore) {
TableRowCore rowCore = (TableRowCore) row;
rowCore.setExpanded(!rowCore.isExpanded());
}
}
}
}
}
}
|
package lab3;
import java.util.*;
public class FibonacciUser
{
public static void main (String[] args)
{
new FibonacciUser().run();
} // method main
/**
* The Fibonacci number of the integer entered has been printed.
*/
public void run()
{
final int SENTINEL = -1;
final String INPUT_PROMPT = "\n\nPlease enter the " +
"positive integer whose Fibonacci number you want (or " +
SENTINEL + " to quit): ";
final String FIBONACCI_MESSAGE = "\nIts Fibonacci number is ";
Scanner sc = new Scanner (System.in);
final String MESSAGE_1 = "The elapsed time was ";
final double NANO_FACTOR = 1000000000.0; // nanoseconds per second
final String MESSAGE_2 = " seconds.";
long startTime,
finishTime,
elapsedTime;
int n;
while (true)
{
try
{
System.out.print (INPUT_PROMPT);
n = sc.nextInt();
if (n == SENTINEL)
break;
System.out.println ("int = " + n );
startTime = System.nanoTime();
System.out.println ("iter fib: " + iterFib (n) );
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println (MESSAGE_1 + (elapsedTime / NANO_FACTOR) + MESSAGE_2);
startTime = System.nanoTime();
System.out.println ("orig fib: " + origFib(n) );
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println (MESSAGE_1 + (elapsedTime / NANO_FACTOR) + MESSAGE_2);
startTime = System.nanoTime();
System.out.println ("form fib: " + formFib(n) );
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println (MESSAGE_1 + (elapsedTime / NANO_FACTOR) + MESSAGE_2);
startTime = System.nanoTime();
System.out.println ("my fib: " + wrapMyFib(n));
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
System.out.println (MESSAGE_1 + (elapsedTime / NANO_FACTOR) + MESSAGE_2);
}//try
catch (Exception e)
{
System.out.println (e);
sc.nextLine();
}//catch Exception
}//while
} // method run
/**
* The Fibonacci number of the int n has been returned.
*
* @param n an int whose Fibinacci number will be returned.
* n > 0.
*
* @return a long containing the Fibonacci number of n.
*
* @throws IllegalArgumentException - if n <= 0 or > 92 (note
* that fib (93) is larger than Long.MAX_VALUE).
*
*/
public static long iterFib (int n)
{
final int MAX_N = 92;
final String ERROR_MESSAGE = "\nThe number entered must be " +
"greater than 0 and at most " + MAX_N + ".";
long previous,
current,
temp;
if (n <= 0 || n > MAX_N)
throw new IllegalArgumentException (ERROR_MESSAGE);
if (n <= 2)
return 1;
previous = 1;
current = 1;
for (int i = 3; i <= n; i++)
{
temp = current;
current = current + previous;
previous = temp;
} // for
return current;
} //iterative fib
public static long origFib (int n)
{
final int MAX_N = 92;
final String ERROR_MESSAGE = "\nThe number entered must be " +
"greater than 0 and at most " + MAX_N + ".";
if (n <= 0 || n > MAX_N)
throw new IllegalArgumentException (ERROR_MESSAGE);
if (n <= 2 )
return 1;
return origFib(n - 1) + origFib(n - 2);
} //original fib
public static long formFib (int n)
{
final int MAX_N = 92;
final String ERROR_MESSAGE = "\nThe number entered must be " +
"greater than 0 and at most " + MAX_N + ".";
if (n <= 0 || n > MAX_N)
throw new IllegalArgumentException (ERROR_MESSAGE);
return (long)((1 / Math.sqrt (5)) *
(Math.pow((1 + Math.sqrt (5)) / 2, n)-
Math.pow((1 - Math.sqrt (5)) / 2, n)));
} //formula fib
public static long myFib(int n, long previous, long current) {
final int MAX_N = 92;
final String ERROR_MESSAGE = "\nThe number entered must be " +
"greater than 0 and at most " + MAX_N + ".";
if (n <= 0 || n > MAX_N)
throw new IllegalArgumentException (ERROR_MESSAGE);
if (n == 1){
return 1;
}else if (n == 2) {
return current;
}else {
return myFib(n - 1, current, previous + current);
}
} // my fib
public static long wrapMyFib(int n){
return myFib(n, 1, 1);
}
} // class FibonacciUser
|
package com.yourname.democalci;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
public class MainActivity extends AppCompatActivity {
Button btn0 , btndot, btnequal, btnclear, btnbract, btndele, btndivi, btn7, btn8, btn9, btn6, btn5, btn4, btn3, btn2, btn1, btnmulite, btnminis, btnpuls, btnpercent;
TextView clcinput, clcoutput;
String process;
boolean checkBracket = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btndot = findViewById(R.id.btndot);
btnequal = findViewById(R.id.btnequal);
btnclear = findViewById(R.id.btnclear);
btnbract = findViewById(R.id.btnbract);
btndele = findViewById(R.id.btndele);
btndivi = findViewById(R.id.btndivi);
btnmulite = findViewById(R.id.btnmulite);
btnminis = findViewById(R.id.btnminis);
btnpuls = findViewById(R.id.btnpuls);
btnpercent = findViewById(R.id.btnpercent);
clcinput = findViewById(R.id.clcinput);
clcoutput = findViewById(R.id.clcoutput);
btndot.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+".");
}
});
btnbract.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
if (checkBracket) {
process = clcinput.getText().toString();
clcinput.setText(process +")");
checkBracket = false;
}else {
process = clcinput.getText().toString();
clcinput.setText(process +"(");
checkBracket = true;
}
}
});
btnequal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
process = process.replaceAll("×","*");
process = process.replaceAll("%","/100");
process = process.replaceAll("÷","/");
org.mozilla.javascript.Context rhino = Context.enter();
rhino.setOptimizationLevel(-1);
String finalResult = "";
try {
Scriptable scriptable = rhino.initStandardObjects();
finalResult = rhino.evaluateString(scriptable, process, "javascript", 1, null).toString();
}catch (Exception e) {
finalResult="0";
}
clcoutput.setText(finalResult);
}
});
btndele.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = clcinput.getText().toString();
if(s.length() != 0) {
s = s.substring(0, s.length() -1);
clcinput.setText(s);
}
}
});
btnclear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clcinput.setText("");
clcoutput.setText("");
}
});
btndivi.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"÷");
}
});
btnminis.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"-");
}
});
btnmulite.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"×");
}
});
btnpuls.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"+");
}
});
btnpercent.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"%");
}
});
btn0.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
process = clcinput.getText().toString();
clcinput.setText(process+"9");
}
});
}
} |
package com.ma.pluginframework.domain.event;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
/**
* 群消息
*/
public class TroopMsgEvent extends PluginMsgEvent implements Parcelable {
private String groupName;
private List<PluginAtEntity> atList;
private long rand3;
/**
* 0文本 1图片 2闪照 3xml 4文本撤回 5图片撤回 6 json
*/
private int type;
public TroopMsgEvent(long currentUin, String extra, long msgId, long senderUin, String senderNick, long toUin, long time, String content, String groupName, List<PluginAtEntity> atList, long rand3, int type) {
super(currentUin, extra, msgId, senderUin, senderNick, toUin, time, content);
this.groupName = groupName;
this.atList = atList;
this.rand3 = rand3;
this.type = type;
}
protected TroopMsgEvent(Parcel in) {
super(in);
groupName = in.readString();
atList = in.createTypedArrayList(PluginAtEntity.CREATOR);
rand3 = in.readLong();
type = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(groupName);
dest.writeTypedList(atList);
dest.writeLong(rand3);
dest.writeInt(type);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<TroopMsgEvent> CREATOR = new Creator<TroopMsgEvent>() {
@Override
public TroopMsgEvent createFromParcel(Parcel in) {
return new TroopMsgEvent(in);
}
@Override
public TroopMsgEvent[] newArray(int size) {
return new TroopMsgEvent[size];
}
};
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public List<PluginAtEntity> getAtList() {
return atList;
}
public void setAtList(List<PluginAtEntity> atList) {
this.atList = atList;
}
public long getRand3() {
return rand3;
}
public void setRand3(long rand3) {
this.rand3 = rand3;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
//0文本 1图片 2闪照 3xml 4文本撤回 5图片撤回
String tn = "";
switch (type) {
case 0:
tn = "文本";
break;
case 1:
tn = "图片";
break;
case 2:
tn = "闪照";
break;
case 3:
tn = "XML";
break;
case 4:
tn = "文本撤回";
break;
case 5:
tn = "图片撤回";
break;
case 6:
tn = "JSON";
break;
}
return "GroupMsgEvent{" +
"groupName='" + groupName + '\'' +
"type='" + tn + '\'' +
", atList=" + atList +
", rand3=" + rand3 +
", type=" + type +
"} " + super.toString();
}
}
|
package com.example.ptljdf;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Main4Activity extends AppCompatActivity {
private EditText name, email_id, passwordcheck, mobile;
private FirebaseAuth mAuth;
private static final String TAG = "";
private ProgressBar progressBar;
private EditText Mobile;
private EditText User_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
TextView btnSignUp = (TextView) findViewById(R.id.login_page);
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, Main5Activity.class);
startActivity(intent);
}
});
mAuth = FirebaseAuth.getInstance();
email_id = (EditText) findViewById(R.id.input_email);
User_name = (EditText) findViewById(R.id.input_name);
Mobile = (EditText) findViewById(R.id.mobile);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
passwordcheck = (EditText) findViewById(R.id.input_password);
Button ahsignup = (Button) findViewById(R.id.btn_signup);
ahsignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = email_id.getText().toString();
String password = passwordcheck.getText().toString();
String name = User_name.getText().toString();
String mobile = Mobile.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter Eamil Id", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(), "Enter User Name", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(mobile)) {
Toast.makeText(getApplicationContext(), "Enter Mobile Number", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(Main4Activity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(Main4Activity.this, Main16Activity.class);
startActivity(intent);
finish();
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(Main4Activity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_1, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_bar_title) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@XmlRootElement
public class Product implements Serializable
{
int idProduct;
String productName;
double netPrice;
double grossPrice;
String description;
boolean isAvailable;
Set<Specimen> specimens = new HashSet<Specimen>();
@Id
@GeneratedValue
@XmlAttribute
public int getIdOrder()
{
return idProduct;
}
@OneToMany
public Set<Specimen> getSpecimens()
{
return specimens;
}
public String getProductName()
{
return productName;
}
public double getNetPrice()
{
return netPrice;
}
public double getGrossPrice()
{
return grossPrice;
}
public String getDescription()
{
return description;
}
public boolean getIsAvailable()
{
return isAvailable;
}
public void setProductName(String name)
{
productName = name;
}
public void setNetPrice(double price)
{
netPrice = price;
}
public void setGrossPrice(double price)
{
grossPrice = price;
}
public void setDescription(String desc)
{
description = desc;
}
public void setIsAvailable(boolean available)
{
isAvailable = available;
}
}
|
package com.zhicai.byteera.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zhicai.byteera.R;
import butterknife.ButterKnife;
/**
* Created by bing on 2015/4/15.
*/
public class KnowWeathDetailBottonLine extends RelativeLayout implements View.OnClickListener {
private ButtonLineClickListener mListener;
private ImageView praises;
private TextView tv_comment_num;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back:
mListener.onBackClick();
break;
case R.id.rl_prise_container:
mListener.onCommentClick();
break;
case R.id.praises:
mListener.onPraiseClick();
break;
case R.id.transpond:
mListener.onTranspondClick();
break;
case R.id.share:
mListener.onShareClick();
break;
}
}
public interface ButtonLineClickListener {
void onBackClick();
void onCommentClick();
void onPraiseClick();
void onTranspondClick();
void onShareClick();
}
public void setButtonLineClickListener(ButtonLineClickListener mListener) {
this.mListener = mListener;
}
private Context mContext;
public KnowWeathDetailBottonLine(Context context) {
this(context, null);
}
public KnowWeathDetailBottonLine(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public KnowWeathDetailBottonLine(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
private void init() {
View view = LayoutInflater.from(mContext).inflate(R.layout.know_wealth_botton_line, this, true);
ImageView back = ButterKnife.findById(view, R.id.back);
RelativeLayout rlPraiseContainer = ButterKnife.findById(view, R.id.rl_prise_container);
praises = ButterKnife.findById(view, R.id.praises);
ImageView transpond = ButterKnife.findById(view, R.id.transpond);
ImageView share = ButterKnife.findById(view, R.id.share);
tv_comment_num = ButterKnife.findById(view, R.id.tv_comment_num);
back.setOnClickListener(this);
rlPraiseContainer.setOnClickListener(this);
praises.setOnClickListener(this);
transpond.setOnClickListener(this);
share.setOnClickListener(this);
}
public ImageView getCollectionButtom() {
return praises;
}
public void setConmmentNum(String num) {
tv_comment_num.setText(num);
}
}
|
package dados;
import java.util.List;
import negocios.beans.MateriaPrima;
public interface IRepositorioMateriaPrima {
public boolean inserir(MateriaPrima materiaPrima);
public boolean alterar(MateriaPrima novaMateriaPrima);
public MateriaPrima buscar(int codigo);
public boolean remover(int codigo);
public boolean materiaPrimaContem(MateriaPrima materiaPrima);
public boolean existe(int codigo);
public abstract List<MateriaPrima> listar();
void salvarArquivo();
}
|
package be.darkshark.parkshark.service;
import be.darkshark.parkshark.domain.entity.person.Employee;
import be.darkshark.parkshark.domain.entity.util.Address;
import be.darkshark.parkshark.domain.entity.util.MailAddress;
import be.darkshark.parkshark.domain.entity.util.PhoneNumber;
import be.darkshark.parkshark.domain.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class CreateEmployees {
private EmployeeRepository employeeRepository;
@Autowired
public CreateEmployees(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
// Employee employee1 = new Employee("Paul", "WOWO",
// new Address("street", "22", 1000, "City"),
// new PhoneNumber("32", 11111),
// new MailAddress("email@email.com"));
// employeeRepository.save(employee1);
// System.out.println("EMPLOYEE CREATED");
}
}
|
package br.edu.puccampinas.projetoc.labirinto;
/**
* É uma posição de um labirinto, representada por uma linha e uma coluna (números do conjunto dos
* números naturais).
*
* @author aleph
*
*/
public class Coordenada {
private Integer linha;
private Integer coluna;
/**
* Constrói uma coordenada na origem (0,0) do plano cartesiano
*/
public Coordenada() {
this.linha = 0;
this.coluna = 0;
}
/**
* Constrói uma coordenada com a mesma posição de uma coordenada específica
*
* @param c Uma coordenada
*/
public Coordenada(Coordenada c) {
this.linha = c.getLinha();
this.coluna = c.getColuna();
}
/**
* Verifica se uma coordenada é válida ou não.
*
* @param x Representa o plano horizontal da coordenada
* @param y Representa o plano vertical da coordenada
* @throws IllegalArgumentException Caso X ou Y sejam números negativos
*/
private void valida(Integer x, Integer y) throws IllegalArgumentException {
if (x < 0) {
throw new IllegalArgumentException("Coordenada X inválida: " + x);
}
if (y < 0) {
throw new IllegalArgumentException("Coordenada Y inválida: " + y);
}
}
/**
* Constrói uma coordenada em uma posição específica do plano
*
* @param x Representa o plano horizontal da coordenada
* @param y Representa o plano vertical da coordenada
* @throws IllegalArgumentException Caso a coordenada tenha números negativos
*/
public Coordenada(Integer x, Integer y) throws IllegalArgumentException {
valida(x, y);
this.linha = x;
this.coluna = y;
}
/**
* Troca a posição de uma coordenada
*
* @param linha Representa o plano horizontal da coordenada
* @param coluna Representa o plano vertical da coordenada
* @throws IllegalArgumentException Caso a coordenada tenha números negativos
*/
public void setPosicao(Integer linha, Integer coluna) throws IllegalArgumentException {
valida(linha, coluna);
this.linha = linha;
this.coluna = coluna;
}
public Integer getLinha() {
return linha;
}
public Integer getColuna() {
return coluna;
}
@Override
public String toString() {
return "Coordenada [linha=" + linha + ", coluna=" + coluna + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((linha == null) ? 0 : linha.hashCode());
result = prime * result + ((coluna == null) ? 0 : coluna.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Coordenada other = (Coordenada) obj;
if (linha == null) {
if (other.linha != null)
return false;
} else if (!linha.equals(other.linha))
return false;
if (coluna == null) {
if (other.coluna != null)
return false;
} else if (!coluna.equals(other.coluna))
return false;
return true;
}
}
|
package com.alura.dto;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class CursoDto {
@NotEmpty @NotNull @Length(min = 5)
private String nome;
@NotEmpty @NotNull @Length(min = 6)
private String categoria;
}
|
package application;
public class PastInvoices {
private String fileName;
private String date;
public PastInvoices(String fileName, String date) {
this.fileName = fileName;
this.date = date;
}
public String getFileName() {
return fileName;
}
public String getDate() {
return date;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setDate(String date) {
this.date = date;
}
}
|
package revolt.backend.service;
import revolt.backend.dto.RTADto;
import java.util.List;
public interface RTAService {
List<RTADto> getRTAs();
RTADto createRTA(RTADto rtaDto);
RTADto getRTA(Long id);
RTADto updateRTA(RTADto rtaDto, Long rtaId);
void deleteRTA(Long id);
}
|
package com.postpc.Sheed.Connections.YourMatches;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.postpc.Sheed.Chat.ChatActivity;
import com.postpc.Sheed.R;
import com.postpc.Sheed.SheedApp;
import com.postpc.Sheed.database.SheedUsersDB;
import com.postpc.Sheed.makeMatches.MatchDescriptor;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class YourMatchesAdapter extends RecyclerView.Adapter<YourMatchesAdapter.viewHolder>{
Context context;
SheedUsersDB db;
List<String> matchesDescriptors;
public YourMatchesAdapter(Context c, HashMap<String, String> matchesDescriptors) {
context = c;
this.matchesDescriptors = new ArrayList<>(matchesDescriptors.values());
db = SheedApp.getDB();
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.your_matches_item, parent, false);
return new viewHolder(view);
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull viewHolder holder, int position) {
MatchDescriptor matchDescriptor = MatchDescriptor.fromString(matchesDescriptors.get(position));
String userId = matchDescriptor.getMatchedWith(db.currentSheedUser.email);
String matchers = matchDescriptor.getMatchersAsString();
int matchersNum = matchDescriptor.getMatchersNumber();
int sheedUserFriendsNum = db.currentSheedUser.community.size();
db.downloadUserAndDo(userId, sheedUser -> {
if(sheedUser.equals(null)){
return;
}
holder.userName.setText(sheedUser.firstName);
holder.userAge.setText(sheedUser.age.toString() + " years old");
holder.matchers.setText(matchers);
holder.ratingBar.setRating((float) matchersNum / (float) sheedUserFriendsNum);
Picasso.with(context).load(sheedUser.imageUrl).into(holder.userImage);
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra("userId", userId);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return matchesDescriptors.size();
}
public static class viewHolder extends RecyclerView.ViewHolder {
TextView userName;
TextView userAge;
TextView matchers;
RatingBar ratingBar;
CircleImageView userImage;
public viewHolder(@NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.userName);
userAge = itemView.findViewById(R.id.userAge);
matchers = itemView.findViewById(R.id.matchers);
ratingBar = itemView.findViewById(R.id.ratingBar);
userImage = itemView.findViewById(R.id.userImage);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.