text stringlengths 10 2.72M |
|---|
package com.example.a77354.android_final_project.HttpServiceInterface;
import com.example.a77354.android_final_project.ToolClass.ResponseBody;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
/**
* Created by kunzhai on 2018/1/6.
*/
public interface CheckIfLoginService {
@Headers({"Content-Type: application/json","Accept: application/json"})
@GET("user/login")
rx.Observable<ResponseBody> login();
}
|
package cyfixusBot.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import cyfixusBot.bot.CyfixusBot;
import cyfixusBot.events.FormEvent;
import cyfixusBot.gui.components.CyButton;
import cyfixusBot.gui.components.CyClassCategory;
import cyfixusBot.gui.components.CyCombo;
import cyfixusBot.gui.components.CyLabel;
import cyfixusBot.gui.components.CyList;
import cyfixusBot.gui.components.CyTextField;
import cyfixusBot.util.FormListener;
public class FormPanel extends JPanel {
private String name;
private String title;
private byte level;
private double capacity;
private long exp;
private long toNextLevel;
private byte health;
private byte mana;
private double currency;
private byte strength;
private byte stamina;
private byte intelligence;
private byte will;
private int playerClass;
private CyLabel nameLabel = new CyLabel("name:");
private CyLabel titleLabel = new CyLabel("title:");
private CyLabel levelLabel = new CyLabel("level:");
private CyLabel expLabel = new CyLabel("exp:");
private CyLabel toNextLevelLabel = new CyLabel("tnl:");
private CyLabel healthLabel = new CyLabel("health:");
private CyLabel manaLabel = new CyLabel("mana:");
private CyLabel currencyLabel = new CyLabel("curr:");
private CyLabel capacityLabel = new CyLabel("cap:");
private CyLabel strengthLabel = new CyLabel("str:");
private CyLabel staminaLabel = new CyLabel("sta:");
private CyLabel intelligenceLabel = new CyLabel("int:");
private CyLabel willLabel = new CyLabel("will:");
private CyLabel classLabel = new CyLabel("class:");
private CyTextField nameField = new CyTextField(10);
private CyTextField titleField = new CyTextField(5);
private CyTextField levelField = new CyTextField(10);
private CyTextField expField = new CyTextField(5);
private CyTextField toNextLevelField = new CyTextField(10);
private CyTextField healthField = new CyTextField(5);
private CyTextField manaField = new CyTextField(10);
private CyTextField currencyField = new CyTextField(5);
private CyTextField capacityField = new CyTextField(10);
private CyTextField strengthField = new CyTextField(5);
private CyTextField staminaField = new CyTextField(10);
private CyTextField intelligenceField = new CyTextField(5);
private CyTextField willField = new CyTextField(10);
private CyButton addBtn = new CyButton("++");
private CyButton rmvBtn = new CyButton("--");
private CyButton getBtn = new CyButton("get");
private CyButton setBtn = new CyButton("set");
private FormListener formListener;
private CyList classList;
private CyCombo classCombo;
private CyCombo nameCombo;
private CyfixusBot bot;
public FormPanel(CyfixusBot bot){
this.bot = bot;
setBackground(new Color(3));
Dimension dim = getPreferredSize();
dim.width = 500;
setPreferredSize(dim);
nameCombo = new CyCombo();
nameCombo.setEditable(true);
nameCombo.getEditor().getEditorComponent().setBackground(new Color(7));
loadNameCombo();
classList = new CyList();
classCombo = new CyCombo();
DefaultComboBoxModel classModel = new DefaultComboBoxModel();
classModel.addElement(new CyClassCategory(0, "Grunt"));
classModel.addElement(new CyClassCategory(1,"Seer"));
classModel.addElement(new CyClassCategory(2,"Sneak"));
classModel.addElement(new CyClassCategory(3,"Tradesmith"));
classCombo.setModel(classModel);
classList.setPreferredSize(new Dimension(110, 66));
classList.setBorder(BorderFactory.createEtchedBorder());
classList.setSelectedIndex(1);
addBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
FormEvent ev = new FormEvent(this, name);
if(formListener != null){
formListener.formAdd(ev);
loadNameCombo();
bot.save();
}
}
});
rmvBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String name = nameField.getText();
FormEvent ev = new FormEvent(this, name);
if(formListener != null){
formListener.formRemove(ev);
loadNameCombo();
bot.save();
}
}
});
setBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
name = new String(nameCombo.getSelectedItem().toString());
title = titleField.getText();
level = Byte.parseByte(levelField.getText());
capacity = Double.parseDouble(capacityField.getText());
exp = Long.parseLong(expField.getText());
health = Byte.parseByte(healthField.getText());
mana = Byte.parseByte(manaField.getText());
currency = Double.parseDouble(currencyField.getText());
strength = Byte.parseByte(strengthField.getText());
stamina = Byte.parseByte(staminaField.getText());
intelligence = Byte.parseByte(intelligenceField.getText());
will = Byte.parseByte(willField.getText());
playerClass = classCombo.getSelectedIndex();
System.out.println("Player class: " + playerClass);
FormEvent ev = new FormEvent(this, name, title,
level, capacity,
exp,
health, mana,
currency, strength,
stamina, intelligence,
will, playerClass);
if(formListener != null){
formListener.setPlayerStats(ev);
loadNameCombo();
bot.save();
}
}
});
getBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
name = new String(nameCombo.getSelectedItem().toString());
FormEvent ev = new FormEvent(this, name);
if(formListener != null){
formListener.getPlayerStats(ev);
}
}
});
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border innerBorder = BorderFactory.createTitledBorder(outerBorder,
"GAME MASTER", TitledBorder.CENTER, TitledBorder.TOP,
nameLabel.getBigFont());
setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
// - - COL 1
gc.weightx = 0.25;
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(nameLabel, gc);
gc.gridx = 0;
gc.gridy = 1;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(levelLabel, gc);
gc.gridx = 0;
gc.gridy = 2;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(expLabel, gc);
gc.gridx = 0;
gc.gridy = 3;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(healthLabel, gc);
gc.gridx = 0;
gc.gridy = 4;
gc.fill = GridBagConstraints.NONE;
add(currencyLabel, gc);
gc.gridx = 0;
gc.gridy = 5;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(staminaLabel, gc);
gc.gridx = 0;
gc.gridy = 6;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(willLabel, gc);
//Buttons
gc.weightx = 1;
gc.weighty = 1;
gc.gridx = 0;
gc.gridy = 8;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(addBtn, gc);
gc.gridx = 1;
gc.gridy = 8;
add(rmvBtn, gc);
gc.gridx = 2;
gc.gridy = 8;
add(getBtn, gc);
gc.gridx = 3;
gc.gridy = 8;
add(setBtn, gc);
// - - COL 2
gc.weightx = 0.8;
gc.weighty = 0;
gc.gridx = 1;
gc.gridy = 0;
gc.fill = GridBagConstraints.HORIZONTAL;
add(nameCombo, gc);
gc.gridx = 1;
gc.gridy = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
add(levelField, gc);
gc.gridx = 1;
gc.gridy = 2;
gc.fill = GridBagConstraints.HORIZONTAL;
add(expField, gc);
gc.gridx = 1;
gc.gridy = 3;
gc.fill = GridBagConstraints.HORIZONTAL;
add(healthField, gc);
gc.gridx = 1;
gc.gridy = 4;
gc.fill = GridBagConstraints.HORIZONTAL;
add(currencyField, gc);
gc.gridx = 1;
gc.gridy = 5;
gc.fill = GridBagConstraints.HORIZONTAL;
add(staminaField, gc);
gc.gridx = 1;
gc.gridy = 6;
gc.fill = GridBagConstraints.HORIZONTAL;
add(willField, gc);
// - - COL 3
gc.weightx = 0.1;
gc.weighty = 0;
gc.gridx = 2;
gc.gridy = 0;
gc.anchor = GridBagConstraints.LINE_START;
add(titleLabel, gc);
gc.gridx = 2;
gc.gridy = 1;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(capacityLabel, gc);
gc.gridx = 2;
gc.gridy = 2;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(toNextLevelLabel, gc);
gc.gridx = 2;
gc.gridy = 3;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(manaLabel, gc);
gc.gridx = 2;
gc.gridy = 4;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(strengthLabel, gc);
gc.gridx = 2;
gc.gridy = 5;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(intelligenceLabel, gc);
gc.gridx = 2;
gc.gridy = 6;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_START;
add(classLabel, gc);
// - - COL 4
gc.weightx = 0;
gc.gridx = 3;
gc.gridy = 0;
gc.anchor = GridBagConstraints.LINE_END;
gc.fill = GridBagConstraints.HORIZONTAL;
add(titleField, gc);
gc.gridx = 3;
gc.gridy = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.LINE_END;
add(capacityField, gc);
gc.gridx = 3;
gc.gridy = 2;
gc.fill = GridBagConstraints.HORIZONTAL;
add(toNextLevelField, gc);
gc.gridx = 3;
gc.gridy = 3;
gc.fill = GridBagConstraints.HORIZONTAL;
add(manaField, gc);
gc.gridx = 3;
gc.gridy = 4;
gc.fill = GridBagConstraints.HORIZONTAL;
add(strengthField, gc);
gc.gridx = 3;
gc.gridy = 5;
gc.fill = GridBagConstraints.HORIZONTAL;
add(intelligenceField, gc);
gc.gridx = 3;
gc.gridy = 6;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(classCombo, gc);
}
public void loadNameCombo(){
int count = 0;
LinkedList<String> players = bot.getPlayerNames();
DefaultComboBoxModel classModel = new DefaultComboBoxModel();
for(String player: players){
classModel.addElement(new CyClassCategory(count++, player));
}
nameCombo.setModel(classModel);
}
public void setFormListener(FormListener listener) {
this.formListener = listener;
}
public void setStats(String name, String title,
byte level, double capacity,
long exp, long toNextLevel,
byte health, byte mana,
double currency, byte strength,
byte stamina, byte intelligence,
byte will, int playerClass) {
this.name = name;
this.title = title;
this.level = level;
this.capacity = capacity;
this.exp = exp;
this.toNextLevel = toNextLevel;
this.health = health;
this.mana = mana;
this.currency = currency;
this.strength = strength;
this.stamina = stamina;
this.intelligence = intelligence;
this.will = will;
this.playerClass = playerClass;
fillTextFields(name, title,
level, capacity,
exp, toNextLevel,
health, mana,
currency, strength,
stamina, intelligence,
will, playerClass);
}
public void fillTextFields(String name, String title,
byte level, double capacity,
long exp, long toNextLevel,
byte health, byte mana,
double currency, byte strength,
byte stamina, byte intelligence,
byte will, int playerClass) {
nameField.setText(name);
titleField.setText(title);
levelField.setText(level+"");
capacityField.setText(capacity+"");
expField.setText(exp+"");
toNextLevelField.setText(toNextLevel+"");
healthField.setText(health+"");
manaField.setText(mana+"");
currencyField.setText(currency+"");
strengthField.setText(strength+"");
staminaField.setText(stamina+"");
intelligenceField.setText(intelligence+"");
willField.setText(will+"");
classCombo.setSelectedIndex(playerClass);
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core;
import java.sql.CallableStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.lang.Nullable;
/**
* Generic callback interface for code that operates on a CallableStatement.
* Allows to execute any number of operations on a single CallableStatement,
* for example a single execute call or repeated execute calls with varying
* parameters.
*
* <p>Used internally by JdbcTemplate, but also useful for application code.
* Note that the passed-in CallableStatement can have been created by the
* framework or by a custom CallableStatementCreator. However, the latter is
* hardly ever necessary, as most custom callback actions will perform updates
* in which case a standard CallableStatement is fine. Custom actions will
* always set parameter values themselves, so that CallableStatementCreator
* capability is not needed either.
*
* @author Juergen Hoeller
* @since 16.03.2004
* @param <T> the result type
* @see JdbcTemplate#execute(String, CallableStatementCallback)
* @see JdbcTemplate#execute(CallableStatementCreator, CallableStatementCallback)
*/
@FunctionalInterface
public interface CallableStatementCallback<T> {
/**
* Gets called by {@code JdbcTemplate.execute} with an active JDBC
* CallableStatement. Does not need to care about closing the Statement
* or the Connection, or about handling transactions: this will all be
* handled by Spring's JdbcTemplate.
*
* <p><b>NOTE:</b> Any ResultSets opened should be closed in finally blocks
* within the callback implementation. Spring will close the Statement
* object after the callback returned, but this does not necessarily imply
* that the ResultSet resources will be closed: the Statement objects might
* get pooled by the connection pool, with {@code close} calls only
* returning the object to the pool but not physically closing the resources.
*
* <p>If called without a thread-bound JDBC transaction (initiated by
* DataSourceTransactionManager), the code will simply get executed on the
* JDBC connection with its transactional semantics. If JdbcTemplate is
* configured to use a JTA-aware DataSource, the JDBC connection and thus
* the callback code will be transactional if a JTA transaction is active.
*
* <p>Allows for returning a result object created within the callback, i.e.
* a domain object or a collection of domain objects. A thrown RuntimeException
* is treated as application exception: it gets propagated to the caller of
* the template.
* @param cs active JDBC CallableStatement
* @return a result object, or {@code null} if none
* @throws SQLException if thrown by a JDBC method, to be auto-converted
* into a DataAccessException by an SQLExceptionTranslator
* @throws DataAccessException in case of custom exceptions
*/
@Nullable
T doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException;
}
|
/**
* Wikipedia says
*
* The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.
*
* So we can create any objects by setting the parameters that we need.
*/
public class BuilderExample_01 {
public static void main(String[] args) {
Person person = new PersonBuilderImpl().setFirstname("Mike").setAge(30).build();
System.out.println(person);
}
}
class Person {
String firstname;
String lastname;
int age;
double salary;
@Override
public String toString() {
return "Person{" +
"firstname='" + this.firstname + '\'' +
", lastname='" + this.lastname + '\'' +
", age=" + this.age +
", salary=" + this.salary +
'}';
}
}
interface PersonBuilder {
PersonBuilder setFirstname(String firstname);
PersonBuilder setLastname(String lastname);
PersonBuilder setAge(int age);
PersonBuilder setSalary(double salary);
Person build();
}
class PersonBuilderImpl implements PersonBuilder {
private Person person = new Person();
@Override
public PersonBuilder setFirstname(final String firstname) {
person.firstname = firstname;
return this;
}
@Override
public PersonBuilder setLastname(final String lastname) {
person.lastname = lastname;
return this;
}
@Override
public PersonBuilder setAge(final int age) {
person.age = age;
return this;
}
@Override
public PersonBuilder setSalary(final double salary) {
person.salary = salary;
return this;
}
@Override
public Person build() {
return this.person;
}
} |
package pl.basistam.books;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import java.io.Serializable;
@XmlRootElement
public class Title implements Serializable {
private String language;
private String name;
@XmlAttribute(name = "lang")
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getName() {
return name;
}
@XmlValue
public void setName(String title) {
this.name = title;
}
@Override
public String toString() {
return "Tytuł w języku " + language + ": " + name;
}
}
|
/*
* 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 io.github.minhaz1217.onlineadvising;
import io.github.minhaz1217.onlineadvising.Interface.CourseDescriptionRepository;
import io.github.minhaz1217.onlineadvising.Interface.CourseRepository;
import io.github.minhaz1217.onlineadvising.Interface.StudentRepository;
import io.github.minhaz1217.onlineadvising.Interface.UserRepository;
import io.github.minhaz1217.onlineadvising.models.*;
import java.util.ArrayList;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
*
* @author Minhaz
*/
@Component
public class DbSeeder implements CommandLineRunner {
protected static CourseRepository courseRepository;
private static UserRepository userRepository;
private static StudentRepository studentRepository;
private static CourseDescriptionRepository courseDescriptionRepository;
public DbSeeder(CourseRepository courseRepository,
UserRepository userRepository,
StudentRepository studentRepository,
CourseDescriptionRepository courseDescriptionRepository){
this.courseRepository = courseRepository;
this.userRepository = userRepository;
this.studentRepository = studentRepository;
this.courseDescriptionRepository = courseDescriptionRepository;
}
public static String deleteAll(){
courseRepository.deleteAll();
userRepository.deleteAll();
studentRepository.deleteAll();
courseDescriptionRepository.deleteAll();
System.out.println("DB Details: " + " Users: "+ userRepository.count() + " Courses: "+ courseRepository.count() + " Course Description: " + courseDescriptionRepository.count() + " Students: " + studentRepository.count());
return ("Details: " + " Users: "+ userRepository.count() + " Courses: "+ courseRepository.count() + " Course Description: " + courseDescriptionRepository.count() + " Students: " + studentRepository.count());
}
public static String loadAll(){
// clearing all the tables
System.out.println("DB Details: " + " Users: "+ userRepository.count() + " Courses: "+ courseRepository.count() + " Course Description: " + courseDescriptionRepository.count() + " Students: " + studentRepository.count());
//adding some user to use
User minhaz = new User("minhaz2", "minhaz2", "ROLE_ADMIN", "ROLE_USER");
User admin = new User("admin", "admin", "ROLE_ADMIN", "ROLE_USER");
userRepository.save(minhaz);
userRepository.save(admin);
// adding all the courses
courseRepository.save( new Course("Basic English","ENG101","Department of English","0",new ArrayList<String>()));
courseRepository.save( new Course("Differential And Integral Calculus","MAT101","Mathematical and Physical Sciences","0",new ArrayList<String>()));
courseRepository.save( new Course("Structured Programming","CSE105","Department of Computer Seience and Engineering","1",new ArrayList<String>()));
courseRepository.save( new Course("Composition and Communication Skills","ENG102","Department of English","0",new ArrayList<String>(Arrays.asList("ENG101"))));
courseRepository.save( new Course("Differential Equations and Special Functions","MAT102","Mathematical and Physical Sciences","0",new ArrayList<String>(Arrays.asList("MAT101"))));
courseRepository.save( new Course("Object Oriented Programming","CSE107","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE105"))));
courseRepository.save( new Course("Engineering Physics-I (Introductory Classical Physics)","PHY109","Mathematical and Physical Sciences","1",new ArrayList<String>(Arrays.asList("MAT102"))));
courseRepository.save( new Course("Coordinate Geometry and Vector Analysis","MAT104","Mathematical and Physical Sciences","0",new ArrayList<String>()));
courseRepository.save( new Course("Engineering Chemistry","CHE109","Department of Pharmacy","1",new ArrayList<String>()));
courseRepository.save( new Course("Electrical Circuits","CSE109","Department of Computer Seience and Engineering","1",new ArrayList<String>()));
courseRepository.save( new Course("Bangladesh Studies","GEN201","Department of Sociology","0",new ArrayList<String>()));
courseRepository.save( new Course("Statics and Probability","STA102","Department of Applied Statistics","0",new ArrayList<String>()));
courseRepository.save( new Course("Discrete Mathematics","CSE205","Department of Computer Seience and Engineering","0",new ArrayList<String>(Arrays.asList("CSE107"))));
courseRepository.save( new Course("Linear Algebra and Complex Veriable","MAT205","Mathematical and Physical Sciences","0",new ArrayList<String>(Arrays.asList("MAT102"))));
courseRepository.save( new Course("Data Structures","CSE207","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE205"))));
courseRepository.save( new Course("Numerical Methods","CSE225","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE105","MAT102"))));
courseRepository.save( new Course("Engineering Physics-II (Introductory Quantum Physics)","PHY209","Mathematical and Physical Sciences","0",new ArrayList<String>(Arrays.asList("MAT205"))));
courseRepository.save( new Course("Algorithms","CSE245","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE207"))));
courseRepository.save( new Course("Signals and Systems","CSE248","Department of Computer Seience and Engineering","0",new ArrayList<String>(Arrays.asList("CSE109","MAT205"))));
courseRepository.save( new Course("Electronic Circuits","CSE251","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE109"))));
courseRepository.save( new Course("Database Systems","CSE301","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE205"))));
courseRepository.save( new Course("Operating Systems","CSE325","Department of Computer Seience and Engineering","1",new ArrayList<String>()));
courseRepository.save( new Course("Digital Logic Design","CSE345","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE205","CSE251"))));
courseRepository.save( new Course("Data Communications","CSE350","Department of Computer Seience and Engineering","0",new ArrayList<String>(Arrays.asList("CSE251","CSE248"))));
courseRepository.save( new Course("Computer Architecture","CSE360","Department of Computer Seience and Engineering","0",new ArrayList<String>(Arrays.asList("CSE325","CSE345"))));
courseRepository.save( new Course("Artificial Intelligence","CSE365","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE245"))));
courseRepository.save( new Course("Compiler Design","CSE375","Department of Computer Seience and Engineering","0",new ArrayList<String>()));
courseRepository.save( new Course("Computer Networks","CSE405","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE245","CSE350"))));
courseRepository.save( new Course("Social and Professional Issues in Computing","CSE498","Department of Computer Seience and Engineering","0",new ArrayList<String>()));
courseRepository.save( new Course("Software Engineering and Information System Design","CSE411","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE301"))));
courseRepository.save( new Course("Microprocessors and Microcontrollers","CSE442","Department of Computer Seience and Engineering","1",new ArrayList<String>(Arrays.asList("CSE360"))));
//adding some course description
courseDescriptionRepository.save(new CourseDescription( "CSE350","01","08:30 - 10:00","ST","AB2-405","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE350","02","11:50 - 01:20","T","226","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE350","02","11:50 - 01:20","R","225","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE350","03","11:50 - 01:20","MW","AB2-205","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE360","01","08:30 - 10:00","SR","112","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE360","02","10:10 - 11:40","SR","112","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE360","03","08:30 - 10:00","MW","435","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE365","01","10:10 - 11:40","ST","AB1-601","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE365","02","01:30 - 03:00","T","436","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE365","02","01:30 - 03:00","S","AB2-503","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE365","03","10:10 - 11:40","MW","109","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE375","01","11:50 - 01:20","ST","115","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE375","02","03:10 - 04:40","SR","Reading Course","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE375","03","01:30 - 03:00","TR","109","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE498","01","08:30 - 10:00","MW","221","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE498","02","03:10 - 04:40","SR","337","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411","01","10:10 - 11:40","T","AB2-304","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411","01","10:10 - 11:40","R","AB2-304","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411","02","10:10 - 11:40","MW","AB1-301","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411","03","01:30 - 03:00","TR","AB2-205","40"));
courseDescriptionRepository.save(new CourseDescription( "GEN201","01","01:30 - 03:00","MW","219","40"));
courseDescriptionRepository.save(new CourseDescription( "GEN201","02","01:30 - 03:00","SR","550 (Lecture Gallery)","40"));
courseDescriptionRepository.save(new CourseDescription( "STA102","01","01:30 - 03:00","MW","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "STA102","02","03:10 - 04:40","TR","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "STA102","03","01:30 - 03:00","ST","AB1-402","40"));
courseDescriptionRepository.save(new CourseDescription( "STA102","04","11:50 - 01:20","MW","AB1-402","40"));
courseDescriptionRepository.save(new CourseDescription( "STA102","05","11:50 - 01:20","MW","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE205","01","10:10 - 11:40","ST","532","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE205","02","01:30 - 03:00","ST","532","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE205","03","10:10 - 11:40","MW","532","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE205","04","01:30 - 03:00","MW","532","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT205","01","01:30 - 03:00","ST","437","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT205","02","11:50 - 01:20","MW","437","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT205","03","10:10 - 11:40","ST","AB2-503","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT205","04","08:30 - 10:00","MW","436","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT205","05","08:30 - 10:00","ST","AB1-502","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT205","06","01:30 - 03:00","MW","AB1-502","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","01","10:10 - 11:40","MW","212","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","02","11:50 - 01:20","MW","212","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","03","10:10 - 11:40","T","AB2-405","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","03","10:10 - 11:40","R","AB2-404","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","04","01:30 - 03:00","T","212","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","04","01:30 - 03:00","R","107","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE225","05","08:30 - 10:00","MW","AB1-301","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE251","01","08:30 - 10:00","TR","AB1-301","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE251","02","01:30 - 03:00","TR","AB1-501","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE251","03","01:30 - 03:00","MW","TBA","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE325","01","08:30 - 10:00","MW","108","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE325","02","11:50 - 01:20","T","AB2-203","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE325","02","11:50 - 01:20","R","114","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE325","03","08:30 - 10:00","SR","AB1-701","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE325","04","03:10 - 04:40","MW","AB1-501","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","01","08:30 - 10:00","MW","223","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","10","01:30 - 03:00","MW","AB2-503","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","11","10:10 - 11:40","T","336","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","11","10:10 - 11:40","R","219","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","12","01:30 - 03:00","S","AB1-602","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","12","01:30 - 03:00","T","115","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","13","08:30 - 10:00","MW","115","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","14","03:10 - 04:40","ST","225","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","15","01:30 - 03:00","MW","AB1-602","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","16","08:30 - 10:00","ST","113","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","17","10:10 - 11:40","S","AB1-602","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","17","10:10 - 11:40","R","532","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","18","03:10 - 04:40","MW","227","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","19","10:10 - 11:40","S","AB2-203","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","19","10:10 - 11:40","R","AB1-401","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","02","08:30 - 10:00","ST","241","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","20","11:50 - 01:20","R","336","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","20","11:50 - 01:20","T","AB2-204","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","21","03:10 - 04:40","S","241","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","21","03:10 - 04:40","R","225","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","22","03:10 - 04:40","MW","AB2-204","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","23","08:30 - 10:00","MW","AB1-201","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","03","03:10 - 04:40","MW","221","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","04","08:30 - 10:00","MW","111","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","05","11:50 - 01:20","MW","AB2-303","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","06","11:50 - 01:20","MW","222","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","07","08:30 - 10:00","R","223","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","07","08:30 - 10:00","T","226","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","08","08:30 - 10:00","TR","AB2-404","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","09","01:30 - 03:00","S","223","40"));
courseDescriptionRepository.save(new CourseDescription( "ENG101","09","01:30 - 03:00","T","221","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","01","01:30 - 03:00","MW","AB1-202","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","10","11:50 - 01:20","MW","AB1-502","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","12","11:50 - 01:20","S","TBA","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","13","08:30 - 10:00","S","TBA","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","02","11:50 - 01:20","ST","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","03","01:30 - 03:00","TR","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","04","11:50 - 01:20","ST","AB1-602","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","05","03:10 - 04:40","SR","AB1-602","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","06","11:50 - 01:20","MW","AB1-301","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","07","11:50 - 01:20","TR","AB1-402","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","08","11:50 - 01:20","S","AB1-402","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","08","11:50 - 01:20","R","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT101","09","10:10 - 11:40","ST","AB1-502","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE105","01","08:30 - 10:00","ST","110","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE105","02","11:50 - 01:20","MW","108","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE105","03","11:50 - 01:20","ST","110","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE105","04","08:30 - 10:00","MW","630 (Software Engineering Lab)","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","01","11:50 - 01:20","MW","358","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","10","11:50 - 01:20","SR","AB2-204","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","12","03:10 - 04:40","T","TBA","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","02","01:30 - 03:00","SR","359","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","03","11:50 - 01:20","ST","433","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","04","01:30 - 03:00","T","432","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","04","01:30 - 03:00","R","219","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","05","01:30 - 03:00","R","437","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","05","01:30 - 03:00","S","AB1-302","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","06","11:50 - 01:20","MW","AB1-501","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","07","11:50 - 01:20","ST","531","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","08","03:10 - 04:40","MW","532","40"));
courseDescriptionRepository.save(new CourseDescription( "MAT104","09","01:30 - 03:00","TR","AB2-404","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","01","08:30 - 10:00","SR","109","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","02","11:50 - 01:20","TR","AB1-301","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","03","03:10 - 04:40","MW","107","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","04","08:30 - 10:00","T","102","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","04","08:30 - 10:00","R","108","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","05","10:10 - 11:40","TR","102","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","06","11:50 - 01:20","SR","113","40"));
courseDescriptionRepository.save(new CourseDescription( "CHE109","07","10:10 - 11:40","SR","212","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","01","08:30 - 10:00","ST","221","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","02","01:30 - 03:00","MW","AB1-201","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","03","11:50 - 01:20","MW","AB2-302","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","04","11:50 - 01:20","S","AB2-203","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","04","11:50 - 01:20","R","AB1-401","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","05","10:10 - 11:40","MW","358","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE109","07","03:10 - 04:40","SR","AB2-203","40"));
//adding the labs
courseDescriptionRepository.save(new CourseDescription( "CSE365LAB","01","10:10 - 12:10","R","638","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE365LAB","02","01:30 - 03:30","R","638","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE365LAB","03","01:30 - 03:30","M","638","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411LAB","01","10:10 - 12:10","S","638","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411LAB","02","08:00 - 10:00","T","638","40"));
courseDescriptionRepository.save(new CourseDescription( "CSE411LAB","03","04:50 - 06:50","T","638","40"));
//adding some demo students
studentRepository.save(new Student( "Jeremy", "G. Ingram", "JeremyGIngram@rhyta.com", "2016-1-60-100",new ArrayList<CourseExtended>( Arrays.asList(
new CourseExtended("ENG101"),
new CourseExtended("MAT101"),
new CourseExtended("CSE105"),
new CourseExtended("ENG102"),
new CourseExtended("MAT102"),
new CourseExtended("CSE107"),
new CourseExtended("PHY109"),
new CourseExtended("MAT104"),
new CourseExtended("CHE109"),
new CourseExtended("CSE109"),
new CourseExtended("GEN201"),
new CourseExtended("STA102"),
new CourseExtended("CSE205"),
new CourseExtended("MAT205"),
new CourseExtended("CSE207"),
new CourseExtended("CSE225"),
new CourseExtended("PHY209"),
new CourseExtended("CSE245"),
new CourseExtended("CSE248"),
new CourseExtended("CSE251"),
new CourseExtended("CSE301"),
new CourseExtended("CSE325"),
new CourseExtended("CSE345" )
)
)));
studentRepository.save(new Student( "Erin","D. Gaither", "ErinDGaither@teleworm.us", "2016-1-60-101",
new ArrayList<CourseExtended>( Arrays.asList(
new CourseExtended("ENG101"),
new CourseExtended("MAT101"),
new CourseExtended("CSE105"),
new CourseExtended("ENG102"),
new CourseExtended("MAT102"),
new CourseExtended("CSE107"),
new CourseExtended("PHY109"),
new CourseExtended("MAT104"),
new CourseExtended("CHE109"),
new CourseExtended("CSE109" )
))));
studentRepository.save(new Student( "Minhazul", "Hayat Khan", "minhaz1217@gmail.com", "2016-1-60-102",
new ArrayList<CourseExtended>( Arrays.asList(
new CourseExtended("")
))));
studentRepository.save(new Student( "John", "A. Davis", "JohnADavis@armyspy.com ", "2016-1-60-103",
new ArrayList<CourseExtended>( Arrays.asList(
new CourseExtended( "MAT101","2"),
new CourseExtended( "ENG101","2"),
new CourseExtended( "CSE411","1")
))));
System.out.println("DB Details: " + " Users: "+ userRepository.count() + " Courses: "+ courseRepository.count() + " Course Description: " + courseDescriptionRepository.count() + " Students: " + studentRepository.count());
return ("Details: " + " Users: "+ userRepository.count() + " Courses: "+ courseRepository.count() + " Course Description: " + courseDescriptionRepository.count() + " Students: " + studentRepository.count());
}
@Override
public void run(String... args) throws Exception {
//this.courseDescriptionRepository.save(new CourseDescription( "CSE405","1","08:30 - 10:00","MW", "112","40"));
//showing some messages to verify that everything went ok
System.out.println("DB Details: " + " Users: "+ userRepository.count() + " Courses: "+ courseRepository.count() + " Course Description: " + courseDescriptionRepository.count() + " Students: " + studentRepository.count());
//System.out.println(courseRepository.count());
System.out.println("DB LOADED SUCCESSFULLY");
}
}
|
package com.spr.utils;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.spr.model.Contract;
import com.spr.model.User;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* Created by Catalina on 14.04.2017.
*/
public class PdfReport implements Report {
@Override
public void generate(Contract contract, User client, Float total) {
Document document = new Document();
String pdfFilePath = "E:\\Catalina\\AnIII_Sem2\\SD\\Lab\\Project\\proiect\\";
String pdfFile = "Contract" + contract.getId().toString() + ".pdf";
String path = new File(".").getAbsolutePath();
try {
PdfWriter.getInstance(document, new FileOutputStream(path + pdfFile));
document.open();
document.add(new Paragraph("Contract: " + contract.getDate().toString()));
document.add(new Paragraph("ID: " + contract.getId().toString()));
document.add(new Paragraph("Description: " + contract.getDescription()));
document.add(new Paragraph(" "));
// document.add(new Paragraph("Adoption: " + adoption.getAdoptionDate().toString()));
// document.add(new Paragraph("Client CNP: " + client.getCNP()));
// document.add(new Paragraph("Client Name: " + client.getFname() + " " + client.getLname()));
// document.add(new Paragraph("Client Email: " + client.getEmail()));
// document.add(new Paragraph("Client Address: " + client.getAddress()));
// document.add(new Paragraph(" "));
// document.add(new Paragraph("User ID: " + adoption.getIdUser().toString()));
document.add(new Paragraph(" "));
document.add(new Paragraph("Total: " + total + " lei"));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
|
package collection;
public class Faculty {
public static void main(String[] args) {
String name;
//Array of skills
int a[]=new int[8];
System.out.println(a.length);
//Sk
}
} |
package com.cigc.limit.service;
import com.cigc.limit.utils.AppCfgUtils;
import com.cigc.limit.utils.DateUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2018/7/10.
* 查询一天内只有抓拍而没有RFID的车牌,且这种情况出现了5次
*/
@Component
public class DeckService3 {
@Autowired
private TransportClient client;
@Autowired
private JdbcTemplate jdbcTemplate;
//双模点
private static List<String> CJDID_List = new ArrayList<String>();
public void searchData(){
String sql = "select distinct(zp.CJDID) FROM HC_ZS_STATIC_CJD_RFID rfid INNER JOIN HC_ZS_STATIC_CJD_ZP zp on rfid.CJDID=zp.CJDID";
CJDID_List = jdbcTemplate.queryForList(sql, String.class);
//7天内有抓拍又有RFID
BoolQueryBuilder DayQuery = QueryBuilders.boolQuery();
ExistsQueryBuilder exitSnapshot = QueryBuilders.existsQuery("snapsotId");
AggregationBuilder groupTerms = AggregationBuilders.terms("groupCode").field("plateCode").size(Integer.MAX_VALUE)
.subAggregation(AggregationBuilders.terms("groupColor").field("plateColor").size(Integer.MAX_VALUE));
RangeQueryBuilder startQuery = QueryBuilders.rangeQuery("passTime").from(DateUtils.getMillis(-AppCfgUtils.getInt("starttime"), true));
RangeQueryBuilder endQuery = QueryBuilders.rangeQuery("passTime").to(DateUtils.getMillis(-AppCfgUtils.getInt("endtime"), true));
TermsQueryBuilder termsQuery = QueryBuilders.termsQuery("cjdid", CJDID_List);
DayQuery.must(exitSnapshot).must(startQuery).must(endQuery).must(termsQuery).mustNot(QueryBuilders.existsQuery("readerIP"));
SearchResponse response = client.prepareSearch("cqct_20180508_*")
.setTypes("AfterVehicle")
.setQuery(DayQuery)
.addAggregation(groupTerms)
.setExplain(true).execute().actionGet();
String code;
String color;
Map<String,String> codeMap=new HashMap<>();
Terms groupCode = response.getAggregations().get("groupCode");
for (Terms.Bucket codeBucket : groupCode.getBuckets()) {
code = codeBucket.getKeyAsString();
Terms groupColor = codeBucket.getAggregations().get("groupColor");
for (Terms.Bucket colorBucket : groupColor.getBuckets()) {
color = colorBucket.getKeyAsString();
codeMap.put(code, color);
}
}
System.out.println(codeMap.size());
}
}
|
package top.junebao.dao;
import top.junebao.domain.Course;
public class CourseDao {
/**
* 通过ID查询一门课程
* @param id
* @return
*/
public static Course selectCourseById(String id) {
return null;
}
}
|
package com.sl.app.access.find.account.dao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sl.app.access.find.account.vo.AppAccessFindAccountVO;
import com.sl.app.common.context.AppContextKey;
import com.sl.system.log.setter.SystemLogSetter;
import com.sl.system.log.setter.SystemLogSetterVO;
import net.sf.json.JSONObject;
@Repository
public class AppAccessFindAccountDAOImpl implements AppAccessFindAccountDAO {
@Autowired
SqlSession sqlSession;
@Autowired
SystemLogSetter logSetter;
private final String NS = "mapper.com.sl.app.access.find.account.";
@Override
public JSONObject updateFindMember(AppAccessFindAccountVO vo) {
// TODO Auto-generated method stub
JSONObject obj = new JSONObject();
if(sqlSession.update(NS+"updateFindMember",vo)==1){
obj.put(AppContextKey.AJAX_RESULT,AppContextKey.AJAX_SUCCESS);
obj.put(AppContextKey.RESULT_MSG, "["+vo.getEmail() + AppContextKey.MSG_FIND_ACCOUNT_SUCCESS);
logSetter.setSystemLog(
logSetter.builder(
AppContextKey.LOG_STATUS_ACCOUNT_FIND,
vo.getEmail(),
null,
null,
null
)
);
}else{
obj.put(AppContextKey.AJAX_RESULT,AppContextKey.AJAX_SUCCESS);
obj.put(AppContextKey.RESULT_MSG, "["+vo.getEmail() + AppContextKey.MSG_FIND_ACCOUNT_FAIL);
SystemLogSetterVO log = logSetter.builder(null, vo.getEmail(), vo.getEmail(),AppContextKey.LOG_STATUS_ACCOUNT_FIND_FAIL, null);
logSetter.setSystemLog(
logSetter.builder(
AppContextKey.LOG_STATUS_ACCOUNT_FIND_FAIL,
vo.getEmail(),
null,
null,
null
)
);
}
return obj;
}
}
|
package pdp.uz.payload;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ClientDto implements Serializable {
@NotNull
@ApiModelProperty(example = "90")
private Short code;
@NotNull
@ApiModelProperty(example = "3734142")
private String number;
@NotNull
private String firstname;
@NotNull
private String lastname;
@NotNull
private String username;
@NotNull
private String password;
@NotNull
@ApiModelProperty(example = "KA")
private String passportSeries;
@NotNull
@ApiModelProperty(example = "4562178")
private String passportNumber;
@NotNull
@ApiModelProperty(example = "PHYSICAL_PERSON")
private String clientType;
private Long branchId;
private Double balance;
private Double price;
private Long tariffId;
@ApiModelProperty(example = "true")
private boolean serviceDebt;
}
|
package sorryclient;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import customUI.ClearPanel;
import customUI.JTextFieldLimiter;
import customUI.PaintedButton;
import customUI.PaintedPanel;
import library.FontLibrary;
import library.ImageLibrary;
public class HostPanel extends PaintedPanel {
private static final long serialVersionUID = 7432083141632844078L;
private static final String portString = "Port:";
private static final String connectString = "Start";
private static final int portLength = 5;
private JLabel portNumberLabel;
private JTextField portNumberField;
{
portNumberLabel = new JLabel(portString);
portNumberLabel.setFont(FontLibrary.getFont("fonts/kenvector_future.ttf", Font.PLAIN, 32));
portNumberField = new JTextField(portLength-1);
portNumberField.setFont(FontLibrary.getFont("fonts/kenvector_future.ttf", Font.PLAIN, 32));
portNumberField.setDocument(new JTextFieldLimiter(portLength));
portNumberField.setBackground(Color.GRAY);
portNumberField.setText("3469");
}
public HostPanel(ActionListener hostAction, Image inImage){
super(inImage,true);
ClearPanel portInfoPanel = new ClearPanel();
portInfoPanel.setLayout(new BoxLayout(portInfoPanel,BoxLayout.X_AXIS));
portInfoPanel.add(portNumberLabel);
portInfoPanel.add(Box.createHorizontalStrut(10));
portInfoPanel.add(portNumberField);
PaintedButton connect = new PaintedButton(
connectString,
ImageLibrary.getImage("images/buttons/grey_button00.png"),
ImageLibrary.getImage("images/buttons/grey_button01.png"),
22
);
connect.addActionListener(hostAction);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(40,40,40,40);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridy = 1;
add(portInfoPanel,gbc);
gbc.ipadx = 100;
gbc.ipady = 25;
gbc.fill = GridBagConstraints.NONE;
gbc.gridy = 2;
add(connect,gbc);
}
public int getPort() {
return Integer.valueOf(portNumberField.getText());
}
} |
package org.zhq;
import org.zhq.constants.UDPConstants;
import lombok.extern.slf4j.Slf4j;
import org.zhq.utils.ByteUtil;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author zhengquan
*/
@Slf4j
public class UDPSearcher {
public static ServerInfo searchServer(int timeout){
log.info("org.zhq.UDPSearcher start");
CountDownLatch receiveLatch = new CountDownLatch(1);
Listener listener = null;
try {
listener = listen(receiveLatch);
sendBroadcast();
receiveLatch.await(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
}
if (listener == null) {
return null;
}
List<ServerInfo> serverInfoList = listener.getServerAndClose();
if (serverInfoList.size() > 0) {
return serverInfoList.get(0);
}
return null;
}
private static void sendBroadcast() throws IOException {
log.info("org.zhq.UDPSearcher sendBroadcast started");
DatagramSocket ds = new DatagramSocket();
ByteBuffer byteBuffer = ByteBuffer.allocate(128);
byteBuffer.put(UDPConstants.HEADER);
byteBuffer.putShort((short) 1);
byteBuffer.putInt(UDPConstants.PORT_CLIENT_RESPONSE);
int len = byteBuffer.position();
DatagramPacket requestPacket = new DatagramPacket(byteBuffer.array(), byteBuffer.position() + 1);
requestPacket.setAddress(InetAddress.getByName("255.255.255.255"));
requestPacket.setPort(UDPConstants.PORT_SERVER);
log.info("org.zhq.UDPSearcher sendBroadcast ip:{} port:{} length:{} data:{}","255.255.255.255",UDPConstants.PORT_SERVER,len,byteBuffer.array());
ds.send(requestPacket);
ds.close();
log.info("org.zhq.UDPSearcher sendBroadcast finished");
}
private static Listener listen(CountDownLatch receiveLatch) throws InterruptedException {
log.info("org.zhq.UDPSearcher listen start");
CountDownLatch startLatch = new CountDownLatch(1);
Listener listener = new Listener(UDPConstants.PORT_CLIENT_RESPONSE, receiveLatch, startLatch);
listener.start();
startLatch.await();
return listener;
}
private static class Listener extends Thread {
private final int port;
private final CountDownLatch receiveLatch;
private final CountDownLatch startLatch;
private final List<ServerInfo> serverInfoList = new ArrayList<>();
private final byte[] buf = new byte[128];
private final int minLen = UDPConstants.HEADER.length + 2 + 4;
private boolean done;
private DatagramSocket ds = null;
private Listener(int port, CountDownLatch receiveLatch, CountDownLatch startLatch) {
this.port = port;
this.receiveLatch = receiveLatch;
this.startLatch = startLatch;
}
@Override
public void run() {
super.run();
//通知监听已开始
startLatch.countDown();
try {
ds = new DatagramSocket(port);
DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
while (!done) {
ds.receive(receivePacket);
InetAddress ip = receivePacket.getAddress();
int port = receivePacket.getPort();
int dataLen = receivePacket.getLength();
byte[] data = receivePacket.getData();
boolean isValid = dataLen >= minLen && ByteUtil.startsWith(data, UDPConstants.HEADER);
log.info("org.zhq.UDPSearcher receive from ip:{} port:{} data:{} dataLen:{} isValid:{}", ip.getHostAddress(), port, data, dataLen, isValid);
if (!isValid) {
continue;
}
ByteBuffer byteBuffer = ByteBuffer.wrap(buf, UDPConstants.HEADER.length, dataLen);
short cmd = byteBuffer.getShort();
int serverPort = byteBuffer.getInt();
if (cmd != 2 || serverPort <= 0) {
log.info("org.zhq.UDPSearcher nonsupport cmd. cmd:{} serverPort:{}", cmd, serverPort);
continue;
}
String sn = new String(buf, minLen, dataLen - minLen);
ServerInfo serverInfo = new ServerInfo(ip.getHostAddress(), serverPort, sn);
serverInfoList.add(serverInfo);
receiveLatch.countDown();
}
} catch (Exception ignored) {
} finally {
close();
}
}
private void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
List<ServerInfo> getServerAndClose() {
done = true;
close();
return serverInfoList;
}
}
}
|
package com.restcode.restcode.controller;
import com.restcode.restcode.domain.model.Owner;
import com.restcode.restcode.domain.service.IOwnerService;
import com.restcode.restcode.resource.ConsultantResource;
import com.restcode.restcode.resource.OwnerResource;
import com.restcode.restcode.resource.SaveConsultantResource;
import com.restcode.restcode.resource.SaveOwnerResource;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@Tag(name="Owners", description ="Owners API")
@RestController
@RequestMapping("/api")
public class OwnerController {
@Autowired
private ModelMapper mapper;
@Autowired
private IOwnerService ownerService;
private Owner convertToEntity(SaveOwnerResource resource) {
return mapper.map(resource, Owner.class);
}
private OwnerResource convertToResource(Owner entity) {
return mapper.map(entity, OwnerResource.class);
}
@Operation(summary="Get All Owners")
@GetMapping("/owners")
public Page<OwnerResource> getAllOwners(Pageable pageable) {
Page<Owner> ownersPage = ownerService.getAllOwners(pageable);
List<OwnerResource> resources = ownersPage.getContent()
.stream().map(this::convertToResource)
.collect(Collectors.toList());
return new PageImpl<>(resources, pageable, resources.size());
}
@Operation(summary="Get Owner")
@GetMapping("/owners/{ownerId}")
public OwnerResource getOwnerById(@PathVariable(value = "ownerId") Long ownerId) {
return convertToResource(ownerService.getOwnerById(ownerId));
}
@Operation(summary="Create Owner")
@PostMapping("plans/{planId}/owners")
public OwnerResource createOwner(@PathVariable(value = "planId") Long planId,
@Valid @RequestBody SaveOwnerResource resource){
return convertToResource(ownerService.createOwner(planId,convertToEntity(resource)));
}
@Operation(summary="Update Owner")
@PutMapping("/owners/{ownerId}")
public OwnerResource updateOwner(@PathVariable Long ownerId,
@Valid @RequestBody SaveOwnerResource resource) {
Owner owner = convertToEntity(resource);
return convertToResource(
ownerService.updateOwner(ownerId, owner));
}
@Operation(summary="Assign Plan To Owner")
@PostMapping("/posts/{ownerId}/tags/{planId}")
public OwnerResource assignOwnerPlan(
@PathVariable(name = "ownerId") Long ownerId,
@PathVariable(name = "planId") Long planId) {
return convertToResource(ownerService.assignOwnerPlan(ownerId, planId));
}
}
|
package com.example.service.impl;
import com.example.entity.Product;
import com.example.entity.ProductCategory;
import com.example.entity.User;
import com.example.service.NotificationService;
import com.example.service.UserService;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
public class NotificationServiceImpl implements NotificationService {
private final UserService userService = new UserServiceImpl();
@Override
public void notifyUserByProduct(Product product) {
Objects.requireNonNull(product, "Product can`t be null");
calculatePriorityForNotification(product)
.forEach(u -> System.out.println("Sending email to " + u.getName() + "..."));
}
private List<User> calculatePriorityForNotification(Product product) {
List<User> fifoNotificationByPriority = new LinkedList<>();
userService.subscribedUsers(product).stream()
.sorted(Comparator.comparing(User::isPremium)
.thenComparing(user -> user.getAge() > 70 && product.getCategory() == ProductCategory.MEDICAL)
.thenComparing(user -> user.getAge() > 70).reversed())
.forEach(fifoNotificationByPriority::add);
return fifoNotificationByPriority;
}
}
|
package br.com.lucro.manager.service.impl;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import br.com.lucro.manager.dao.FileOperationResumeOutstandingBalanceCieloDAO;
import br.com.lucro.manager.model.FileHeaderCielo;
import br.com.lucro.manager.model.FileOperationResumeOutstandingBalanceCielo;
import br.com.lucro.manager.service.FileOperationResumeOutstandingBalanceCieloService;
public class FileOperationResumeOutstandingBalanceCieloServiceImpl implements FileOperationResumeOutstandingBalanceCieloService {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(FileOperationResumeOutstandingBalanceCieloServiceImpl.class);
@Inject
private FileOperationResumeOutstandingBalanceCieloDAO dao;
@Override
public FileOperationResumeOutstandingBalanceCielo processOperation(String line, FileHeaderCielo fileHeaderCielo) throws Exception {
FileOperationResumeOutstandingBalanceCielo balance = new FileOperationResumeOutstandingBalanceCielo();
Pattern search = Pattern.compile("^(\\d{1})(\\d{10})(\\d{7})(\\d{6})(.{10})(.{21})(\\d{3})(\\d{3})(\\d{8})(\\d{8})(\\d{8})(\\d{8})([\\+\\-]{1})(\\d{15})([\\+\\-]{1})(\\d{15})([\\+\\-]{1})(\\d{15})([\\+\\-]{1})(\\d{15})([\\+\\-]{1})(\\d{15})(.{1})(.{1})(.{2})(.{2})([\\+\\-]{1})(\\d{15})(\\d{3})([\\+\\-]{1})(\\d{15})(\\d{22})");
Matcher matcher = search.matcher(line);
if(!matcher.find()) throw new Exception("Dados não correnpondem ao padrão especificado!");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
balance.setHeader(fileHeaderCielo);
balance.setEstablishmentNumber(matcher.group(2));
balance.setOperationResumeLotNumber(matcher.group(3));
balance.setReferenceDate(new SimpleDateFormat("MMyyyy").parse(matcher.group(4)));
balance.setPlatformType(matcher.group(5).trim());
balance.setReleaseType(matcher.group(6).trim().isEmpty() ? null : matcher.group(6).trim());
balance.setCardFlagId(Integer.parseInt(matcher.group(7)));
balance.setSalesReceiptSize(Integer.parseInt(matcher.group(8)));
balance.setTransferDate(dateFormat.parse(matcher.group(9)));
balance.setCatchDate((matcher.group(10).trim().isEmpty() || Integer.parseInt(matcher.group(10))==0) ? null : dateFormat.parse(matcher.group(10)));
balance.setPaymentForecastDate(dateFormat.parse(matcher.group(11)));
balance.setPaymentDate((matcher.group(12).trim().isEmpty() || Integer.parseInt(matcher.group(12))==0) ? null : dateFormat.parse(matcher.group(12)));
balance.setGrossValue((Double.parseDouble(matcher.group(14)) / (double)100) * (matcher.group(13).equals("-")?-1:1));
balance.setNetValue((Double.parseDouble(matcher.group(16)) / (double)100) * (matcher.group(15).equals("-")?-1:1));
balance.setAnticipatedValue((Double.parseDouble(matcher.group(18)) / (double)100) * (matcher.group(17).equals("-")?-1:1));
balance.setToCompensateValue((Double.parseDouble(matcher.group(20)) / (double)100) * (matcher.group(19).equals("-")?-1:1));
balance.setCededValue((Double.parseDouble(matcher.group(22)) / (double)100) * (matcher.group(21).equals("-")?-1:1));
balance.setCurrency(matcher.group(23));
balance.setCededIndicator(matcher.group(24).trim().isEmpty() ? null : matcher.group(24));
balance.setPaymentSplitSize(Integer.parseInt(matcher.group(25)));
balance.setPaymentPendingParcelsSize(Integer.parseInt(matcher.group(26)));
balance.setNegotiatedValue((Double.parseDouble(matcher.group(28)) / (double)100) * (matcher.group(27).equals("-")?-1:1));
balance.setNegotiatedParcelsSize(Integer.parseInt(matcher.group(29)));
balance.setPendingPaymentValue((Double.parseDouble(matcher.group(31)) / (double)100) * (matcher.group(30).equals("-")?-1:1));
balance.setOperationResumeNumber(matcher.group(32));
if(!dao.exists(balance)){
dao.create(balance);
}else{
balance = dao.select(balance);
}
return balance;
}
}
|
package com.sportzcourt.booking.ui.fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sportzcourt.booking.R;
/**
* Copyright 2016 (C) Happiest Minds Pvt Ltd..
*
* <P> A placeholder fragment containing a simple view.
*
* <P>Notes:
* <P>Dependency:
*
* @authors Ravindra Kamble (ravindra.kambale@happiestminds.com)
*
* @created on: 4-Jan-2016
*/
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
|
/*
* Origin of the benchmark:
* repo: https://github.com/diffblue/cbmc.git
* branch: develop
* directory: regression/jbmc-strings/StringCompare01
* The benchmark was taken from the repo: 24 January 2018
*/
public class Main
{
public static void main(String[] args)
{
String s1 = new String("test");
String s2 = "goodbye";
String s3 = "Automatic Test Generation";
String s4 = "automatic test generation";
if (s1.equals("test")) // true
assert true;
else
assert false;
if (s1 != "test") // true; they are not the same object
assert true;
else
assert false;
if (s3.equalsIgnoreCase(s4)) // true
assert true;
else
assert false;
assert s1.compareTo(s2)==13; //true
assert s2.compareTo(s1)==-13; //true
assert s1.compareTo(s1)==0; //true
assert s3.compareTo(s4)==-32; //true
assert s4.compareTo(s3)==32; //true
// test regionMatches (case sensitive)
if (!s3.regionMatches(0, s4, 0, 5)) //true
assert true;
else
assert false;
// test regionMatches (ignore case)
if (s3.regionMatches(true, 0, s4, 0, 5)) //true
assert true;
else
assert false;
}
}
|
package com.sparshik.yogicapple.model;
import java.util.HashMap;
/**
* data structure for group chat
*/
public class ChatMessage {
private String text;
private String nickName;
private String userProfilePicUrl;
private boolean flagged;
private HashMap<String, Object> timestampCreated;
public ChatMessage() {
}
public ChatMessage(String text, String nickName, String userProfilePicUrl, HashMap<String, Object> timestampCreated) {
this.text = text;
this.nickName = nickName;
this.userProfilePicUrl = userProfilePicUrl;
this.flagged = false;
this.timestampCreated = timestampCreated;
}
public String getText() {
return text;
}
public String getNickName() {
return nickName;
}
public String getUserProfilePicUrl() {
return userProfilePicUrl;
}
public boolean isFlagged() {
return flagged;
}
public HashMap<String, Object> getTimestampCreated() {
return timestampCreated;
}
} |
package com.company.test.dao;
import java.io.Serializable;
import com.company.test.entity.Person;
/**
* 测试dao
* @author Dongfuming
* 2016-5-6 下午5:02:04
*/
public interface TestDao {
public boolean savePerson(Person person);
public Person findPersonById(Serializable id);
}
|
public class AlgorithmNF extends Algorithm {
private long l = 0L;
public String getName() {
return "nf";
}
public long getL() {
return l;
}
public void f(long n) {
for (long i = 0; i < n; i++) {
l++;
f(n - 1);
}
}
}
|
import java.util.Scanner;
class InvalidAtmpinnumberException extends Exception
{
Long pin;
int n=0;
void checkpin(Long pin) throws InvalidAtmpinnumberException
{
this.pin=pin;
while(pin>0)
{
pin=pin/10;
n++;
}
if(n!=4)
{
throw new InvalidAtmpinnumberException();
}
else
{
System.out.println("valid pin number");
}
}
}
class CustomException
{
public static void main(String args[])
{
Long pin;
System.out.println("enter pin number");
Scanner s=new Scanner(System.in);
pin=s.nextLong();
InvalidAtmpinnumberException i=new InvalidAtmpinnumberException();
try
{
i.checkpin(pin);
}
catch(InvalidAtmpinnumberException e)
{
System.out.println(e);
}
}
} |
package com.example.citiesapi.configuration;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.context.annotation.Bean;
import java.time.Duration;
@org.springframework.context.annotation.Configuration
public class Configuration {
@Bean
public RateLimiter rateLimiter() {
return RateLimiter.create(0.1d, Duration.ofSeconds(30));
}
}
//Reference: https://github.com/ekim197711/springboot-guava-ratelimiter
|
package com.zareca.spring.formework.annotation;
import java.lang.annotation.*;
/**
* @Auther: ly
* @Date: 2020/12/6 20:37
* @Description:
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ZARequestMapping {
String value() default "";
}
|
package first.task.android;
import java.io.Serializable;
/**
* Simple class to represent item with its name and boolean value
*/
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private boolean checked;
public Item(String name) {
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
/* if (checked == true) checked = false; else checked = true; */
public void switchChecked() {
this.checked ^= true;
}
@Override public String toString() {
return getName();
}
@Override public boolean equals(Object o) {
if (o == null || !(o instanceof Item)) return false;
return this.name.equals(((Item) o).name);
}
} |
package com.lovers.java;
/**
* Created by wangzefeng on 2019/11/8 0008.
*/
public class Demo {
public static void main(String[] args) {
String s="大萨达多";
System.out.println(s.indexOf("大"));
}
}
|
package dto.user.menu.submenu;
import dto.listados.TipoEstatusDTO;
public class SubMenuDTO {
private int idAction;
private int fkApp;
private String nombreMenu;
private String nombreAction;
private String urlAction;
private String iconoAction;
private int isHeader;
private TipoEstatusDTO isHeaderSubmenuDTO;
private int statusAction;
private TipoEstatusDTO estatusSubmenuDTO;
/**
* CONSTRUCTOR
*/
public SubMenuDTO(){
this.setIdAction(-1);
if(this.getEstatusSubmenuDTO() == null){
this.setEstatusSubmenuDTO(new TipoEstatusDTO());
}
if(this.getIsHeaderSubmenuDTO() == null){
this.setIsHeaderSubmenuDTO(new TipoEstatusDTO());
}
}
public int getIdAction() {
return idAction;
}
public void setIdAction(int idAction) {
this.idAction = idAction;
}
public int getFkApp() {
return fkApp;
}
public void setFkApp(int fkApp) {
this.fkApp = fkApp;
}
public String getNombreAction() {
return nombreAction;
}
public void setNombreAction(String nombreAction) {
this.nombreAction = nombreAction;
}
public String getUrlAction() {
return urlAction;
}
public void setUrlAction(String urlAction) {
this.urlAction = urlAction;
}
public int getStatusAction() {
return statusAction;
}
public void setStatusAction(int statusAction) {
this.statusAction = statusAction;
}
public int getIsHeader() {
return isHeader;
}
public void setIsHeader(int isHeader) {
this.isHeader = isHeader;
}
public String getIconoAction() {
return iconoAction;
}
public void setIconoAction(String iconoAction) {
this.iconoAction = iconoAction;
}
public String getNombreMenu() {
return nombreMenu;
}
public void setNombreMenu(String nombreMenu) {
this.nombreMenu = nombreMenu;
}
public TipoEstatusDTO getEstatusSubmenuDTO() {
return estatusSubmenuDTO;
}
public void setEstatusSubmenuDTO(TipoEstatusDTO estatusSubmenuDTO) {
this.estatusSubmenuDTO = estatusSubmenuDTO;
}
public TipoEstatusDTO getIsHeaderSubmenuDTO() {
return isHeaderSubmenuDTO;
}
public void setIsHeaderSubmenuDTO(TipoEstatusDTO isHeaderSubmenuDTO) {
this.isHeaderSubmenuDTO = isHeaderSubmenuDTO;
}
}
|
//(c) A+ Computer Science
//www.apluscompsci.com
//Name: Adham Elarabawy
public class RayOddToEven {
public static int go(int[] ray) {
int counter = 0;
for (int i = 0; i < ray.length; i++) {
if (ray[i] % 2 != 0) {
for (int j = i+1; j < ray.length; j++) {
counter++;
if (ray[j] % 2 == 0) {
return counter;
}
}
}
}
return -1;
}
} |
package test;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.news.pojo.News;
import com.news.pojo.Users;
import com.spring.service.CommentsServices;
import com.spring.service.NewsService;
import com.spring.service.UserServices;
public class Test1 {
//登录
@Test
public void testLoginUser() throws Exception {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserServices userService = (UserServices) context.getBean("userServices");
Users user = userService.getUser("sa", "sa");
if(user != null){
System.out.println("成功");
}
}
//注册
@Test
public void testRegUser() throws Exception {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserServices userService = (UserServices) context.getBean("userServices");
Users u = new Users();
u.setUname("kasa");
u.setUpwd("123456");
int res = userService.regUser(u);
if(res>0){
System.out.println("注册成功");
}
}
//新闻添加
@Test
public void testSaveComments() throws Exception {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
CommentsServices commentsServices = (CommentsServices) context.getBean("commentsServices");
int res = commentsServices.saveComments(48, "2134324", "321312", "23213", new Date());
if(res>0){
System.out.println("添加成功");
}
}
//新闻
@Test
public void testGetAllNewsCount() throws Exception {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
NewsService newsService = (NewsService) context.getBean("newsServiceImpl");
int res = newsService.getAllNewsCount(3);
System.out.println(res);
}
@Test
public void testSelectNews() throws Exception {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
NewsService newsService = (NewsService) context.getBean("newsServiceImpl");
List<News> data = newsService.getAllNews(1,2);
System.out.println(data.size());
}
}
|
package com.alex.eat;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SuperBasket<E extends Weigh> implements Weigh {
private Set<E> elements;
public SuperBasket(int size) {
this.elements = new HashSet<>(size);
}
public SuperBasket() {
this.elements = new HashSet<>();
}
public void addElement(E element) {
elements.add(element);
}
public E getElement() {
Iterator<E> iterator = elements.iterator();
if (iterator.hasNext()) {
E nextElem = iterator.next();
elements.remove(nextElem);
return nextElem;
} else {
throw new IllegalStateException("Sorry, no elements in basket!");
}
}
public Set<E> getAllElements() {
return Collections.unmodifiableSet(elements);
}
public int getCurrentSize() {
return elements.size();
}
@Override
public int getWeight() {
int sum = 0;
//3 variant
/* for (E element : elements) {
if (element != null) {
sum = sum + element.getWeight();
}
}*/
//4 variant
sum = elements.stream().mapToInt(E::getWeight).sum();
return sum;
}
}
|
package org.git;
public class GitHub {
public static void main(String[] args) {
System.out.println("123455");
System.out.println("1234678");
System.out.println("123");
System.out.println("12333");
}
}
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.serialization.impl.compact;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class CompactTestUtil {
private CompactTestUtil() {
}
public static SchemaService createInMemorySchemaService() {
return new SchemaService() {
private final Map<Long, Schema> schemas = new ConcurrentHashMap<>();
@Override
public Schema get(long schemaId) {
return schemas.get(schemaId);
}
@Override
public void put(Schema schema) {
long schemaId = schema.getSchemaId();
Schema existingSchema = schemas.putIfAbsent(schemaId, schema);
if (existingSchema != null && !schema.equals(existingSchema)) {
throw new IllegalStateException("Schema with schemaId " + schemaId + " already exists. "
+ "existing schema " + existingSchema
+ "new schema " + schema);
}
}
@Override
public void putLocal(Schema schema) {
put(schema);
}
};
}
}
|
package com.example.shivam.maintain_notes;
import android.app.ActionBar;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Notes7 extends AppCompatActivity {
EditText e2,e21,e22,e23,e24,e25,e26,e27,e28,e29,e30,e31,e32,e33,e34,e35,e36,e37,e38,e39;
EditText e40,e41,e42,e43,e44,e45,e46,e47,e48,e49,e50,e51,e52,e53,e54,e55,e56,e57,e58,e59;
Button bdelete;
String string="null";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes5);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button bsave=(Button)findViewById(R.id.button2);//Save button
bsave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 1- 10
try {
FileOutputStream fos = openFileOutput("7data",Context.MODE_PRIVATE);
e2=(EditText)findViewById(R.id.editText2);
string=e2.getText().toString();
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos1 = openFileOutput("7data1",Context.MODE_PRIVATE);
e21=(EditText)findViewById(R.id.editText21);
string=e21.getText().toString();
fos1.write(string.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput("7data2",Context.MODE_PRIVATE);
e22=(EditText)findViewById(R.id.editText22);
string=e22.getText().toString();
fos2.write(string.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput("7data3",Context.MODE_PRIVATE);
e23=(EditText)findViewById(R.id.editText23);
string=e23.getText().toString();
fos3.write(string.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput("7data4",Context.MODE_PRIVATE);
e24=(EditText)findViewById(R.id.editText24);
string=e24.getText().toString();
fos4.write(string.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput("7data5",Context.MODE_PRIVATE);
e25=(EditText)findViewById(R.id.editText25);
string=e25.getText().toString();
fos5.write(string.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos6 = openFileOutput("7data6",Context.MODE_PRIVATE);
e26=(EditText)findViewById(R.id.editText26);
string=e26.getText().toString();
fos6.write(string.getBytes());
fos6.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos7 = openFileOutput("7data7",Context.MODE_PRIVATE);
e27=(EditText)findViewById(R.id.editText27);
string=e27.getText().toString();
fos7.write(string.getBytes());
fos7.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos8= openFileOutput("7data8",Context.MODE_PRIVATE);
e28=(EditText)findViewById(R.id.editText28);
string=e28.getText().toString();
fos8.write(string.getBytes());
fos8.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos9 = openFileOutput("7data9",Context.MODE_PRIVATE);
e29=(EditText)findViewById(R.id.editText29);
string=e29.getText().toString();
fos9.write(string.getBytes());
fos9.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 11 - 20
try {
FileOutputStream fos = openFileOutput("7data10",Context.MODE_PRIVATE);
e30=(EditText)findViewById(R.id.editText30);
string=e30.getText().toString();
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos1 = openFileOutput("7data11",Context.MODE_PRIVATE);
e31=(EditText)findViewById(R.id.editText31);
string=e31.getText().toString();
fos1.write(string.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput("7data12",Context.MODE_PRIVATE);
e32=(EditText)findViewById(R.id.editText32);
string=e32.getText().toString();
fos2.write(string.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput("7data13",Context.MODE_PRIVATE);
e33=(EditText)findViewById(R.id.editText33);
string=e33.getText().toString();
fos3.write(string.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput("7data14",Context.MODE_PRIVATE);
e34=(EditText)findViewById(R.id.editText34);
string=e34.getText().toString();
fos4.write(string.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput("7data15",Context.MODE_PRIVATE);
e35=(EditText)findViewById(R.id.editText35);
string=e35.getText().toString();
fos5.write(string.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos6 = openFileOutput("7data16",Context.MODE_PRIVATE);
e36=(EditText)findViewById(R.id.editText36);
string=e36.getText().toString();
fos6.write(string.getBytes());
fos6.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos7 = openFileOutput("7data17",Context.MODE_PRIVATE);
e37=(EditText)findViewById(R.id.editText37);
string=e37.getText().toString();
fos7.write(string.getBytes());
fos7.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos8= openFileOutput("7data18",Context.MODE_PRIVATE);
e38=(EditText)findViewById(R.id.editText38);
string=e38.getText().toString();
fos8.write(string.getBytes());
fos8.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos9 = openFileOutput("7data19",Context.MODE_PRIVATE);
e39=(EditText)findViewById(R.id.editText39);
string=e39.getText().toString();
fos9.write(string.getBytes());
fos9.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//21-40
try {
FileOutputStream fos = openFileOutput("7data20",Context.MODE_PRIVATE);
e40=(EditText)findViewById(R.id.editText40);
string=e40.getText().toString();
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos1 = openFileOutput("7data21",Context.MODE_PRIVATE);
e41=(EditText)findViewById(R.id.editText41);
string=e41.getText().toString();
fos1.write(string.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput("7data22",Context.MODE_PRIVATE);
e42=(EditText)findViewById(R.id.editText42);
string=e42.getText().toString();
fos2.write(string.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput("7data23",Context.MODE_PRIVATE);
e43=(EditText)findViewById(R.id.editText43);
string=e43.getText().toString();
fos3.write(string.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput("7data24",Context.MODE_PRIVATE);
e44=(EditText)findViewById(R.id.editText44);
string=e44.getText().toString();
fos4.write(string.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput("7data25",Context.MODE_PRIVATE);
e45=(EditText)findViewById(R.id.editText45);
string=e45.getText().toString();
fos5.write(string.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos6 = openFileOutput("7data26",Context.MODE_PRIVATE);
e46=(EditText)findViewById(R.id.editText46);
string=e46.getText().toString();
fos6.write(string.getBytes());
fos6.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos7 = openFileOutput("7data27",Context.MODE_PRIVATE);
e47=(EditText)findViewById(R.id.editText47);
string=e47.getText().toString();
fos7.write(string.getBytes());
fos7.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos8= openFileOutput("7data28",Context.MODE_PRIVATE);
e48=(EditText)findViewById(R.id.editText48);
string=e48.getText().toString();
fos8.write(string.getBytes());
fos8.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos9 = openFileOutput("7data29",Context.MODE_PRIVATE);
e49=(EditText)findViewById(R.id.editText49);
string=e49.getText().toString();
fos9.write(string.getBytes());
fos9.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 11 - 20
try {
FileOutputStream fos = openFileOutput("7data30",Context.MODE_PRIVATE);
e50=(EditText)findViewById(R.id.editText50);
string=e50.getText().toString();
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos1 = openFileOutput("7data31",Context.MODE_PRIVATE);
e51=(EditText)findViewById(R.id.editText51);
string=e51.getText().toString();
fos1.write(string.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput("7data32",Context.MODE_PRIVATE);
e52=(EditText)findViewById(R.id.editText52);
string=e52.getText().toString();
fos2.write(string.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput("7data33",Context.MODE_PRIVATE);
e53=(EditText)findViewById(R.id.editText53);
string=e53.getText().toString();
fos3.write(string.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput("7data34",Context.MODE_PRIVATE);
e54=(EditText)findViewById(R.id.editText54);
string=e54.getText().toString();
fos4.write(string.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput("7data35",Context.MODE_PRIVATE);
e55=(EditText)findViewById(R.id.editText55);
string=e55.getText().toString();
fos5.write(string.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos6 = openFileOutput("7data36",Context.MODE_PRIVATE);
e56=(EditText)findViewById(R.id.editText56);
string=e56.getText().toString();
fos6.write(string.getBytes());
fos6.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos7 = openFileOutput("7data37",Context.MODE_PRIVATE);
e57=(EditText)findViewById(R.id.editText57);
string=e57.getText().toString();
fos7.write(string.getBytes());
fos7.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos8= openFileOutput("7data38",Context.MODE_PRIVATE);
e58=(EditText)findViewById(R.id.editText58);
string=e58.getText().toString();
fos8.write(string.getBytes());
fos8.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos9 = openFileOutput("7data39",Context.MODE_PRIVATE);
e59=(EditText)findViewById(R.id.editText59);
string=e59.getText().toString();
fos9.write(string.getBytes());
fos9.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent=new Intent(getApplicationContext(),Notes1.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
Button bdelete=(Button)findViewById(R.id.bdelete);
bdelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) { //Delete
AlertDialog.Builder builder=new AlertDialog.Builder(Notes7.this);
builder.setMessage("Are you sure?").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//code 1 -10
deleteFile("7data");
deleteFile("7data1");
deleteFile("7data2");
deleteFile("7data3");
deleteFile("7data4");
deleteFile("7data5");
deleteFile("7data6");
deleteFile("7data7");
deleteFile("7data8");
deleteFile("7data9");
//11-20
deleteFile("7data10");
deleteFile("7data11");
deleteFile("7data12");
deleteFile("7data13");
deleteFile("7data14");
deleteFile("7data15");
deleteFile("7data16");
deleteFile("7data17");
deleteFile("7data18");
deleteFile("7data19");
//21-30
deleteFile("7data20");
deleteFile("7data21");
deleteFile("7data22");
deleteFile("7data23");
deleteFile("7data24");
deleteFile("7data25");
deleteFile("7data26");
deleteFile("7data27");
deleteFile("7data28");
deleteFile("7data29");
//31-40
deleteFile("7data30");
deleteFile("7data31");
deleteFile("7data32");
deleteFile("7data33");
deleteFile("7data34");
deleteFile("7data35");
deleteFile("7data36");
deleteFile("7data37");
deleteFile("7data38");
deleteFile("7data39");
Intent intent=new Intent(getApplicationContext(),Notes1.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_SHORT).show();
}
}
).setNegativeButton("cancel",null);
AlertDialog alert=builder.create();
alert.show();
}
});
try {
FileInputStream fis=(FileInputStream)openFileInput("7data");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
e2=(EditText)findViewById(R.id.editText2);
e2.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis1=(FileInputStream)openFileInput("7data1");
InputStreamReader isr1 = new InputStreamReader(fis1);
BufferedReader bufferedReader1 = new BufferedReader(isr1);
StringBuilder sb1 = new StringBuilder();
String line;
while ((line = bufferedReader1.readLine()) != null) {
e21=(EditText)findViewById(R.id.editText21);
e21.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis2=(FileInputStream)openFileInput("7data2");
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader bufferedReader2 = new BufferedReader(isr2);
StringBuilder sb2 = new StringBuilder();
String line;
while ((line = bufferedReader2.readLine()) != null) {
e22=(EditText)findViewById(R.id.editText22);
e22.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis3=(FileInputStream)openFileInput("7data3");
InputStreamReader isr3 = new InputStreamReader(fis3);
BufferedReader bufferedReader3 = new BufferedReader(isr3);
StringBuilder sb3 = new StringBuilder();
String line;
while ((line = bufferedReader3.readLine()) != null) {
e23=(EditText)findViewById(R.id.editText23);
e23.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis4=(FileInputStream)openFileInput("7data4");
InputStreamReader isr4 = new InputStreamReader(fis4);
BufferedReader bufferedReader4 = new BufferedReader(isr4);
StringBuilder sb4 = new StringBuilder();
String line;
while ((line = bufferedReader4.readLine()) != null) {
e24=(EditText)findViewById(R.id.editText24);
e24.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis5=(FileInputStream)openFileInput("7data5");
InputStreamReader isr5 = new InputStreamReader(fis5);
BufferedReader bufferedReader5 = new BufferedReader(isr5);
StringBuilder sb5 = new StringBuilder();
String line;
while ((line = bufferedReader5.readLine()) != null) {
e25=(EditText)findViewById(R.id.editText25);
e25.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis6=(FileInputStream)openFileInput("7data6");
InputStreamReader isr6 = new InputStreamReader(fis6);
BufferedReader bufferedReader6 = new BufferedReader(isr6);
StringBuilder sb6 = new StringBuilder();
String line;
while ((line = bufferedReader6.readLine()) != null) {
e26=(EditText)findViewById(R.id.editText26);
e26.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis7=(FileInputStream)openFileInput("7data7");
InputStreamReader isr7 = new InputStreamReader(fis7);
BufferedReader bufferedReader7 = new BufferedReader(isr7);
StringBuilder sb7 = new StringBuilder();
String line;
while ((line = bufferedReader7.readLine()) != null) {
e27=(EditText)findViewById(R.id.editText27);
e27.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis8=(FileInputStream)openFileInput("7data8");
InputStreamReader isr8 = new InputStreamReader(fis8);
BufferedReader bufferedReader8 = new BufferedReader(isr8);
StringBuilder sb8 = new StringBuilder();
String line;
while ((line = bufferedReader8.readLine()) != null) {
e28=(EditText)findViewById(R.id.editText28);
e28.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis9=(FileInputStream)openFileInput("7data9");
InputStreamReader isr9 = new InputStreamReader(fis9);
BufferedReader bufferedReader9 = new BufferedReader(isr9);
StringBuilder sb9 = new StringBuilder();
String line;
while ((line = bufferedReader9.readLine()) != null) {
e29=(EditText)findViewById(R.id.editText29);
e29.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//11-20
try {
FileInputStream fis=(FileInputStream)openFileInput("7data10");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
e30=(EditText)findViewById(R.id.editText30);
e30.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis1=(FileInputStream)openFileInput("7data11");
InputStreamReader isr1 = new InputStreamReader(fis1);
BufferedReader bufferedReader1 = new BufferedReader(isr1);
StringBuilder sb1 = new StringBuilder();
String line;
while ((line = bufferedReader1.readLine()) != null) {
e31=(EditText)findViewById(R.id.editText31);
e31.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis2=(FileInputStream)openFileInput("7data12");
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader bufferedReader2 = new BufferedReader(isr2);
StringBuilder sb2 = new StringBuilder();
String line;
while ((line = bufferedReader2.readLine()) != null) {
e32=(EditText)findViewById(R.id.editText32);
e32.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis3=(FileInputStream)openFileInput("7data13");
InputStreamReader isr3 = new InputStreamReader(fis3);
BufferedReader bufferedReader3 = new BufferedReader(isr3);
StringBuilder sb3 = new StringBuilder();
String line;
while ((line = bufferedReader3.readLine()) != null) {
e33=(EditText)findViewById(R.id.editText33);
e33.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis4=(FileInputStream)openFileInput("7data14");
InputStreamReader isr4 = new InputStreamReader(fis4);
BufferedReader bufferedReader4 = new BufferedReader(isr4);
StringBuilder sb4 = new StringBuilder();
String line;
while ((line = bufferedReader4.readLine()) != null) {
e34=(EditText)findViewById(R.id.editText34);
e34.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis5=(FileInputStream)openFileInput("7data15");
InputStreamReader isr5 = new InputStreamReader(fis5);
BufferedReader bufferedReader5 = new BufferedReader(isr5);
StringBuilder sb5 = new StringBuilder();
String line;
while ((line = bufferedReader5.readLine()) != null) {
e35=(EditText)findViewById(R.id.editText35);
e35.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis6=(FileInputStream)openFileInput("7data16");
InputStreamReader isr6 = new InputStreamReader(fis6);
BufferedReader bufferedReader6 = new BufferedReader(isr6);
StringBuilder sb6 = new StringBuilder();
String line;
while ((line = bufferedReader6.readLine()) != null) {
e36=(EditText)findViewById(R.id.editText36);
e36.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis7=(FileInputStream)openFileInput("7data17");
InputStreamReader isr7 = new InputStreamReader(fis7);
BufferedReader bufferedReader7 = new BufferedReader(isr7);
StringBuilder sb7 = new StringBuilder();
String line;
while ((line = bufferedReader7.readLine()) != null) {
e37=(EditText)findViewById(R.id.editText37);
e37.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis8=(FileInputStream)openFileInput("7data18");
InputStreamReader isr8 = new InputStreamReader(fis8);
BufferedReader bufferedReader8 = new BufferedReader(isr8);
StringBuilder sb8 = new StringBuilder();
String line;
while ((line = bufferedReader8.readLine()) != null) {
e38=(EditText)findViewById(R.id.editText38);
e38.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis9=(FileInputStream)openFileInput("7data19");
InputStreamReader isr9 = new InputStreamReader(fis9);
BufferedReader bufferedReader9 = new BufferedReader(isr9);
StringBuilder sb9 = new StringBuilder();
String line;
while ((line = bufferedReader9.readLine()) != null) {
e39=(EditText)findViewById(R.id.editText39);
e39.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//21-30
try {
FileInputStream fis=(FileInputStream)openFileInput("7data20");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
e40=(EditText)findViewById(R.id.editText40);
e40.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis1=(FileInputStream)openFileInput("7data21");
InputStreamReader isr1 = new InputStreamReader(fis1);
BufferedReader bufferedReader1 = new BufferedReader(isr1);
StringBuilder sb1 = new StringBuilder();
String line;
while ((line = bufferedReader1.readLine()) != null) {
e41=(EditText)findViewById(R.id.editText41);
e41.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis2=(FileInputStream)openFileInput("7data22");
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader bufferedReader2 = new BufferedReader(isr2);
StringBuilder sb2 = new StringBuilder();
String line;
while ((line = bufferedReader2.readLine()) != null) {
e42=(EditText)findViewById(R.id.editText42);
e42.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis3=(FileInputStream)openFileInput("7data23");
InputStreamReader isr3 = new InputStreamReader(fis3);
BufferedReader bufferedReader3 = new BufferedReader(isr3);
StringBuilder sb3 = new StringBuilder();
String line;
while ((line = bufferedReader3.readLine()) != null) {
e43=(EditText)findViewById(R.id.editText43);
e43.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis4=(FileInputStream)openFileInput("7data24");
InputStreamReader isr4 = new InputStreamReader(fis4);
BufferedReader bufferedReader4 = new BufferedReader(isr4);
StringBuilder sb4 = new StringBuilder();
String line;
while ((line = bufferedReader4.readLine()) != null) {
e44=(EditText)findViewById(R.id.editText44);
e44.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis5=(FileInputStream)openFileInput("7data25");
InputStreamReader isr5 = new InputStreamReader(fis5);
BufferedReader bufferedReader5 = new BufferedReader(isr5);
StringBuilder sb5 = new StringBuilder();
String line;
while ((line = bufferedReader5.readLine()) != null) {
e45=(EditText)findViewById(R.id.editText45);
e45.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis6=(FileInputStream)openFileInput("7data26");
InputStreamReader isr6 = new InputStreamReader(fis6);
BufferedReader bufferedReader6 = new BufferedReader(isr6);
StringBuilder sb6 = new StringBuilder();
String line;
while ((line = bufferedReader6.readLine()) != null) {
e46=(EditText)findViewById(R.id.editText46);
e46.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis7=(FileInputStream)openFileInput("7data27");
InputStreamReader isr7 = new InputStreamReader(fis7);
BufferedReader bufferedReader7 = new BufferedReader(isr7);
StringBuilder sb7 = new StringBuilder();
String line;
while ((line = bufferedReader7.readLine()) != null) {
e47=(EditText)findViewById(R.id.editText47);
e47.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis8=(FileInputStream)openFileInput("7data28");
InputStreamReader isr8 = new InputStreamReader(fis8);
BufferedReader bufferedReader8 = new BufferedReader(isr8);
StringBuilder sb8 = new StringBuilder();
String line;
while ((line = bufferedReader8.readLine()) != null) {
e48=(EditText)findViewById(R.id.editText48);
e48.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis9=(FileInputStream)openFileInput("7data29");
InputStreamReader isr9 = new InputStreamReader(fis9);
BufferedReader bufferedReader9 = new BufferedReader(isr9);
StringBuilder sb9 = new StringBuilder();
String line;
while ((line = bufferedReader9.readLine()) != null) {
e49=(EditText)findViewById(R.id.editText49);
e49.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//31-40
try {
FileInputStream fis=(FileInputStream)openFileInput("7data30");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
e50=(EditText)findViewById(R.id.editText50);
e50.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis1=(FileInputStream)openFileInput("7data31");
InputStreamReader isr1 = new InputStreamReader(fis1);
BufferedReader bufferedReader1 = new BufferedReader(isr1);
StringBuilder sb1 = new StringBuilder();
String line;
while ((line = bufferedReader1.readLine()) != null) {
e51=(EditText)findViewById(R.id.editText51);
e51.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis2=(FileInputStream)openFileInput("7data32");
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader bufferedReader2 = new BufferedReader(isr2);
StringBuilder sb2 = new StringBuilder();
String line;
while ((line = bufferedReader2.readLine()) != null) {
e52=(EditText)findViewById(R.id.editText52);
e52.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis3=(FileInputStream)openFileInput("7data33");
InputStreamReader isr3 = new InputStreamReader(fis3);
BufferedReader bufferedReader3 = new BufferedReader(isr3);
StringBuilder sb3 = new StringBuilder();
String line;
while ((line = bufferedReader3.readLine()) != null) {
e53=(EditText)findViewById(R.id.editText53);
e53.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis4=(FileInputStream)openFileInput("7data34");
InputStreamReader isr4 = new InputStreamReader(fis4);
BufferedReader bufferedReader4 = new BufferedReader(isr4);
StringBuilder sb4 = new StringBuilder();
String line;
while ((line = bufferedReader4.readLine()) != null) {
e54=(EditText)findViewById(R.id.editText54);
e54.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis5=(FileInputStream)openFileInput("7data35");
InputStreamReader isr5 = new InputStreamReader(fis5);
BufferedReader bufferedReader5 = new BufferedReader(isr5);
StringBuilder sb5 = new StringBuilder();
String line;
while ((line = bufferedReader5.readLine()) != null) {
e55=(EditText)findViewById(R.id.editText55);
e55.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis6=(FileInputStream)openFileInput("7data36");
InputStreamReader isr6 = new InputStreamReader(fis6);
BufferedReader bufferedReader6 = new BufferedReader(isr6);
StringBuilder sb6 = new StringBuilder();
String line;
while ((line = bufferedReader6.readLine()) != null) {
e56=(EditText)findViewById(R.id.editText56);
e56.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis7=(FileInputStream)openFileInput("7data37");
InputStreamReader isr7 = new InputStreamReader(fis7);
BufferedReader bufferedReader7 = new BufferedReader(isr7);
StringBuilder sb7 = new StringBuilder();
String line;
while ((line = bufferedReader7.readLine()) != null) {
e57=(EditText)findViewById(R.id.editText57);
e57.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis8=(FileInputStream)openFileInput("7data38");
InputStreamReader isr8 = new InputStreamReader(fis8);
BufferedReader bufferedReader8 = new BufferedReader(isr8);
StringBuilder sb8 = new StringBuilder();
String line;
while ((line = bufferedReader8.readLine()) != null) {
e58=(EditText)findViewById(R.id.editText58);
e58.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis9=(FileInputStream)openFileInput("7data39");
InputStreamReader isr9 = new InputStreamReader(fis9);
BufferedReader bufferedReader9 = new BufferedReader(isr9);
StringBuilder sb9 = new StringBuilder();
String line;
while ((line = bufferedReader9.readLine()) != null) {
e59=(EditText)findViewById(R.id.editText59);
e59.setText(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options_menu, menu);
return true;
} // menu option
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.Aboutme:
{
Toast.makeText(this, "My name is Shivam Taneja , Pursuing BE in IT from UIET(PU),Chandigarh", Toast.LENGTH_LONG).show();
return true;
}
case R.id.Contactme:
{
Toast.makeText(this, "E-mail me :shivamtaneja1990@gmail.com", Toast.LENGTH_LONG).show();
return true;
}
case R.id.rate_me:
{
Intent intent = new Intent(this, Notes2.class);
startActivity(intent);
Toast.makeText(this, "Please give me stars", Toast.LENGTH_SHORT).show();
return true;
}
case android.R.id.home:
{
Intent intent = new Intent(this, Notes1.class);
startActivity(intent);
}
default:
return true;
}}
@Override
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(Notes7.this);
builder.setMessage("Really exit?").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Notes7.super.onBackPressed();
}
}
).setNegativeButton("cancel",null).setCancelable(false);
AlertDialog alert=builder.create();
alert.show();
}
}
|
package com.itinerary.resort.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.easymock.EasyMock;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.powermock.api.easymock.PowerMock;
import org.powermock.reflect.internal.WhiteboxImpl;
import org.springframework.dao.DataAccessException;
import com.itinerary.resort.model.entity.ResortReservation;
/**
* TestResortDao test class.
* @author akuma408
*
*/
public class TestResortDao {
/**
* bookDiningReservationTest method of test class.
*/
@Test
public void bookDiningReservationTest() {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
ResortReservation resort = new ResortReservation();
SessionFactory sessionFactory = EasyMock.createMock(
SessionFactory.class);
resortDaoImpl.setSessionFactory(sessionFactory);
EasyMock.expect(sessionFactory.getCurrentSession()).andReturn(
EasyMock.createMock(Session.class));
EasyMock.replay(sessionFactory);
resortDaoImpl.bookResortReservation(resort);
}
/**
* bookDiningReservationTest test method.
*/
@Test(expected = DataAccessException.class)
public void bookResortReservationTest() {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
ResortReservation resort = new ResortReservation();
SessionFactory sessionFactory = EasyMock.createMock(
SessionFactory.class);
resortDaoImpl.setSessionFactory(sessionFactory);
EasyMock.expect(sessionFactory.getCurrentSession()).andThrow(
EasyMock.createMock(DataAccessException.class));
EasyMock.replay(sessionFactory);
resortDaoImpl.bookResortReservation(resort);
}
/**
* @throws Exception Exception
*/
@Test
public void tetsprovideResortReservation() throws Exception {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
SessionFactory sessionFactory = PowerMock.createMock(
SessionFactory.class);
Session session = PowerMock.createMock(Session.class);
Query queryMock = PowerMock.createMock(Query.class);
resortDaoImpl.setSessionFactory(sessionFactory);
PowerMock.expectPrivate(sessionFactory, "getCurrentSession").
andReturn(session);
PowerMock.expectPrivate(session, "createQuery", (""
+ "FROM ResortReservation where customerId = :guestID"))
.andReturn(queryMock);
EasyMock.expect(queryMock.setLong("guestID", 1L)).
andReturn(queryMock);
PowerMock.expectPrivate(queryMock, "list").andReturn(
EasyMock.createMock(List.class));
PowerMock.replay(sessionFactory, session, queryMock);
WhiteboxImpl.setInternalState(resortDaoImpl, ""
+ "sessionFactory", sessionFactory);
WhiteboxImpl.invokeMethod(resortDaoImpl, ""
+ "provideResortReservation", 1L);
}
/**
* @throws Exception Exception
*/
@Test
public void tetsprovideResortReservation3() throws Exception {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
SessionFactory sessionFactory = PowerMock.
createMock(SessionFactory.class);
Session session = PowerMock.createMock(Session.class);
Query queryMock = PowerMock.createMock(Query.class);
resortDaoImpl.setSessionFactory(sessionFactory);
PowerMock.expectPrivate(sessionFactory, "getCurrentSession").
andReturn(session);
PowerMock.expectPrivate(session, "createQuery", (""
+ "FROM ResortReservation where customerId = :guestID"))
.andReturn(queryMock);
EasyMock.expect(queryMock.setLong("guestID", 1L)).andReturn(queryMock);
List<ResortReservation> resortReservation = new ArrayList<>();
PowerMock.expectPrivate(queryMock, "list").andReturn(resortReservation);
PowerMock.replay(sessionFactory, session, queryMock);
WhiteboxImpl.setInternalState(resortDaoImpl, ""
+ "sessionFactory", sessionFactory);
WhiteboxImpl.invokeMethod(resortDaoImpl, ""
+ "provideResortReservation", 1L);
}
/**
* @throws Exception
* Exception
*/
@Test(expected = DataAccessException.class)
public void provideResortReservationTest1() throws Exception {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
SessionFactory sessionFactory = PowerMock.
createMock(SessionFactory.class);
Session session = PowerMock.createMock(Session.class);
Query queryMock = PowerMock.createMock(Query.class);
resortDaoImpl.setSessionFactory(sessionFactory);
PowerMock.expectPrivate(sessionFactory, "getCurrentSession").
andReturn(session);
PowerMock.expectPrivate(session, "createQuery", (""
+ "FROM ResortReservation where customerId = :guestID"))
.andThrow(EasyMock.createMock(DataAccessException.class));
PowerMock.replay(sessionFactory, session, queryMock);
WhiteboxImpl.setInternalState(
resortDaoImpl, "sessionFactory", sessionFactory);
WhiteboxImpl.invokeMethod(
resortDaoImpl, "" + "provideResortReservation", 1L);
}
/**
* @throws Exception Exception
*/
@Test
public void cancelResortReservationTest() throws Exception {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
SessionFactory sessionFactory = PowerMock.createMock(
SessionFactory.class);
Session session = PowerMock.createMock(Session.class);
Query queryMock = PowerMock.createMock(Query.class);
resortDaoImpl.setSessionFactory(sessionFactory);
Date date = PowerMock.createMock(Date.class);
PowerMock.expectPrivate(sessionFactory, "getCurrentSession").
andReturn(session);
PowerMock
.expectPrivate(session, "createQuery",
("UPDATE ResortReservation set status = :status, "
+ "updatedate = :updatedate "
+ "WHERE customerId = :customerId and reservationId ="
+ " :reservationId"))
.andReturn(queryMock);
EasyMock.expect(queryMock.setString("status", "Cancelled")).
andReturn(queryMock);
EasyMock.expect(queryMock.setLong("customerId", 1L)).
andReturn(queryMock);
EasyMock.expect(queryMock.setLong("reservationId", 1L)).
andReturn(queryMock);
PowerMock.expectPrivate(System.class, "currentTimeMillis").
andReturn(EasyMock.anyObject(Date.class));
EasyMock.expect(queryMock.setDate("updatedDate",
EasyMock.anyObject(Date.class))).andReturn(queryMock);
EasyMock.expect(queryMock.executeUpdate()).andReturn(1);
PowerMock.replay(sessionFactory, session, queryMock,
date, System.class);
WhiteboxImpl.setInternalState(resortDaoImpl,
"sessionFactory", sessionFactory);
WhiteboxImpl.invokeMethod(resortDaoImpl,
"cancelResortReservation", 1L, 1L);
}
/**
* @throws Exception Exception
*/
@Test
public void cancelResortReservationTest2() throws Exception {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
SessionFactory sessionFactory = PowerMock.
createMock(SessionFactory.class);
Session session = PowerMock.createMock(Session.class);
Query queryMock = PowerMock.createMock(Query.class);
resortDaoImpl.setSessionFactory(sessionFactory);
Date date = PowerMock.createMock(Date.class);
PowerMock.expectPrivate(sessionFactory, "getCurrentSession").
andReturn(session);
PowerMock
.expectPrivate(session, "createQuery",
("UPDATE ResortReservation set status = :status, "
+ "updatedate = :updatedate "
+ "WHERE customerId = :customerId and reservationId ="
+ " :reservationId"))
.andReturn(queryMock);
EasyMock.expect(queryMock.setString("status", "Cancelled")).
andReturn(queryMock);
EasyMock.expect(queryMock.setLong("customerId", 1L)).
andReturn(queryMock);
EasyMock.expect(queryMock.setLong("reservationId", 1L)).
andReturn(queryMock);
PowerMock.expectPrivate(System.class, "currentTimeMillis").
andReturn(EasyMock.anyObject(Date.class));
EasyMock.expect(queryMock.setDate("updatedDate", EasyMock.anyObject(
Date.class))).andReturn(queryMock);
EasyMock.expect(queryMock.executeUpdate()).andReturn(2);
PowerMock.replay(sessionFactory, session, queryMock, date,
System.class);
WhiteboxImpl.setInternalState(resortDaoImpl, "sessionFactory",
sessionFactory);
resortDaoImpl.cancelResortReservation(1L, 1L);
}
/**
* @throws Exception Exception
*/
@Test(expected = DataAccessException.class)
public void cancelResortReservationTest1() throws Exception {
ResortDaoImpl resortDaoImpl = new ResortDaoImpl();
SessionFactory sessionFactory = PowerMock.
createMock(SessionFactory.class);
Session session = PowerMock.createMock(Session.class);
Query queryMock = PowerMock.createMock(Query.class);
resortDaoImpl.setSessionFactory(sessionFactory);
resortDaoImpl.getSessionFactory();
Date date = PowerMock.createMock(Date.class);
PowerMock.expectPrivate(sessionFactory, "getCurrentSession")
.andThrow(EasyMock.createMock(DataAccessException.class));
PowerMock
.expectPrivate(session, "createQuery",
("UPDATE DiningReservation set status = :status, "
+ "updatedDate = :updatedDate "
+ "WHERE customerId = :customerId and reservationId ="
+ " :reservationId"))
.andThrow(EasyMock.createMock(DataAccessException.class));
PowerMock.replay(sessionFactory, session, queryMock, date,
System.class);
WhiteboxImpl.setInternalState(resortDaoImpl, "sessionFactory",
sessionFactory);
resortDaoImpl.cancelResortReservation(1L, 1L);
}
}
|
/*
* Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.datumbox.framework.statistics.sampling;
import com.datumbox.common.dataobjects.AssociativeArray;
import com.datumbox.common.dataobjects.AssociativeArray2D;
import com.datumbox.common.dataobjects.FlatDataList;
import com.datumbox.common.dataobjects.FlatDataCollection;
import com.datumbox.common.dataobjects.TransposeDataList;
import com.datumbox.common.dataobjects.TransposeDataCollection;
import com.datumbox.framework.statistics.descriptivestatistics.Descriptives;
import com.datumbox.configuration.TestConfiguration;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author bbriniotis
*/
public class StratifiedSamplingTest {
public StratifiedSamplingTest() {
}
protected AssociativeArray generateNh() {
AssociativeArray nh = new AssociativeArray();
nh.put("strata1", 3);
nh.put("strata2", 4);
return nh;
}
protected AssociativeArray generateNh2() {
AssociativeArray nh = new AssociativeArray();
nh.put(1, 4);
nh.put(2, 3);
nh.put(3, 3);
return nh;
}
protected AssociativeArray generatePopulationNh() {
AssociativeArray populationNh = new AssociativeArray();
populationNh.put(1, 14);
populationNh.put(2, 8);
populationNh.put(3, 8);
return populationNh;
}
protected TransposeDataCollection generateSampleDataCollection() {
TransposeDataCollection sampleDataCollection = new TransposeDataCollection();
sampleDataCollection.put(1, new FlatDataCollection(Arrays.asList(new Object[]{2,3,6,5}))); //,6,8,6,7,8,6,7,7,9,8
sampleDataCollection.put(2, new FlatDataCollection(Arrays.asList(new Object[]{10,9,12}))); //,8,14,7,12,9
sampleDataCollection.put(3, new FlatDataCollection(Arrays.asList(new Object[]{8,6,7}))); //,4,5,6,4,3
return sampleDataCollection;
}
/**
* Test of weightedProbabilitySampling method, of class StratifiedSampling.
*/
@Test
public void testWeightedProbabilitySampling() {
System.out.println("weightedProbabilitySampling");
AssociativeArray2D strataFrequencyTable = new AssociativeArray2D();
strataFrequencyTable.put2d("strata1", "1", 10);
strataFrequencyTable.put2d("strata1", "2", 20);
strataFrequencyTable.put2d("strata1", "3", 30);
strataFrequencyTable.put2d("strata1", "4", 40);
strataFrequencyTable.put2d("strata2", "1", 100);
strataFrequencyTable.put2d("strata2", "2", 200);
strataFrequencyTable.put2d("strata2", "3", 300);
strataFrequencyTable.put2d("strata2", "4", 400);
strataFrequencyTable.put2d("strata2", "5", 500);
strataFrequencyTable.put2d("strata2", "6", 600);
strataFrequencyTable.put2d("strata2", "7", 800);
AssociativeArray nh = generateNh();
boolean withReplacement = true;
double expResult = Descriptives.sum(nh.toFlatDataCollection());
TransposeDataCollection sampledIds = StratifiedSampling.weightedProbabilitySampling(strataFrequencyTable, nh, withReplacement);
double result = 0;
for(Object stata : sampledIds.keySet()) {
result+= sampledIds.get(stata).size();
}
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of randomSampling method, of class StratifiedSampling.
*/
@Test
public void testRandomSampling() {
System.out.println("randomSampling");
TransposeDataList strataIdList = new TransposeDataList();
strataIdList.put("strata1", new FlatDataList(Arrays.asList(new Object[]{"1","2","3","4"})));
strataIdList.put("strata2", new FlatDataList(Arrays.asList(new Object[]{"1","2","3","4","5","6","7"})));
AssociativeArray nh = generateNh();
boolean withReplacement = true;
double expResult = Descriptives.sum(nh.toFlatDataCollection());
TransposeDataCollection sampledIds = StratifiedSampling.randomSampling(strataIdList, nh, withReplacement);
double result = 0;
for(Object stata : sampledIds.keySet()) {
result+= sampledIds.get(stata).size();
}
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of mean method, of class StratifiedSampling.
*/
@Test
public void testMean() {
System.out.println("mean");
TransposeDataCollection sampleDataCollection = generateSampleDataCollection();
AssociativeArray populationNh = generatePopulationNh();
double expResult = 6.4888888888889;
double result = StratifiedSampling.mean(sampleDataCollection, populationNh);
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of variance method, of class StratifiedSampling.
*/
@Test
public void testVariance() {
System.out.println("variance");
TransposeDataCollection sampleDataCollection = generateSampleDataCollection();
AssociativeArray populationNh = generatePopulationNh();
double expResult = 9.43856960409;
double result = StratifiedSampling.variance(sampleDataCollection, populationNh);
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of std method, of class StratifiedSampling.
*/
@Test
public void testStd() {
System.out.println("std");
TransposeDataCollection sampleDataCollection = generateSampleDataCollection();
AssociativeArray populationNh = generatePopulationNh();
double expResult = 3.0722255132211;
double result = StratifiedSampling.std(sampleDataCollection, populationNh);
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of xbarVariance method, of class StratifiedSampling.
*/
@Test
public void testXbarVariance() {
System.out.println("xbarVariance");
TransposeDataCollection sampleDataCollection = generateSampleDataCollection();
AssociativeArray nh = generateNh2();
AssociativeArray populationNh = generatePopulationNh();
double expResult = 0.17901234567;
double result = StratifiedSampling.xbarVariance(sampleDataCollection, nh, populationNh);
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of xbarStd method, of class StratifiedSampling.
*/
@Test
public void testXbarStd() {
System.out.println("xbarStd");
TransposeDataCollection sampleDataCollection = generateSampleDataCollection();
AssociativeArray nh = generateNh2();
AssociativeArray populationNh = generatePopulationNh();
double expResult = 0.42309850588133;
double result = StratifiedSampling.xbarStd(sampleDataCollection, nh, populationNh);
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
/**
* Test of optimumSampleSize method, of class StratifiedSampling.
*/
@Test
public void testOptimumSampleSize() {
System.out.println("optimumSampleSize");
int n = 0;
AssociativeArray populationNh = new AssociativeArray();
populationNh.put(1,394);
populationNh.put(2,461);
populationNh.put(3,391);
populationNh.put(4,334);
populationNh.put(5,169);
populationNh.put(6,113);
populationNh.put(7,148);
AssociativeArray populationStdh = new AssociativeArray();
populationStdh.put(1,8.3);
populationStdh.put(2,13.3);
populationStdh.put(3,15.1);
populationStdh.put(4,19.8);
populationStdh.put(5,24.5);
populationStdh.put(6,26.0);
populationStdh.put(7,35.0);
double expResult = n;
AssociativeArray sampleSizes = StratifiedSampling.optimumSampleSize(n, populationNh, populationStdh);
double result = Descriptives.sum(sampleSizes.toFlatDataCollection());
assertEquals(expResult, result, TestConfiguration.DOUBLE_ACCURACY_HIGH);
}
}
|
package com.example.kamil.ebookyourchildshealth.fragment;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.example.kamil.ebookyourchildshealth.MyDebugger;
import com.example.kamil.ebookyourchildshealth.R;
import com.example.kamil.ebookyourchildshealth.activity.ChooseChildMainActivity;
import com.example.kamil.ebookyourchildshealth.database.MyDatabaseHelper;
import com.example.kamil.ebookyourchildshealth.model.Child;
import com.example.kamil.ebookyourchildshealth.util.UtilCode;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.util.Calendar;
import static android.app.Activity.RESULT_OK;
public class AddNewChildFragment extends Fragment {
static MyDebugger myDebugger;
private String[] textViewLeftColumnNamesArray;
private MyDatabaseHelper myDatabaseHelper;
private Button saveChildButton;
private Bitmap croppedImage;
private Calendar calendar;
private int day, month, year;
private Child childObject;
private Uri uriChildPhoto;
@BindString(R.string.pick_date)
String pickDateString;
@BindView(R.id.imageButtonAddPhoto)
ImageButton imageButton;
@BindView(R.id.columnName1)
TextView textViewName;
@BindView(R.id.columnSurname)
TextView textViewSurname;
@BindView(R.id.columnPesel)
TextView textViewPesel;
@BindView(R.id.columnSex)
TextView textViewSex;
@BindView(R.id.columnBloodGroup)
TextView textViewBlood;
@BindView(R.id.columnBirthDate)
TextView textViewBirthDate;
@BindView(R.id.columnBirthPlace)
TextView textViewBirthPlace;
@BindView(R.id.columnMother)
TextView textViewMother;
@BindView(R.id.columnFather)
TextView textViewFather;
@BindView(R.id.columnNameValue)
EditText editTextName;
@BindView(R.id.columnSurnameValue)
EditText editTextSurname;
@BindView(R.id.columnPeselValue)
EditText editTextPesel;
@BindView(R.id.columnSexValueSpinner)
Spinner spinnerSex;
@BindView(R.id.columnBloodGroupValueSpinner)
Spinner spinnerBlood;
@BindView(R.id.buttonDatePicker)
Button buttonBirthDate;
@BindView(R.id.columnBirthPlaceValue)
EditText editTextBirthPlace;
@BindView(R.id.columnMotherValue)
EditText editTextMother;
@BindView(R.id.columnFatherValue)
EditText editTextFather;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_new_child, container, false);
myDebugger = new MyDebugger();
ButterKnife.bind(this, view);
myDatabaseHelper = MyDatabaseHelper.getMyDatabaseHelperInstance(getActivity());
saveChildButton = (Button) view.findViewById(R.id.buttonSaveChild);
setArrayContainsTextViewNames();
setTextOnLeftColumnTextView();
createAndSetSpinners(view);
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
if (myDatabaseHelper != null) {
myDatabaseHelper = null;
}
}
private void setArrayContainsTextViewNames () {
Resources resources = getActivity().getResources();
textViewLeftColumnNamesArray = resources.getStringArray(R.array.child_table);
}
private void setTextOnLeftColumnTextView() {
textViewName.setText(textViewLeftColumnNamesArray[0]);
textViewSurname.setText(textViewLeftColumnNamesArray[1]);
textViewPesel.setText(textViewLeftColumnNamesArray[2]);
textViewSex.setText(textViewLeftColumnNamesArray[3]);
textViewBlood.setText(textViewLeftColumnNamesArray[4]);
textViewBirthDate.setText(textViewLeftColumnNamesArray[5]);
textViewBirthPlace.setText(textViewLeftColumnNamesArray[6]);
textViewMother.setText(textViewLeftColumnNamesArray[7]);
textViewFather.setText(textViewLeftColumnNamesArray[8]);
}
private void createAndSetSpinners(View view) {
// Create an ArrayAdapter using the string array and a default spinner layout
/**An ArrayAdapter is an adapter backed by an array of objects.
* It links the array to the Adapter View.
* The default ArrayAdapter converts an array item into a String object
* putting it into a TextView. The text view is then displayed
* in the AdapterView (a ListView for example).
* When you create the adapter, you need to supply the layout for displaying each array string.
* You can define your own or use one of Android’s, such as:
*/
ArrayAdapter<CharSequence> adapterSpinner1 = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_sex_array, R.layout.spinner_item);
ArrayAdapter<CharSequence> adapterSpinner2 = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_blood_array, R.layout.spinner_item);
// Specify the layout to use when the list of choices appears
adapterSpinner1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterSpinner2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerSex.setAdapter(adapterSpinner1);
spinnerBlood.setAdapter(adapterSpinner2);
}
public void setImageOnImageButton(String uri, Uri resultUri) throws IOException {
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(uri, imageButton);
this.uriChildPhoto = resultUri; // kopiujemy uri obrazka do zmiennej klasy, którą wrzucimy do bd
croppedImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), resultUri);
myDebugger.someMethod("!!!!!!!!!!!! ADRES FOTKI: " + uriChildPhoto.toString());
}
@OnClick(R.id.imageButtonAddPhoto)
public void pickPhoto() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // nowy intent i ustawia typ na pobranie plików
intent.setType("image/*"); // typ pliku
this.startActivityForResult(intent, UtilCode.FILE_PICK_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == UtilCode.FILE_PICK_CODE && resultCode == RESULT_OK) {
Uri imageUri;
imageUri = data.getData();
CropImage.activity(imageUri).setAspectRatio(15,9).setFixAspectRatio(true)
.setCropShape(CropImageView.CropShape.RECTANGLE)
.setGuidelines(CropImageView.Guidelines.OFF)
.start(getContext(), this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
try {
setImageOnImageButton("file://" + resultUri.getPath(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@OnClick(R.id.buttonSaveChild)
public void saveChildToDatabaseButtonAction(View v) {
childObject = new Child();
//if (checkIfAllFieldAreFilled()) {
if (true) {
//if (checkIfPeselCorrect()) {
if (true) {
childObject.setName(editTextName.getText().toString());
childObject.setSurname(editTextSurname.getText().toString());
childObject.setPesel(editTextPesel.getText().toString());
childObject.setSex(spinnerSex.getSelectedItem().toString());
childObject.setBloodGroup(spinnerBlood.getSelectedItem().toString());
childObject.setBirthDate(buttonBirthDate.getText().toString());
childObject.setBirthPlace(editTextBirthPlace.getText().toString());
childObject.setMother(editTextMother.getText().toString());
childObject.setFather(editTextFather.getText().toString());
childObject.setImageUri(uriChildPhoto);
boolean isInserted = myDatabaseHelper.insertDataIntoChildTable(childObject);
if (isInserted == true) {
Toast.makeText(getActivity(), "Dane zapisane", Toast.LENGTH_LONG).show();
newActivityBackToChooseChildMainActivity();
}
else
Toast.makeText(getActivity(), "Dane nie zostały zapisane", Toast.LENGTH_LONG).show();
} else
Toast.makeText(getActivity(), "NIEPOPRAWNY PESEL!", Toast.LENGTH_LONG).show();
} else
Toast.makeText(getActivity(), "UZUPEŁNIJ WSZYSTKIE POLA!", Toast.LENGTH_LONG).show();
}
private boolean checkIfAllFieldAreFilled() {
String uriString = "";
if (uriChildPhoto != null)
uriString += uriChildPhoto.toString();
if (uriString.matches("") ||
editTextName.getText().toString().matches("") ||
editTextSurname.getText().toString().matches("") ||
editTextPesel.getText().toString().matches("") ||
spinnerSex.getSelectedItem().toString().matches("") ||
spinnerBlood.getSelectedItem().toString().matches("") ||
buttonBirthDate.getText().toString().matches(pickDateString) ||
editTextBirthPlace.getText().toString().matches("") ||
editTextMother.getText().toString().matches("") ||
editTextFather.getText().toString().matches(""))
return false;
return true;
}
private boolean checkIfPeselCorrect() {
char tempChar;
int charCount = 0;
String string = editTextPesel.getText().toString();
for (int i=0 ; i<string.length() ; i++ ) {
tempChar = string.charAt(i);
if (tempChar<'0' && tempChar>'9')
return false;
charCount++;
}
if (charCount!=11)
return false;
return true;
}
private DatePickerDialog.OnDateSetListener datePickerListener =
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1) // +1 bo miesiące numeruje od 0
+ "/" +String.valueOf(year);
setDateOnButton(date);
}
};
private void setDateOnButton(String date) {
buttonBirthDate.setText(date);
}
@OnClick(R.id.buttonDatePicker)
public void showDatePickerDialog(View v) {
setCurrentDate();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
android.R.style.Theme_Holo_Light_Dialog_NoActionBar,datePickerListener,
year, month, day);
datePickerDialog.show();
}
private void setCurrentDate() {
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
}
private void newActivityBackToChooseChildMainActivity () {
Intent intent = new Intent(this.getActivity(), ChooseChildMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
|
package toba.user;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String firstName;
private String lastName;
private String phone;
private String address;
private String city;
private String state;
private String zipcode;
private String email;
private String username;
private String password;
private LocalDateTime registerDate;
private String passwordSalt;
public User () {
this.firstName = "";
this.lastName = "";
this.phone = "";
this.address = "";
this.city = "";
this.state = "";
this.zipcode = "";
this.email = "";
this.username = "";
this.password = "";
this.registerDate = LocalDateTime.now();
this.passwordSalt = "";
}
public User (String firstName, String lastName, String phone, String address, String city, String state, String zipcode, String email, String username, String password, LocalDateTime registerDate, String passwordSalt) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
this.address = address;
this.city = city;
this.state = state;
this.zipcode = zipcode;
this.email = email;
this.username = username;
this.password = password;
this.registerDate = registerDate;
this.passwordSalt = passwordSalt;
}
public Long getUserId () {
return this.userId;
}
public void setUserId (Long userId) {
this.userId = userId;
}
public String getFirstName () {
return this.firstName;
}
public void setFirstName (String firstName) {
this.firstName = firstName;
}
public String getLastName () {
return this.lastName;
}
public void setLastName (String lastName) {
this.lastName = lastName;
}
public String getPhone () {
return this.phone;
}
public void setPhone (String phone) {
this.phone = phone;
}
public String getAddress () {
return this.address;
}
public void setAddress (String address) {
this.address = address;
}
public String getCity () {
return this.city;
}
public void setCity (String city) {
this.city = city;
}
public String getState () {
return this.state;
}
public void setState (String state) {
this.state = state;
}
public String getZipcode () {
return this.zipcode;
}
public void setZipcode (String zipcode) {
this.zipcode = zipcode;
}
public String getEmail () {
return this.email;
}
public void setEmail (String email) {
this.email = email;
}
public String getUsername () {
return this.username;
}
public void setUsername (String username) {
this.username = username;
}
public String getPassword () {
return this.password;
}
public void setPassword (String password) {
this.password = password;
}
public LocalDateTime getRegisterDate () {
return this.registerDate;
}
public void setRegisterDate (LocalDateTime registerDate) {
this.registerDate = registerDate;
}
public String getPasswordSalt () {
return this.passwordSalt;
}
public void setPasswordSalt (String salt) {
this.passwordSalt = salt;
}
}
|
package com.cn.domain;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 主观题表
* @author Hang
* @date 2016年2月29日上午10:37:16
* @version
*/
public class SubjectiveQuestions {
//主观题表ID
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "sid", nullable = false, length = 50, unique = true)
private int sid;
//主观题表内容
@Column(name = "scontent", nullable = false, length = 100)
private String scontent;
//主观题表类型
@Column(name = "stype", nullable = false, length = 255)
private int stype;
//主观题表备注
@Column(name = "snote", nullable = true, length = 255)
private String snote;
//主观题表所对应问卷
@Column(name = "squestionnaire", nullable = false, length = 50)
private String squestionnaire;
}
|
package msip.go.kr.share.service;
import java.util.List;
import msip.go.kr.share.entity.ReqOpn;
/**
* 자료공유-자료요청 의견 관련 업무 처리를 위한 Sevice Interface 정의
*
* @author 정승철
* @since 2015.07.10
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.10 정승철 최초생성
*
* </pre>
*/
public interface ReqOpnService {
/**
* 선택된 id의 자료요청 의견 정보를 데이터베이스에서 삭제하도록 요청
* @param ReqOpn entity
* @throws Exception
*/
public void remove(ReqOpn entity) throws Exception;
/**
* 자료요청 의견 정보를 입력받아 데이터베이스에 저장하도록 요청
* @param ReqOpn entity
* @return Long
* @throws Exception
*/
public void persist(ReqOpn entity) throws Exception;
/**
* 자료요청 의견 목록을 데이터베이스에서 읽어와 화면에 출력하도록 요청
* @return List<ReqOpn> 알리미 목록
* @throws Exception
*/
public List<ReqOpn> findAll() throws Exception;
/**
* 수정된 자료요청 의견 정보를 데이터베이스에 반영하도록 요청
* @param ReqOpn entity
* @throws Exception
*/
public void merge(ReqOpn entity) throws Exception;
/**
* 선택된 id에 따라 데이터베이스에서 자료요청 의견 정보를 읽어와 화면에 출력하도록 요청
* @param Long id
* @return ReqOpn entity
* @throws Exception
*/
public ReqOpn findById(Long id) throws Exception;
/**
* 선택된 자료요청 ID 에 따라 데이터베이스에서 자료요청 의견 전체 목록을 읽어와 화면에 출력하도록 요청
* @param Long id
* @return ReqOpn entity
* @throws Exception
*/
public List<ReqOpn> findAllByReqId(Long id) throws Exception;
/**
* 하위의견 수를 조회하며 반환한다.
* @param id 의견일련번호
* @return
* @throws Exception
*/
public int countByPid(Long id) throws Exception;
}
|
package com.github.sd;
/**
* User: Daniil Sosonkin
* Date: 5/30/2018 11:38 AM
*/
public interface JsonConvertable
{
String toJSON();
}
|
import java.awt.*;
import java.applet.*;
public class msg3 extends Applet
{
public void paint(Graphics a)
{
a.drawString("FATHERS NAME:- KUMAR SINGH",10,20);
}//CLOSE OF MAIN
}//CLOSE OF CLASS
|
package mf0227.uf2404.actividad2;
/**
* Interfaz donne se declaran las funciones arrancar y parar.
* Estas funciones se implementaran en la clase Vehiculo
*
* @author Arturo Montaņez
*
*/
public interface IConducible {
//Arrancar vehiculo. Si existiera el atributo estaArrancado lo pondria a true
void arrancar();
//Parar vehiculo. Si existiera el atributo estaArrancado lo pondria a true
void parar();
}
|
package f.star.iota.milk.ui.gkdgif.gkd;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import f.star.iota.milk.R;
import f.star.iota.milk.base.BaseAdapter;
public class GkdGifAdapter extends BaseAdapter<GkdGifViewHolder, GkdGifBean> {
@Override
public GkdGifViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new GkdGifViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((GkdGifViewHolder) holder).bindView(mBeans.get(position));
}
}
|
package gui.db;
import gui.ComponentTools;
import gui.form.ComboBoxItem;
import gui.form.TextItem;
import gui.form.ValueChangeEvent;
import gui.form.ValueChangeListener;
import gui.form.valid.RegexValidator;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import model.ObservableDelegate;
import model.ObservableDelegator;
import utils.ImageTools;
import db.SQL;
import db.SQLU;
public class SchemaEditor implements ObservableDelegator, ValueChangeListener
{
private static final Icon addIcon =
ImageTools.getIcon ("icons/20/gui/RowNew.gif");
private static final Icon delIcon =
ImageTools.getIcon ("icons/20/gui/RowDelete.gif");
private static final Icon upIcon =
ImageTools.getIcon ("icons/20/flow/ArrowUp.gif");
private static final Icon downIcon =
ImageTools.getIcon ("icons/20/flow/ArrowDown.gif");
private static final Dimension DIM = new Dimension (30, 30);
private JPanel panel;
private JTable view;
private JButton delButton, upButton, downButton;
private DefaultTableModel model;
private ComboBoxItem connBox;
private TextItem tableItem;
private JButton loadButton, createButton;
private ObservableDelegate observable;
public SchemaEditor()
{
panel = new JPanel (new BorderLayout());
panel.setBorder (BorderFactory.createTitledBorder
("Select or create the table to hold the imported data"));
view = new JTable();
view.getTableHeader().setReorderingAllowed (false);
Collection<String> connections = SQLU.getConnectionNames();
connBox = new ComboBoxItem ("Database", connections);
connBox.setToolTipText ("Select a DBMS Connection");
connBox.addValueChangeListener (this);
// TBD: use an editable combo box with the tables from the DBMS
// TBD: default to file name
tableItem = new TextItem ("Table Name");
tableItem.setValidator (new RegexValidator ("[-A-Za-z0-9_]+"));
tableItem.addValueChangeListener (this);
JScrollPane scroll = new JScrollPane (view);
JPanel columnPanel = new JPanel (new BorderLayout());
columnPanel.add (getButtonPanel(), BorderLayout.WEST);
columnPanel.add (scroll, BorderLayout.CENTER);
columnPanel.setBorder (FormattedDataImporter.TABLE_BORDER);
JPanel upper = new JPanel (new BorderLayout());
upper.add (connBox.getTitledPanel(), BorderLayout.WEST);
upper.add (tableItem.getTitledPanel(), BorderLayout.CENTER);
ActionListener listener = new ButtonListener();
loadButton = new JButton ("Load Schema");
loadButton.setToolTipText ("Load the table schema into the editor");
loadButton.addActionListener (listener);
loadButton.setEnabled (false);
createButton = new JButton ("Create New Table");
createButton.setToolTipText ("Create a new table using the current schema");
createButton.addActionListener (listener);
createButton.setEnabled (false);
JPanel controls = new JPanel (new FlowLayout (FlowLayout.LEADING));
controls.add (loadButton);
controls.add (createButton);
panel.add (upper, BorderLayout.NORTH);
panel.add (columnPanel, BorderLayout.CENTER);
panel.add (controls, BorderLayout.SOUTH);
observable = new ObservableDelegate();
}
// called when the connection or table name changes
public void valueChanged (final ValueChangeEvent event)
{
enableButtons();
observable.registerChange();
}
private void enableButtons()
{
String conn = (String) connBox.getValue ();
String table = tableItem.getValue ().toString().toUpperCase();
SQL sql = new SQL (conn);
boolean ok = tableItem.isValid () && tableItem.hasChanged ();
loadButton.setEnabled (ok && SQL.exists (conn, table));
if (model != null)
createButton.setEnabled (ok && model.getRowCount () > 0);
}
class ButtonListener implements ActionListener
{
public void actionPerformed (final ActionEvent e)
{
String connName = (String) connBox.getValue();
String tableName = tableItem.getValue().toString().toUpperCase();
String cmd = e.getActionCommand();
if (cmd.equals ("Load Schema"))
loadSchema (connName, tableName);
else if (cmd.equals ("Create New Table"))
createTable (connName, tableName);
}
}
public void setTable (final TableModel inputTable, final int skip)
{
model = new DefaultTableModel();
model.addColumn ("Column Name");
model.addColumn ("Column Type");
// start at 1 to skip the "Line Number" column
if (inputTable != null)
for (int col = skip; col < inputTable.getColumnCount(); col++)
{
String columnName = inputTable.getColumnName (col);
columnName = SQLU.standardizeColumn (columnName);
String columnType = "VARCHAR";
if (inputTable instanceof MutableTableModel)
columnType = ((MutableTableModel) inputTable).getColumnTypeName (col);
// TBD: combo-box of valid types
model.addRow (new String[] { columnName, columnType });
}
view.setModel (model);
}
JPanel getButtonPanel()
{
ActionListener bl = new EditorButtonListener();
JButton addButton =
makeButton (addIcon, "Add", "Add a new column entry", bl);
addButton.setEnabled (true);
delButton = makeButton (delIcon, "Delete", "Remove selected column entries", bl);
upButton = makeButton (upIcon, "Up", "Move column entry up", bl);
downButton = makeButton (downIcon, "Down", "Move column entry down", bl);
JPanel buttons = new JPanel (new GridLayout (0, 1));
buttons.add (addButton);
buttons.add (delButton);
buttons.add (upButton);
buttons.add (downButton);
SelectionListener l = new SelectionListener(); // calls valueChanged
view.getSelectionModel().addListSelectionListener (l);
return buttons;
}
private JButton makeButton (final Icon icon, final String command,
final String tip, final ActionListener listener)
{
JButton button = new JButton (icon);
button.setPreferredSize (DIM);
button.setActionCommand (command);
button.setToolTipText (tip);
button.addActionListener (listener);
button.setEnabled (false);
return button;
}
class EditorButtonListener implements ActionListener
{
public void actionPerformed (final ActionEvent e)
{
tableItem.setInitialValue (null); // to indicate schema change
String command = e.getActionCommand();
if (model == null)
setTable(null, 0);
if (command.equals ("Add"))
{
String columnName = "COLUMN_" + (model.getRowCount() + 1);
model.addRow (new String[] { columnName, "VARCHAR" });
enableButtons(); // in case we just added the first row
}
else if (command.equals ("Delete"))
{
int[] selected = view.getSelectedRows();
for (int i = selected.length - 1; i >= 0; i--)
model.removeRow (selected[i]);
view.clearSelection();
enableButtons(); // in case we just deleted the last row
}
else if (command.equals ("Up"))
{
int selected = view.getSelectedRows()[0];
int row = selected - 1;
model.moveRow (selected, selected, row);
view.getSelectionModel().setSelectionInterval (row, row);
}
else if (command.equals ("Down"))
{
int selected = view.getSelectedRows()[0];
int row = selected + 1;
model.moveRow (selected, selected, row);
view.getSelectionModel().setSelectionInterval (row, row);
}
}
}
class SelectionListener implements ListSelectionListener
{
public void valueChanged (final ListSelectionEvent e)
{
int[] selected = view.getSelectedRows();
delButton.setEnabled (selected.length >= 1);
upButton.setEnabled (selected.length == 1 && selected[0] > 0);
downButton.setEnabled (selected.length == 1 &&
selected[0] < view.getRowCount() - 1);
}
}
public void loadSchema (final String connName, final String tableName)
{
connBox.setInitialValue (connName);
tableItem.setInitialValue (tableName);
setTable (new DatabaseSubset (connName, tableName, false), 0);
}
private boolean createTable (final String connName, final String tableName)
{
if (SQL.exists (connName, tableName))
{
int count = (int)
SQL.getDouble (connName, "select count(*) from " + tableName);
if (Confirm.confirm
(panel, "TABLE EXISTS",
"The " + tableName + " table already exists.\n" +
"It currently contains " + count + " record(s).\n" +
"Are you sure you want to overwrite it?"))
{
SQL.execute (connName, "drop table " + tableName);
tableItem.apply();
}
else
return false; // abort
}
StringBuilder sql = new StringBuilder ("create table ");
sql.append (tableName);
sql.append (" (\n");
for (int row = 0, count = model.getRowCount(); row < count; row++)
{
sql.append (" ");
sql.append (model.getValueAt (row, 0)); // column name
sql.append (" ");
sql.append (model.getValueAt (row, 1)); // column type
if (row < count - 1)
sql.append (",");
sql.append ("\n");
}
sql.append (")");
boolean ok = SQL.execute (connName, sql.toString());
if (ok)
{
observable.registerChange();
tableItem.apply ();
}
else
JOptionPane.showMessageDialog
(panel, "Database error ocurred during table creation:\n" + sql,
"ERROR", JOptionPane.ERROR_MESSAGE);
return ok;
}
public JPanel getPanel()
{
return panel;
}
public String getConnection()
{
return (String) connBox.getValue();
}
public String getTableName()
{
return tableItem.isValid() ? (String) tableItem.getValue() : null;
}
public List<String> getColumnNames()
{
if (model != null)
{
List<String> columnNames = new ArrayList<String>();
for (int row = 0; row < model.getRowCount(); row++)
columnNames.add ((String) model.getValueAt (row, 0));
return columnNames;
}
return null;
}
public Observable getObservable()
{
return observable;
}
public void addObserver (final Observer observer)
{
observable.addObserver (observer);
}
public void deleteObserver (final Observer observer)
{
observable.deleteObserver (observer);
}
public static void main (final String[] args)
{
SchemaEditor se = new SchemaEditor();
ComponentTools.open (se.getPanel(), SchemaEditor.class.getName());
}
}
|
package algorithm.genetic.factory;
import java.util.ArrayList;
import java.util.List;
import algorithm.genetic.GAParameters;
import algorithm.genetic.GeneticAlgorithm;
import algorithm.genetic.crossover.CrossoverMethod;
import algorithm.genetic.crossover.NoCrossover;
import algorithm.genetic.crossover.OnePointCrossover;
import algorithm.genetic.crossover.TwoPointCrossover;
import algorithm.genetic.mutation.MutationMethod;
import algorithm.genetic.mutation.ReverseSubsetMutation;
import algorithm.genetic.mutation.SwapMutation;
import algorithm.genetic.mutation.SwapOnlyImprovingMutation;
public class GAFactory {
public static GeneticAlgorithm getDefault() {
return new GeneticAlgorithm(new GAParameters());
}
public static GeneticAlgorithm getOptimal() {
GAParameters params = new GAParameters();
params.setMutationMethod(new SwapOnlyImprovingMutation());
params.setMutationRate(0.05);
params.setCrossoverMethod(new OnePointCrossover());
params.setNumGenerations(50);
params.setPopulationSize(50);
return new GeneticAlgorithm(params);
}
public static List<GeneticAlgorithm> getMutationRates(double min, double max, double increment) {
List<GeneticAlgorithm> result = new ArrayList<GeneticAlgorithm>();
for (double i=min; i<=max; i += increment) {
result.add(new GeneticAlgorithm(new GAParameters(i)));
}
return result;
}
public static List<GeneticAlgorithm> getGenerations(int min, int max, int increment) {
List<GeneticAlgorithm> result = new ArrayList<GeneticAlgorithm>();
for (int i=min; i<=max; i += increment) {
GAParameters params = new GAParameters();
params.setNumGenerations(i);
result.add(new GeneticAlgorithm(params));
}
return result;
}
public static List<GeneticAlgorithm> getCrossoverMethods() {
List<Class<? extends CrossoverMethod>> classes = new ArrayList<Class<? extends CrossoverMethod>>();
classes.add(TwoPointCrossover.class);
classes.add(OnePointCrossover.class);
classes.add(NoCrossover.class);
List<GeneticAlgorithm> result = new ArrayList<GeneticAlgorithm>();
for (Class<? extends CrossoverMethod> clazz : classes) {
GAParameters params = new GAParameters();
try {
params.setCrossoverMethod(clazz.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
result.add(new GeneticAlgorithm(params));
}
return result;
}
public static List<GeneticAlgorithm> getMutationMethods() {
List<Class<? extends MutationMethod>> classes = new ArrayList<Class<? extends MutationMethod>>();
classes.add(SwapMutation.class);
classes.add(SwapOnlyImprovingMutation.class);
classes.add(ReverseSubsetMutation.class);
List<GeneticAlgorithm> result = new ArrayList<GeneticAlgorithm>();
for (Class<? extends MutationMethod> clazz : classes) {
GAParameters params = new GAParameters();
try {
params.setMutationMethod(clazz.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
result.add(new GeneticAlgorithm(params));
}
return result;
}
public static List<GeneticAlgorithm> getPopulationSizes(int min, int max, int increment) {
List<GeneticAlgorithm> result = new ArrayList<GeneticAlgorithm>();
for (int i=min; i<=max; i += increment) {
GAParameters params = new GAParameters();
params.setPopulationSize(i);
result.add(new GeneticAlgorithm(params));
}
return result;
}
public static List<GeneticAlgorithm> getGroupSizes(int min, int max, int increment) {
List<GeneticAlgorithm> result = new ArrayList<GeneticAlgorithm>();
for (int i=min; i<=max; i += increment) {
GAParameters params = new GAParameters();
params.setGroupSize(i);
result.add(new GeneticAlgorithm(params));
}
return result;
}
}
|
package be.dpms.medwan.webapp.wl.struts.actions.healthrecord;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.*;
import java.text.SimpleDateFormat;
import be.dpms.medwan.webapp.wo.common.system.SessionContainerWO;
import be.dpms.medwan.common.model.vo.occupationalmedicine.ExaminationVO;
import be.dpms.medwan.common.model.vo.authentication.UserVO;
import be.dpms.medwan.services.exceptions.InternalServiceException;
import be.mxs.webapp.wl.session.SessionContainerFactory;
import be.mxs.webapp.wl.exceptions.SessionContainerFactoryException;
import be.mxs.common.model.vo.healthrecord.*;
import be.mxs.common.model.vo.healthrecord.util.TransactionFactory;
import be.mxs.common.model.vo.IdentifierFactory;
import be.mxs.common.model.util.collections.BeanPropertyAccessor;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
public class ManageVaccinationAction extends org.apache.struts.action.Action {
private class DummyTransactionFactory extends TransactionFactory{
public TransactionVO createTransactionVO(UserVO userVO) {
return null;
}
}
//--- PERFORM ---------------------------------------------------------------------------------
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ActionForward actionForward = mapping.findForward("success");
VaccinationInfoVO vaccinationInfoVO = null;
PersonalVaccinationsInfoVO personalVaccinationsInfoVO = null;
try{
SessionContainerWO sessionContainerWO = (SessionContainerWO)SessionContainerFactory.getInstance().getSessionContainerWO( request , SessionContainerWO.class.getName() );
String _param_vaccinationMessageKey = null;
String sTransactionId = ScreenHelper.checkString(request.getParameter("be.mxs.healthrecord.transaction_id")),
sServerId = ScreenHelper.checkString(request.getParameter("be.mxs.healthrecord.server_id"));
// id = serverid and transactionid
if(sTransactionId.length() > 0 && !sTransactionId.equals("null")){
TransactionVO existingTransactionVO;
try{
existingTransactionVO = MedwanQuery.getInstance().loadTransaction(Integer.parseInt(sServerId),Integer.parseInt(sTransactionId));
Iterator iItems = existingTransactionVO.getItems().iterator();
ItemVO item;
while(iItems.hasNext()){
item = (ItemVO)iItems.next();
if(item.getType().equals(be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_VACCINATION_TYPE)){
_param_vaccinationMessageKey = item.getValue();
break;
}
}
vaccinationInfoVO = new VaccinationInfoVO();
personalVaccinationsInfoVO = sessionContainerWO.getPersonalVaccinationsInfoVO();
if(personalVaccinationsInfoVO == null && sessionContainerWO.getPersonVO()!=null) {
personalVaccinationsInfoVO = MedwanQuery.getInstance().getPersonalVaccinationsInfo( sessionContainerWO.getPersonVO(),sessionContainerWO.getUserVO() );
}
Iterator iVaccinationsInfoVO = personalVaccinationsInfoVO.getVaccinationsInfoVO().iterator();
VaccinationInfoVO _vaccinationInfoVO;
String vaccinationType;
while(iVaccinationsInfoVO.hasNext()) {
_vaccinationInfoVO = (VaccinationInfoVO) iVaccinationsInfoVO.next();
vaccinationType = null;
try {
vaccinationType = (String) BeanPropertyAccessor.getInstance().getValue( _vaccinationInfoVO,
"transactionVO.items",
"value",
"type=be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_VACCINATION_TYPE");
}
catch (Exception e) {
e.printStackTrace();
}
if ((vaccinationType != null) && (vaccinationType.equals(_param_vaccinationMessageKey)) ) {
vaccinationInfoVO = _vaccinationInfoVO;
break;
}
}
vaccinationInfoVO.setTransactionVO(existingTransactionVO);
}
catch (Exception e) {
//
}
}
// id = vaccinationMessageKey-parameter
else{
_param_vaccinationMessageKey = request.getParameter("vaccination");
personalVaccinationsInfoVO = sessionContainerWO.getPersonalVaccinationsInfoVO();
if(personalVaccinationsInfoVO == null && sessionContainerWO.getPersonVO()!=null) {
personalVaccinationsInfoVO = MedwanQuery.getInstance().getPersonalVaccinationsInfo( sessionContainerWO.getPersonVO(),sessionContainerWO.getUserVO() );
}
Iterator iVaccinationsInfoVO = personalVaccinationsInfoVO.getVaccinationsInfoVO().iterator();
VaccinationInfoVO _vaccinationInfoVO;
String vaccinationType;
while (iVaccinationsInfoVO.hasNext()) {
_vaccinationInfoVO = (VaccinationInfoVO) iVaccinationsInfoVO.next();
vaccinationType = null;
try{
vaccinationType = (String) BeanPropertyAccessor.getInstance().getValue( _vaccinationInfoVO,
"transactionVO.items",
"value",
"type=be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_VACCINATION_TYPE");
}
catch (Exception e) {
e.printStackTrace();
}
if ((vaccinationType != null) && !vaccinationType.equals("be.mxs.healthrecord.vaccination.Other") && (vaccinationType.equals(_param_vaccinationMessageKey)) ) {
vaccinationInfoVO = _vaccinationInfoVO;
break;
}
}
}
if (vaccinationInfoVO == null) {
Debug.println("VaccinationInfo is null");
Iterator iOtherVaccinations = personalVaccinationsInfoVO.getOtherVaccinations().iterator();
ExaminationVO examinationVO;
Collection itemsVO;
ItemContextVO itemContextVO;
TransactionVO transactionVO;
while (iOtherVaccinations.hasNext()) {
examinationVO = (ExaminationVO) iOtherVaccinations.next();
Debug.println("Validating vaccination "+examinationVO.getMessageKey()+" against "+_param_vaccinationMessageKey);
if (examinationVO.getMessageKey().equalsIgnoreCase(_param_vaccinationMessageKey)) {
Debug.println("Found "+examinationVO.getMessageKey());
itemsVO = new Vector();
itemContextVO = null;
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_TYPE,
_param_vaccinationMessageKey,
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_STATUS,
IConstants.ITEM_TYPE_VACCINATION_STATUS_NONE,
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_NAME,
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_COMMENT,
"",
new Date(),
itemContextVO));
transactionVO = new TransactionVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.TRANSACTION_TYPE_VACCINATION,
new Date(),
new Date(),
IConstants.TRANSACTION_STATUS_CLOSED,
sessionContainerWO.getUserVO(),
itemsVO);
vaccinationInfoVO = MedwanQuery.getInstance().getVaccinationInfoVO(transactionVO, examinationVO);
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_DATE,
ScreenHelper.stdDateFormat.format(new Date()),
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
"be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_PREGNANT",
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_RESULTRECEIVED,
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_OTHER_REQUESTS_PRESTATION_ACTION,
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_OTHER_REQUESTS_PRESTATION_PRODUCT,
"",
new Date(),
itemContextVO));
boolean bNextDateExists=false;
Iterator i = itemsVO.iterator();
ItemVO item;
while (i.hasNext()){
item = (ItemVO)i.next();
if(item.getType().equalsIgnoreCase(IConstants.ITEM_TYPE_VACCINATION_NEXT_DATE)){
item.setValue(ScreenHelper.stdDateFormat.format(new Date(new Date().getTime()+vaccinationInfoVO.getNextMinInterval()*24*60*60*1000)));
bNextDateExists=true;
break;
}
}
if (!bNextDateExists){
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_NEXT_DATE,
ScreenHelper.stdDateFormat.format(new Date(new Date().getTime()+vaccinationInfoVO.getNextMinInterval()*24*60*60*1000)),
new Date(),
itemContextVO));
}
transactionVO.setItems(itemsVO);
vaccinationInfoVO.setTransactionVO(transactionVO);
break;
}
}
}
else {
Debug.println("VaccinationInfo is not null");
Collection itemsVO = new Vector();
Iterator iterator = vaccinationInfoVO.getTransactionVO().getItems().iterator();
ItemVO previousItemVO, newItemVO;
while (iterator.hasNext()) {
previousItemVO = (ItemVO) iterator.next();
newItemVO = new ItemVO( previousItemVO.getItemId(),
previousItemVO.getType(),
previousItemVO.getValue(),
previousItemVO.getDate(),
null);
itemsVO.add(newItemVO);
}
TransactionVO transactionVO = new TransactionVO( vaccinationInfoVO.getTransactionVO().getTransactionId(),
IConstants.TRANSACTION_TYPE_VACCINATION,
new Date(),
new Date(),
IConstants.TRANSACTION_STATUS_CLOSED,
sessionContainerWO.getUserVO(),
itemsVO);
ItemContextVO itemContextVO = new ItemContextVO(new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier()), "", "");
//Create a baseTransaction
Collection items = new Vector();
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_TYPE,
"",
new Date(),
itemContextVO));
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_STATUS,
IConstants.ITEM_TYPE_VACCINATION_STATUS_NONE,
new Date(),
itemContextVO));
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_DATE,
"",
new Date(),
itemContextVO));
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_NEXT_DATE,
"",
new Date(),
itemContextVO));
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_VACCINATION_NAME,
"",
new Date(),
itemContextVO));
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
"be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_PREGNANT",
"",
new Date(),
itemContextVO));
items.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_COMMENT,
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_OTHER_REQUESTS_PRESTATION,
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_OTHER_REQUESTS_PRESTATION_ACTION,
"",
new Date(),
itemContextVO));
itemsVO.add( new ItemVO( new Integer( IdentifierFactory.getInstance().getTemporaryNewIdentifier() ),
IConstants.ITEM_TYPE_OTHER_REQUESTS_PRESTATION_PRODUCT,
"",
new Date(),
itemContextVO));
TransactionVO baseTransactionVO = new TransactionVO(vaccinationInfoVO.getTransactionVO().getTransactionId(),
IConstants.TRANSACTION_TYPE_VACCINATION,
new Date(),
new Date(),
IConstants.TRANSACTION_STATUS_CLOSED,
sessionContainerWO.getUserVO(),
items);
DummyTransactionFactory df = new DummyTransactionFactory();
df.populateTransaction(baseTransactionVO,transactionVO);
vaccinationInfoVO.setTransactionVO(baseTransactionVO);
}
if (vaccinationInfoVO == null) {
actionForward = mapping.findForward( "failure" );
}
else {
sessionContainerWO.setPersonalVaccinationsInfoVO(null);
sessionContainerWO.setCurrentVaccinationInfoVO(vaccinationInfoVO);
sessionContainerWO.setCurrentTransactionVO(vaccinationInfoVO.getTransactionVO());
}
}
catch (SessionContainerFactoryException e) {
e.printStackTrace();
actionForward = mapping.findForward( "failure" );
}
catch (InternalServiceException e) {
e.printStackTrace();
actionForward = mapping.findForward( "failure" );
}
return actionForward;
}
}
|
package TestPack;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class facebookSignUP {
public static void main(String[] args) throws InterruptedException {
// setting up and opening up browser
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Agile1Tech\\Desktop\\Selenium Testing libraries\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Thread.sleep(2000);
// will maximizing the window
driver.manage().window().maximize();
// navigating to an url
//driver.get("https://www.facebook.com/");
driver.navigate().to("https://www.facebook.com/");
Thread.sleep(2000);
//entering value in first name text box
// data type in selenium called web element
WebElement firstName = driver.findElement(By.id("u_0_f"));
firstName.sendKeys("Michael"); Thread.sleep(1000); firstName.clear();
// Entering value for last name text box
WebElement lastName = driver.findElement(By.name("lastname"));
lastName.sendKeys("Jackson");
String url = driver.getCurrentUrl();
System.out.println(url);
String title = driver.getTitle();
System.out.println(title);
WebElement facebookLitelink = driver.findElement(By.linkText("Facebook Lite"));
String liteText = facebookLitelink.getText();
System.out.println(liteText);
facebookLitelink.click();
String liteUrl = driver.getCurrentUrl();
System.out.println(liteUrl );
String liteTtitle = driver.getTitle();
System.out.println(liteTtitle);
}
}
|
package modelo.personajes;
import modelo.*;
import modelo.fases.FaseInicialMajinBoo;
public class MajinBoo extends EnemigoDeLaTierra {
public MajinBoo(Tablero tablero,Equipo equipo) {
this.nombre = "MajinBoo";
this.tablero = tablero;
this.fase = new FaseInicialMajinBoo();
this.equipo = equipo;
this.estado = new Estado(this.nombre,this.fase);
this.ataque = new Ataque(this.getPoderDePelea());
Posicion pos = new Posicion(this.tablero.getTamanio()-1,this.tablero.getTamanio());
this.movimiento = new Movimiento(estado.getVelocidad(),pos);
}
public void ataqueEspecial(Personaje enemigo){
this.corrobarDistancias(enemigo);
this.esAtacable(enemigo);
this.corrobarKiAtaqueEspecial(StatsJuego.kiAtaqueEspecialMajinBoo);
this.ataque.convertirEnChocolate((GuerreroZ)enemigo);
this.estado.restarKi(StatsJuego.kiAtaqueEspecialMajinBoo);
}
} |
package com.yyy.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yyy.json.ARTICLE_TOPIC20Json;
/**
* Servlet implementation class ArticleTopicDistServlet
*/
@WebServlet("/articleTopicDist")
public class ArticleTopicDistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String WEBCONTENT_PATH = "";
/**
* @see HttpServlet#HttpServlet()
*/
public ArticleTopicDistServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
WEBCONTENT_PATH = request.getSession().getServletContext().getRealPath("");
System.out.println(WEBCONTENT_PATH);
String index = request.getParameter("articleIndex");
String strJsonFileName = "article_" + index + "_topic20" + ".json";
// create article_topic json file
ARTICLE_TOPIC20Json atjson = new ARTICLE_TOPIC20Json();
atjson.create(index, WEBCONTENT_PATH + File.separator + "data" + File.separator + strJsonFileName);
request.setAttribute("index", index);
request.setAttribute("jsonfilepath", "data" + File.separator + strJsonFileName);
request.getRequestDispatcher("article_topic_dist.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.metoo.module.weixin.view.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.metoo.core.annotation.SecurityMapping;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.security.support.SecurityUserHolder;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.Address;
import com.metoo.foundation.domain.IntegralGoods;
import com.metoo.foundation.domain.IntegralGoodsCart;
import com.metoo.foundation.domain.IntegralGoodsOrder;
import com.metoo.foundation.domain.IntegralLog;
import com.metoo.foundation.domain.Payment;
import com.metoo.foundation.domain.PredepositLog;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.service.IAddressService;
import com.metoo.foundation.service.IAreaService;
import com.metoo.foundation.service.IIntegralGoodsCartService;
import com.metoo.foundation.service.IIntegralGoodsOrderService;
import com.metoo.foundation.service.IIntegralGoodsService;
import com.metoo.foundation.service.IIntegralLogService;
import com.metoo.foundation.service.IPaymentService;
import com.metoo.foundation.service.IPredepositLogService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.foundation.service.IUserService;
import com.metoo.manage.admin.tools.OrderFormTools;
import com.metoo.manage.admin.tools.PaymentTools;
import com.metoo.pay.tools.PayTools;
import com.metoo.view.web.tools.IntegralViewTools;
/**
*
* <p>
* Title: WapIntegralViewAction.java
* </p>
*
* <p>
* Description:wap积分商城控制器,用来控制积分商城所有前端展示、兑换、订单信息
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author jinxinzhe
*
* @date 2014-1-4
*
* @version koala_b2b2c v2.0 2015版
*/
@Controller
public class WeixinIntegralViewAction {
@Autowired
private ISysConfigService configService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IIntegralGoodsService integralGoodsService;
@Autowired
private IUserService userService;
@Autowired
private IAddressService addressService;
@Autowired
private IIntegralGoodsOrderService integralGoodsOrderService;
@Autowired
private IIntegralGoodsCartService integralGoodsCartService;
@Autowired
private IPaymentService paymentService;
@Autowired
private IIntegralLogService integralLogService;
@Autowired
private IAreaService areaService;
@Autowired
private PaymentTools paymentTools;
@Autowired
private PayTools payTools;
@Autowired
private OrderFormTools orderFormTools;
@Autowired
private IntegralViewTools integralViewTools;
@Autowired
private IPredepositLogService predepositLogService;
@RequestMapping("/wap/integral/index.htm")
public ModelAndView integral(HttpServletRequest request,
HttpServletResponse response, String begin, String end,
String rank, String ig_user_Level) {
ModelAndView mv = new JModelAndView("wap/integral.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
if (this.configService.getSysConfig().isIntegralStore()) {
Map params = new HashMap();
String sql = "";
params.put("ig_show", true);
if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("0")) {
params.put("ig_user_Level", 0);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("1")) {
params.put("ig_user_Level", 1);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("2")) {
params.put("ig_user_Level", 2);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("3")) {
params.put("ig_user_Level", 3);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else {
params.put("ig_user_Level", 0);
sql = " and obj.ig_user_Level=:ig_user_Level";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("2000")) {
params.put("begin", 2000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("4000")) {
params.put("begin", 4000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("6000")) {
params.put("begin", 6000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("10000")) {
params.put("begin", 10000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("1999")) {
params.put("end", 1999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("3999")) {
params.put("end", 3999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("4999")) {
params.put("end", 4999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("9999")) {
params.put("end", 9999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
sql = sql + " order by obj.addTime desc";
List<IntegralGoods> integralGoods = this.integralGoodsService
.query("select obj from IntegralGoods obj where obj.ig_show=:ig_show"
+ sql, params, -1, 6);
mv.addObject("integralGoods", integralGoods);
mv.addObject("integralViewTools", integralViewTools);
if (SecurityUserHolder.getCurrentUser() != null) {
mv.addObject("user",
this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId()));
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "系统未开启积分商城");
mv.addObject("url", CommUtil.getURL(request) + "/index.htm");
}
mv.addObject("end", end);
mv.addObject("begin", begin);
mv.addObject("ig_user_Level", ig_user_Level);
mv.addObject("rank", rank);
return mv;
}
@RequestMapping("/wap/integral/integral_data.htm")
public ModelAndView intergral_data(HttpServletRequest request,
HttpServletResponse response, String begin, String end,
String rank, String ig_user_Level, String begin_count) {
ModelAndView mv = new JModelAndView("wap/integral_data.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
Map params = new HashMap();
String sql = "";
params.put("ig_show", true);
if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("0")) {
params.put("ig_user_Level", 0);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("1")) {
params.put("ig_user_Level", 1);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("2")) {
params.put("ig_user_Level", 2);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else if (!CommUtil.null2String(ig_user_Level).equals("")
&& CommUtil.null2String(ig_user_Level).equals("3")) {
params.put("ig_user_Level", 3);
sql = " and obj.ig_user_Level=:ig_user_Level";
} else {
params.put("ig_user_Level", 0);
sql = " and obj.ig_user_Level=:ig_user_Level";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("2000")) {
params.put("begin", 2000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("4000")) {
params.put("begin", 4000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("6000")) {
params.put("begin", 6000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(begin).equals("")
&& CommUtil.null2String(begin).equals("10000")) {
params.put("begin", 10000);
sql = sql + " and obj.ig_goods_integral>=:begin";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("1999")) {
params.put("end", 1999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("3999")) {
params.put("end", 3999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("4999")) {
params.put("end", 4999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
if (!CommUtil.null2String(end).equals("")
&& CommUtil.null2String(end).equals("9999")) {
params.put("end", 9999);
sql = sql + " and obj.ig_goods_integral<=:end";
}
sql = sql + " order by obj.addTime desc";
List<IntegralGoods> integralGoods = this.integralGoodsService.query(
"select obj from IntegralGoods obj where obj.ig_show=:ig_show"
+ sql, params, CommUtil.null2Int(begin_count), 6);
mv.addObject("integralGoods", integralGoods);
mv.addObject("integralViewTools", integralViewTools);
if (SecurityUserHolder.getCurrentUser() != null) {
mv.addObject("user", this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId()));
}
mv.addObject("end", end);
mv.addObject("begin", begin);
mv.addObject("ig_user_Level", ig_user_Level);
mv.addObject("begin_count", begin_count);
mv.addObject("rank", rank);
return mv;
}
@RequestMapping("/wap/integral/view.htm")
public ModelAndView integral_view(HttpServletRequest request,
HttpServletResponse response, String id) {
ModelAndView mv = new JModelAndView("wap/integral_view.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
if (this.configService.getSysConfig().isIntegralStore()) {
IntegralGoods obj = this.integralGoodsService.getObjById(CommUtil
.null2Long(id));
if (obj != null) {
obj.setIg_click_count(obj.getIg_click_count() + 1);
this.integralGoodsService.update(obj);
List<IntegralGoodsCart> gcs = this.integralGoodsCartService
.query("select obj from IntegralGoodsCart obj order by obj.addTime desc",
null, 0, 20);
mv.addObject("gcs", gcs);
mv.addObject("obj", obj);
if (SecurityUserHolder.getCurrentUser() != null) {
mv.addObject("user", this.userService
.getObjById(SecurityUserHolder.getCurrentUser()
.getId()));
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "不存在该商品,参数错误");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "系统未开启积分商城");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
}
return mv;
}
@SecurityMapping(title = "积分兑换第一步", value = "/wap/integral/exchange1.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/exchange1.htm")
public ModelAndView integral_exchange1(HttpServletRequest request,
HttpServletResponse response, String id, String exchange_count) {
ModelAndView mv = new JModelAndView("wap/success.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
if (this.configService.getSysConfig().isIntegralStore()) {
IntegralGoods obj = this.integralGoodsService.getObjById(CommUtil
.null2Long(id));
int exchange_status = 0;// -1为数量不足,-2为限制兑换,-3为积分不足,-4为兑换时间已过,-5为会员等级不够,0为正常兑换
if (obj != null) {
if (exchange_count == null || exchange_count.equals("")) {
exchange_count = "1";
}
if (obj.getIg_goods_count() < CommUtil.null2Int(exchange_count)) {
exchange_status = -1;
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "库存数量不足,重新选择兑换数量");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/view.htm?id=" + id);
}
if (obj.isIg_limit_type()
&& obj.getIg_limit_count() < CommUtil
.null2Int(exchange_count)) {
exchange_status = -2;
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "限制最多兑换" + obj.getIg_limit_count()
+ ",重新选择兑换数量");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/view.htm?id=" + id);
}
int cart_total_integral = obj.getIg_goods_integral()
* CommUtil.null2Int(exchange_count);
User user = this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId());
if (user.getIntegral() < cart_total_integral) {
exchange_status = -3;
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "您的积分不足");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/view.htm?id=" + id);
}
if (obj.isIg_time_type()) {
if (obj.getIg_begin_time() != null
&& obj.getIg_end_time() != null) {
if ((obj.getIg_begin_time().after(new Date()) || obj
.getIg_end_time().before(new Date()))) {
exchange_status = -4;
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1,
request, response);
mv.addObject("op_title", "兑换已经过期");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/view.htm?id=" + id);
}
}
}
if (this.integralViewTools.query_user_level(CommUtil
.null2String(user.getId())) < obj.getIg_user_Level()) {
exchange_status = -5;
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "您的会员等级不够");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/view.htm?id=" + id);
}
}
if (exchange_status == 0) {
Map map = new HashMap();
map.put("user_id", SecurityUserHolder.getCurrentUser().getId()
.toString());
List<IntegralGoodsCart> integral_goods_cart = this.integralGoodsCartService
.query(""
+ "select obj from IntegralGoodsCart obj where obj.user_id=:user_id",
map, -1, -1);
if (integral_goods_cart == null) {
integral_goods_cart = new ArrayList<IntegralGoodsCart>();
}
boolean add = obj == null ? false : true;
IntegralGoodsCart same = new IntegralGoodsCart();
for (IntegralGoodsCart igc : integral_goods_cart) {
if (igc.getGoods().getId().toString().equals(id)) {
add = false;
same = igc;
break;
}
}
User user = SecurityUserHolder.getCurrentUser();
if (add) {
IntegralGoodsCart gc = new IntegralGoodsCart();
gc.setAddTime(new Date());
gc.setCount(CommUtil.null2Int(exchange_count));
gc.setGoods(obj);
gc.setTrans_fee(obj.getIg_transfee());
gc.setIntegral(CommUtil.null2Int(exchange_count)
* obj.getIg_goods_integral());
gc.setUser_id(user.getId().toString());
this.integralGoodsCartService.save(gc);
integral_goods_cart.add(gc);
} else {
IntegralGoodsCart gc = same;
gc.setAddTime(new Date());
gc.setCount(CommUtil.null2Int(exchange_count)
+ gc.getCount());
gc.setTrans_fee(obj.getIg_transfee());
gc.setIntegral(gc.getCount() * obj.getIg_goods_integral());
this.integralGoodsCartService.update(gc);
}
mv.addObject("op_title", "积分购物车添加成功");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/integral_cart.htm");
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "系统未开启积分商城");
mv.addObject("url", CommUtil.getURL(request) + "/index.htm");
}
return mv;
}
@SecurityMapping(title = "积分兑换购物车", value = "/wap/integral/integral_cart.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/integral_cart.htm")
public ModelAndView integral_cart(HttpServletRequest request,
HttpServletResponse response, String id) {
ModelAndView mv = new JModelAndView("wap/integral_exchange1.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
User user = SecurityUserHolder.getCurrentUser();
Map map = new HashMap();
map.put("user_id", user.getId().toString());
map.put("ig_show", true);
List<IntegralGoodsCart> integral_goods_cart = this.integralGoodsCartService
.query("select obj from IntegralGoodsCart obj where obj.user_id=:user_id and obj.goods.ig_show=:ig_show",
map, -1, -1);
map.put("ig_show", false);
List<IntegralGoodsCart> integral_goods_cart_false = this.integralGoodsCartService
.query("select obj from IntegralGoodsCart obj where obj.user_id=:user_id and obj.goods.ig_show=:ig_show",
map, -1, -1);
int total_integral = 0;
BigDecimal ship_price = new BigDecimal("0");
for (IntegralGoodsCart igc : integral_goods_cart) {
total_integral = total_integral + igc.getIntegral();
if (igc.getGoods().getIg_transfee_type() == 1) {
ship_price = ship_price.add(igc.getTrans_fee());
}
}
mv.addObject("total_integral", total_integral);
mv.addObject("ship_price", ship_price);
mv.addObject("integral_cart", integral_goods_cart);
mv.addObject("integral_cart_false", integral_goods_cart_false);
mv.addObject("user", this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId()));
return mv;
}
@SecurityMapping(title = "积分兑换删除购物车", value = "/wap/integral/cart_remove.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/cart_remove.htm")
public void integral_cart_remove(HttpServletRequest request,
HttpServletResponse response, String id) {
User user = SecurityUserHolder.getCurrentUser();
Map map1 = new HashMap();
map1.put("user_id", user.getId().toString());
this.integralGoodsCartService.delete(CommUtil.null2Long(id));
List<IntegralGoodsCart> igcs = this.integralGoodsCartService
.query("select obj from IntegralGoodsCart obj where obj.user_id=:user_id",
map1, -1, -1);
int total_integral = 0;
BigDecimal ship_price = new BigDecimal("0");
for (IntegralGoodsCart igc : igcs) {
total_integral = total_integral + igc.getIntegral();
if (igc.getGoods().getIg_transfee_type() == 1) {
ship_price = ship_price.add(igc.getTrans_fee());
}
}
Map map = new HashMap();
map.put("status", 100);
map.put("total_integral", total_integral);
map.put("ship_price", ship_price);
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(Json.toJson(map, JsonFormat.compact()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SecurityMapping(title = "积分兑换第二步", value = "/wap/integral/exchange2.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/exchange2.htm")
public ModelAndView integral_exchange2(HttpServletRequest request,
HttpServletResponse response, String id, String exchange_count) {
ModelAndView mv = new JModelAndView("wap/integral_exchange2.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
if (this.configService.getSysConfig().isIntegralStore()) {
Map map = new HashMap();
map.put("user_id", SecurityUserHolder.getCurrentUser().getId()
.toString());
map.put("ig_show", true);
List<IntegralGoodsCart> igcs = this.integralGoodsCartService
.query(""
+ "select obj from IntegralGoodsCart obj where obj.user_id=:user_id and obj.goods.ig_show=:ig_show",
map, -1, -1);
if (igcs.size() > 0) {
User user = this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId());
Map params = new HashMap();
params.put("user_id", SecurityUserHolder.getCurrentUser()
.getId());
List<Address> addrs = this.addressService
.query("select obj from Address obj where obj.user.id=:user_id",
params, -1, -1);
if (addrs.size() >= 1) {
mv.addObject("addrs", addrs);
}
params.put("default_val", 1);
List<Address> addrs_default_val = this.addressService
.query("select obj from Address obj where obj.user.id=:user_id and obj.default_val=:default_val",
params, -1, -1);
if (addrs_default_val.size() > 0) {
mv.addObject("addrs_default_val", addrs_default_val.get(0));
}
mv.addObject("igcs",
igcs == null ? new ArrayList<IntegralGoodsCart>()
: igcs);
int total_integral = 0;
double trans_fee = 0;
for (IntegralGoodsCart igc : igcs) {
total_integral = total_integral + igc.getIntegral();
trans_fee = CommUtil.null2Double(igc.getTrans_fee())
+ trans_fee;
}
if (user.getIntegral() < total_integral) {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "兑换积分不足");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/exchange1.htm");
return mv;
}
mv.addObject("trans_fee", trans_fee);
mv.addObject("total_integral", total_integral);
String integral_order_session = CommUtil.randomString(32);
mv.addObject("integral_order_session", integral_order_session);
request.getSession(false).setAttribute(
"integral_order_session", integral_order_session);
map.clear();
map.put("user_id", user.getId());
List<Address> addresses = this.addressService
.query("select obj from Address obj where obj.user.id=:user_id",
map, -1, -1);
mv.addObject("addresses", addresses);
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "兑换购物车为空");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "系统未开启积分商城");
mv.addObject("url", CommUtil.getURL(request) + "/wap/index.htm");
}
return mv;
}
@SecurityMapping(title = "积分兑换第三步", value = "/wap/integral/exchange3.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/exchange3.htm")
public ModelAndView integral_exchange3(HttpServletRequest request,
HttpServletResponse response, String addr_id, String igo_msg,
String integral_order_session) {
ModelAndView mv = new JModelAndView("wap/integral_exchange3.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
if (this.configService.getSysConfig().isIntegralStore()) {
List<IntegralGoodsCart> igcs = this.integralGoodsCartService
.query(""
+ "select obj from IntegralGoodsCart obj where obj.user_id="
+ SecurityUserHolder.getCurrentUser().getId()
.toString(), null, -1, -1);
String integral_order_session1 = CommUtil.null2String(request
.getSession(false).getAttribute("integral_order_session"));
if (integral_order_session1.equals("")) {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "表单已经过期");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
} else {
if (integral_order_session1.equals(integral_order_session
.trim())) {
if (igcs != null) {
int total_integral = 0;
double trans_fee = 0;
for (IntegralGoodsCart igc : igcs) {
total_integral = total_integral + igc.getIntegral();
trans_fee = CommUtil
.null2Double(igc.getTrans_fee())
+ trans_fee;
}
IntegralGoodsOrder order = new IntegralGoodsOrder();
Address addr = this.addressService.getObjById(CommUtil
.null2Long(addr_id));
order.setAddTime(new Date());
// 设置收货地址信息
order.setReceiver_Name(addr.getTrueName());
order.setReceiver_area(addr.getArea().getParent()
.getParent().getAreaName()
+ addr.getArea().getParent().getAreaName()
+ addr.getArea().getAreaName());
order.setReceiver_area_info(addr.getArea_info());
order.setReceiver_mobile(addr.getMobile());
order.setReceiver_telephone(addr.getTelephone());
order.setReceiver_zip(addr.getZip());
List<Map> json_list = new ArrayList<Map>();
for (IntegralGoodsCart gc : igcs) {
Map json_map = new HashMap();
json_map.put("id", gc.getGoods().getId());
json_map.put("ig_goods_name", gc.getGoods()
.getIg_goods_name());
json_map.put("ig_goods_price", gc.getGoods()
.getIg_goods_price());
json_map.put("ig_goods_count", gc.getCount());
json_map.put("ig_goods_img",
CommUtil.getURL(request)
+ "/"
+ gc.getGoods().getIg_goods_img()
.getPath()
+ "/"
+ gc.getGoods().getIg_goods_img()
.getName()
+ "_small."
+ gc.getGoods().getIg_goods_img()
.getExt());
json_list.add(json_map);
}
String json = Json.toJson(json_list,
JsonFormat.compact());
order.setGoods_info(json);// 商品信息json
order.setIgo_msg(igo_msg);
User user = this.userService
.getObjById(SecurityUserHolder.getCurrentUser()
.getId());
order.setIgo_order_sn("igo"
+ CommUtil.formatTime("yyyyMMddHHmmss",
new Date()) + user.getId());
order.setIgo_user(user);
order.setIgo_trans_fee(BigDecimal.valueOf(trans_fee));
order.setIgo_total_integral(total_integral);
if (trans_fee == 0) {
order.setIgo_status(20);// 无运费订单,默认状态为已付款
order.setIgo_pay_time(new Date());
order.setIgo_payment("no_fee");
this.integralGoodsOrderService.save(order);
for (IntegralGoodsCart igc : igcs) {
IntegralGoods goods = igc.getGoods();
goods.setIg_goods_count(goods
.getIg_goods_count() - igc.getCount());
goods.setIg_exchange_count(goods
.getIg_exchange_count()
+ igc.getCount());
this.integralGoodsService.update(goods);
}
request.getSession(false).removeAttribute(
"integral_goods_cart");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/buyer/integral_order_list.htm");
mv.addObject("order", order);
} else {
order.setIgo_status(0);// 有运费订单,默认状态为未付款
this.integralGoodsOrderService.save(order);
mv = new JModelAndView(
"wap/integral_exchange4.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1,
request, response);
mv.addObject("obj", order);
mv.addObject("paymentTools", paymentTools);
}
for (IntegralGoodsCart igc : igcs) {
this.integralGoodsCartService.delete(igc.getId());
}
// 用户积分减少
user.setIntegral(user.getIntegral()
- order.getIgo_total_integral());
this.userService.update(user);
// 记录日志
IntegralLog log = new IntegralLog();
log.setAddTime(new Date());
log.setContent("兑换商品消耗积分");
log.setIntegral(-order.getIgo_total_integral());
log.setIntegral_user(user);
log.setType("integral_order");
this.integralLogService.save(log);
request.getSession(false).removeAttribute(
"integral_goods_cart");
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1,
request, response);
mv.addObject("op_title", "兑换购物车为空");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "参数错误,订单提交失败");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/index.htm");
}
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "系统未开启积分商城");
mv.addObject("url", CommUtil.getURL(request) + "/wap/index.htm");
}
return mv;
}
@SecurityMapping(title = "积分兑换选择支付方式", value = "/wap/integral/order_pay.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/order_pay.htm")
public ModelAndView integral_order_pay(HttpServletRequest request,
HttpServletResponse response, String payType,
String integral_order_id) {
ModelAndView mv = null;
IntegralGoodsOrder order = this.integralGoodsOrderService
.getObjById(CommUtil.null2Long(integral_order_id));
if ("wx_pay".equals(payType)) {
String type = "integral";
try {
response.sendRedirect("/weixin/pay/wx_pay.htm?id="
+ integral_order_id + "&showwxpaytitle=1&type=" + type);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "支付方式错误!");
mv.addObject("url", CommUtil.getURL(request) + "/wap/index.htm");
}
}
if (order.getIgo_status() == 0) {
if (CommUtil.null2String(payType).equals("")) {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "支付方式错误!");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
} else {
// 给订单添加支付方式
order.setIgo_payment(payType);
this.integralGoodsOrderService.update(order);
if (payType.equals("balance")) {
mv = new JModelAndView("wap/integral_balance_pay.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("paymentTools", paymentTools);
} else {
mv = new JModelAndView("wap/line_pay.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("payType", payType);
mv.addObject("url", CommUtil.getURL(request));
mv.addObject("payTools", payTools);
mv.addObject("type", "integral");
Map params = new HashMap();
params.put("install", true);
params.put("mark", payType);
List<Payment> payments = this.paymentService
.query("select obj from Payment obj where obj.install=:install and obj.mark=:mark",
params, -1, -1);
mv.addObject("payment_id", payments.size() > 0 ? payments
.get(0).getId() : new Payment());
}
mv.addObject("integral_order_id", integral_order_id);
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "该订单不能进行付款!");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/integral/index.htm");
}
return mv;
}
@SecurityMapping(title = "积分兑换预存款支付", value = "/wap/integral/order_pay_balance.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/order_pay_balance.htm")
public ModelAndView integral_order_pay_balance(HttpServletRequest request,
HttpServletResponse response, String payType,
String integral_order_id, String igo_pay_msg) {
ModelAndView mv = new JModelAndView("wap/success.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
IntegralGoodsOrder order = this.integralGoodsOrderService
.getObjById(CommUtil.null2Long(integral_order_id));
User user = this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId());
if (order.getIgo_user().getId() == user.getId()) {
if (CommUtil.null2Double(user.getAvailableBalance()) > CommUtil
.null2Double(order.getIgo_trans_fee())) {
order.setIgo_pay_msg(igo_pay_msg);
order.setIgo_status(20);
order.setIgo_payment("balance");
order.setIgo_pay_time(new Date());
boolean ret = this.integralGoodsOrderService.update(order);
if (ret) {
user.setAvailableBalance(BigDecimal.valueOf(CommUtil
.subtract(user.getAvailableBalance(),
order.getIgo_trans_fee())));
this.userService.update(user);
// 执行库存减少
List<IntegralGoods> igs = this.orderFormTools
.query_integral_all_goods(CommUtil
.null2String(order.getId()));
for (IntegralGoods obj : igs) {
int count = this.orderFormTools
.query_integral_one_goods_count(order,
CommUtil.null2String(obj.getId()));
obj.setIg_goods_count(obj.getIg_goods_count() - count);
obj.setIg_exchange_count(obj.getIg_exchange_count()
+ count);
this.integralGoodsService.update(obj);
}
}
// 记录预存款日志
PredepositLog log = new PredepositLog();
log.setAddTime(new Date());
log.setPd_log_user(user);
log.setPd_log_amount(order.getIgo_trans_fee());
log.setPd_op_type("消费");
log.setPd_type("可用预存款");
log.setPd_log_info("订单" + order.getIgo_order_sn()
+ "兑换礼品减少可用预存款");
this.predepositLogService.save(log);
mv.addObject("op_title", "预付款支付成功!");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/buyer/integral_order_list.htm");
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "可用余额不足,支付失败!");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/buyer/integral_order_list.htm");
}
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "请求参数错误");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/buyer/integral_order_list.htm");
}
return mv;
}
@RequestMapping("/wap/integral/order_finish.htm")
public ModelAndView integral_order_finish(HttpServletRequest request,
HttpServletResponse response, String order_id) {
ModelAndView mv = new JModelAndView("wap/integral_order_finish.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
IntegralGoodsOrder obj = this.integralGoodsOrderService
.getObjById(CommUtil.null2Long(order_id));
mv.addObject("obj", obj);
return mv;
}
@SecurityMapping(title = "积分兑换去支付", value = "/wap/integral/order_pay_view.htm*", rtype = "buyer", rname = "wap端积分兑换", rcode = "wap_integral_exchange", rgroup = "wap端积分兑换")
@RequestMapping("/wap/integral/order_pay_view.htm")
public ModelAndView integral_order_pay_view(HttpServletRequest request,
HttpServletResponse response, String id) {
ModelAndView mv = new JModelAndView("wap/integral_exchange4.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request, response);
IntegralGoodsOrder obj = this.integralGoodsOrderService
.getObjById(CommUtil.null2Long(id));
if (obj.getIgo_status() == 0) {
mv.addObject("obj", obj);
mv.addObject("paymentTools", this.paymentTools);
mv.addObject("url", CommUtil.getURL(request));
} else if (obj.getIgo_status() < 0) {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "该订单已经取消!");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/buyer/integral_order_list.htm");
} else {
mv = new JModelAndView("wap/error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 1, request,
response);
mv.addObject("op_title", "该订单已经付款!");
mv.addObject("url", CommUtil.getURL(request)
+ "/wap/buyer/integral_order_list.htm");
}
return mv;
}
@RequestMapping("/wap/integral/adjust_count.htm")
public void integral_adjust_count(HttpServletRequest request,
HttpServletResponse response, String goods_id, String count) {
User user = this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId());
Map map = new HashMap();
map.put("user_id", user.getId().toString());
map.put("ig_show", true);
List<IntegralGoodsCart> igcs = this.integralGoodsCartService
.query(""
+ "select obj from IntegralGoodsCart obj where obj.user_id=:user_id and obj.goods.ig_show=:ig_show",
map, -1, -1);
IntegralGoodsCart obj = null;
int old_num = 0;
int num = CommUtil.null2Int(count);
for (IntegralGoodsCart igc : igcs) {
if (igc.getGoods().getId().toString().equals(goods_id)) {
IntegralGoods ig = igc.getGoods();
old_num = igc.getCount();
if (num > ig.getIg_goods_count()) {
num = ig.getIg_goods_count();
}
if (ig.isIg_limit_type() && ig.getIg_limit_count() < num) {
num = ig.getIg_limit_count();
}
igc.setCount(num);
igc.setIntegral(igc.getGoods().getIg_goods_integral()
* CommUtil.null2Int(num));
this.integralGoodsCartService.update(igc);
obj = igc;
break;
}
}
int total_integral = 0;
for (IntegralGoodsCart igc : igcs) {
total_integral = total_integral + igc.getIntegral();
}
// 判断积分
if (total_integral > user.getIntegral()) {
for (IntegralGoodsCart igc : igcs) {
if (igc.getGoods().getId().toString().equals(goods_id)) {
num = old_num;
IntegralGoods ig = igc.getGoods();
igc.setCount(num);
igc.setIntegral(igc.getGoods().getIg_goods_integral()
* CommUtil.null2Int(num));
this.integralGoodsCartService.update(igc);
obj = igc;
break;
}
}
total_integral = 0;
for (IntegralGoodsCart igc : igcs) {
total_integral = total_integral + igc.getIntegral();
}
}
request.getSession(false).setAttribute("integral_goods_cart", igcs);
map.clear();
map.put("total_integral", total_integral);
map.put("integral", obj.getIntegral());
map.put("count", num);
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(Json.toJson(map, JsonFormat.compact()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.esum.comp.dbm.process.outbound;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.dbm.DBConfig;
import com.esum.comp.dbm.table.DBIfInfoRecord;
import com.esum.comp.dbm.table.DBIfInfoTable;
import com.esum.comp.dbm.table.TriggerInfo;
import com.esum.framework.FrameworkSystemVariables;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.listener.LegacyListener;
import com.esum.framework.core.component.table.InfoTableManager;
import com.esum.framework.core.exception.SystemException;
/**
* DBListenerFactory
* - DBListener 클래스를 관리하기 위한 클래스
*
* Copyright(c) eSum Technologies., inc. All rights reserved.
*/
public class DBListenerFactory extends LegacyListener {
private static final long serialVersionUID = 20150202L;
private Logger log = LoggerFactory.getLogger(DBListenerFactory.class);
private List<DBIfInfoRecord> triggerIfList;
private Map<String, DBListener> dbListenerList = new HashMap<String, DBListener>();
private String nodeId;
public DBListenerFactory() throws SystemException {
nodeId = System.getProperty(FrameworkSystemVariables.NODE_ID);
DBIfInfoTable dbIfInfoTable =
(DBIfInfoTable)InfoTableManager.getInstance().getInfoTable(DBConfig.DB_IFINFO_TABLE_ID);
triggerIfList = dbIfInfoTable.getTriggeredIfList();
}
@Override
protected void startupLegacy() throws SystemException {
traceId = "[" +getComponentId() + "][" + nodeId + "] ";
log.info(traceId + "DB Outbound Listener starting. nodeId : " + nodeId);
for (int i = 0; i < triggerIfList.size(); i++) {
DBIfInfoRecord dbIfInfo = triggerIfList.get(i);
String interfaceId = dbIfInfo.getInterfaceId();
if(log.isDebugEnabled())
log.debug(traceId+"Starting Db listener. interfaceId : "+interfaceId);
if (dbIfInfo.containsNodeId(nodeId)) {
try {
DBListener dbListener = new DBListener(this, dbIfInfo);
dbListener.startup();
dbListenerList.put(dbIfInfo.getInterfaceId(), dbListener);
log.info(traceId+"["+interfaceId+"] DB Outbound Listener started.");
} catch (Exception e) {
log.error(traceId+"["+interfaceId+"] DB Outbound Listener starting error.", e);
}
}
}
log.info(traceId + dbListenerList.size() + " DB Listener started.");
}
public boolean isRunning() {
if(dbListenerList==null || dbListenerList.size()==0)
return false;
Iterator<String> i = dbListenerList.keySet().iterator();
while (i.hasNext()) {
String key = i.next();
DBListener dbListener = dbListenerList.get(key);
if (!dbListener.isRunning())
return false;
}
return true;
}
public void reload(String[] reloadIds) throws SystemException {
if (dbListenerList.containsKey(reloadIds[0])) {
DBListener dbListener = (DBListener)dbListenerList.get(reloadIds[0]);
dbListener.shutdown();
dbListener = null;
dbListenerList.remove(reloadIds[0]);
}
DBIfInfoTable dbIfInfoTable =
(DBIfInfoTable)InfoTableManager.getInstance().getInfoTable(DBConfig.DB_IFINFO_TABLE_ID);
DBIfInfoRecord dbIfInfo = null;
try{
dbIfInfo = (DBIfInfoRecord) dbIfInfoTable.getInfoRecord(reloadIds);
}catch(ComponentException e){
log.error(traceId + "reload()", e);
}
if (dbIfInfo != null && dbIfInfo.isDbTriggerUse()) {
String interfaceId = dbIfInfo.getInterfaceId();
List<String> dbIfNodeList = dbIfInfo.getNodeList();
log.debug(traceId+"["+interfaceId+"] reload. nodeList : " + dbIfNodeList);
if (dbIfInfo.containsNodeId(nodeId)) {
try {
//TriggerInfo Cache 삭제
TriggerInfo.removeInstance(dbIfInfo.getDbTriggerInfo());
DBListener dbListener = new DBListener(this, dbIfInfo);
dbListener.startup();
dbListenerList.put(dbIfInfo.getInterfaceId(), dbListener);
log.info(traceId+"["+interfaceId+"] DB Outbound Listener after reloading info table restarted.");
} catch (Exception e) {
log.error(traceId+"["+interfaceId+"] DB Outbound Listener reload starting error.", e);
throw new ComponentException(e.toString());
}
}
}
}
protected void shutdownLegacy() throws SystemException {
Iterator<String> i = dbListenerList.keySet().iterator();
while (i.hasNext()) {
String key = i.next();
DBListener dbListener = dbListenerList.get(key);
dbListener.shutdown();
}
dbListenerList.clear();
}
}
|
package com.GestiondesClub.controller;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.GestiondesClub.dto.CreeClubDto;
import com.GestiondesClub.entities.Club;
import com.GestiondesClub.entities.ClubTarifInscription;
import com.GestiondesClub.entities.DemandeCreationClub;
import com.GestiondesClub.entities.Mail;
import com.GestiondesClub.entities.MembreFondateur;
import com.GestiondesClub.services.AnneUnivService;
import com.GestiondesClub.services.ClubService;
import com.GestiondesClub.services.ClubTarifationService;
import com.GestiondesClub.services.DemCreationClubService;
import com.GestiondesClub.services.EmailService;
import com.GestiondesClub.services.MembreClubServ;
import com.GestiondesClub.services.MembreFondateurService;
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8000")
public class DemCreationClubController {
@Autowired
private DemCreationClubService demCreClub ;
@Autowired
private MembreFondateurService membFondaServ ;
@Autowired
private MembreClubServ membreDeClubServ;
@Autowired
private ClubService clubServ;
@Autowired
private EmailService mailServ;
@Autowired
private ClubTarifationService tarifInscServ;
@Autowired
private AnneUnivService anneServ;
/*@RequestMapping("/demandecreationclub/list")
public List<DemandeCreationClub> getAllDemandes()
{
return demCreClub.getAllDem();
}*/
@RequestMapping("/demandecreationclub/list")
public List<CreeClubDto> getDem()
{
return demCreClub.getDem();
}
@RequestMapping("/demandecreationclub/{id}")
public Optional<DemandeCreationClub> getDemande(@PathVariable Long id)
{
return demCreClub.getDem(id);
}
@PutMapping("/demandecreationclub/create")
public void createDemande(@RequestBody DemandeCreationClub dem){
DemandeCreationClub d ;
dem.setDatedemande(new Date());
d = demCreClub.save(dem);
for(MembreFondateur m : dem.getMembresFondateur())
{
m.setDemandeCreationClub(d);
membFondaServ.saveMbreFonda(m);
}
}
@PutMapping("/demandecreationclub/update")
public DemandeCreationClub updateDemande(@RequestBody DemandeCreationClub dem){
return demCreClub.updateDemande(dem);
}
@PutMapping("/demandecreationclub/Confirm")
public DemandeCreationClub confirmDemande(@RequestBody DemandeCreationClub dem){
if(dem.getId()==null)
return null;
DemandeCreationClub d = demCreClub.getDem(dem.getId()).get();
d.setConfirmer(dem.getConfirmer());
d = demCreClub.save(d);
if(d==null)
return null;
Club c = new Club();
c.setNomClub(dem.getNomClub());
c.setDateCreation(new Date());
c.setActivityStop(false);
c.setClubLogo("no_Image.jpg");
c.setCouvertureClub("cover-default.jpg");
c.setDemandeCreationClub(d);
Club newClub = clubServ.save(c);
if(newClub == null)
return null;
for(MembreFondateur membFonda : dem.getMembresFondateur())
{
membreDeClubServ.saveMembre(membFonda,newClub);
}
ClubTarifInscription tr = new ClubTarifInscription();
tr.setClub(newClub);
tr.setTarifation(0);
tr.setAnneeUniver(anneServ.findlastOne());
tarifInscServ.updateTarif(tr);
Mail m = new Mail();
m.setContent("Votre Demande de Club "+dem.getNomClub()+" a été accepter vous peuvait Maintenamt accéder"
+ " au interface est mise a jour votre club est crée des évenement");
m.setFrom("systemgestionclubfsegs@gmail.com");
m.setSubject("Confirmation de création de Club");
m.setTo("boulbebazz@yahoo.fr");
//mailServ.sendSimpleMessage(m);
return null;
}
}
|
package com.sdr.sdr;
import com.mongodb.MongoException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import static com.sdr.sdr.Login.fecha;
import javax.swing.table.DefaultTableModel;
import static com.sdr.sdr.Main.db;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import org.bson.Document;
/**
*
* @author david
*/
public class INVENTARIO extends javax.swing.JFrame {
Icon modificar;
public boolean reponer = true;
public INVENTARIO() {
initComponents();
llenar();
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Login n=new Login();
n.setVisible(true);
}
});
jLabel5.setText(fecha);
Timer tiempo=new Timer(100,new INVENTARIO.hora());
tiempo.start();
}
class hora implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
Date hora=new Date();
String pmam="hh:mm:ss a";
SimpleDateFormat format=new SimpleDateFormat(pmam);
Calendar hoy=Calendar.getInstance();
jLabel6.setText(String.format(format.format(hora),hoy));
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPopupMenu1 = new javax.swing.JPopupMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jTextField1 = new javax.swing.JTextField();
bBuscar = new javax.swing.JButton();
bmostrar = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
jButton6 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jMenuItem1.setText("Verificar Si El Inventario es bajo");
jMenuItem1.setComponentPopupMenu(jPopupMenu1);
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jPopupMenu1.add(jMenuItem1);
jMenuItem2.setText("Actualizar Inventario");
jMenuItem2.setComponentPopupMenu(jPopupMenu1);
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jPopupMenu1.add(jMenuItem2);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setIconImage(getIconImage());
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField1KeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextField1KeyTyped(evt);
}
});
getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(72, 361, 143, -1));
bBuscar.setText("Buscar");
bBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bBuscarActionPerformed(evt);
}
});
getContentPane().add(bBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(221, 360, -1, -1));
bmostrar.setText("Mostrar Todos");
bmostrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bmostrarActionPerformed(evt);
}
});
getContentPane().add(bmostrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(292, 360, -1, -1));
jButton1.setText("EXIT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 360, -1, -1));
jButton2.setText("Agregar Producto");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 50, 123, -1));
jLabel1.setText("Producto:");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 364, 54, -1));
jLabel2.setFont(new java.awt.Font("Tw Cen MT Condensed", 3, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("INVENTARIO");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 119, 18));
jButton3.setText("Modificar Producto");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 80, -1, -1));
jButton4.setText("Eliminar producto");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 110, 123, -1));
jButton5.setText("Ventas");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 140, 120, -1));
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane2.setViewportView(table);
getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 57, 547, 285));
jButton6.setText("Reportes");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
getContentPane().add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 170, 120, -1));
jLabel5.setText("jLabel5");
getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 300, 120, 20));
jLabel6.setText("jLabel6");
getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 330, 120, -1));
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SDR2.png"))); // NOI18N
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 700, 400));
pack();
}// </editor-fold>//GEN-END:initComponents
public void busca() {
//Metodo para hacer busquedas
MongoCollection<Document> coll = db.getCollection("productos");
Document filtro = new Document(); //si se realiza consulta con foltro se hace este objeto
String j = jTextField1.getText();
filtro = new Document("ARTICULO", new Document("$regex", j));//pones el filtro que se requiera
MongoCursor<Document> cursor = coll.find(filtro).iterator();
DefaultTableModel model = Main.tabla();
try {
while (cursor.hasNext()) {
Document doc = cursor.next();
String item = (String) doc.get("ARTICULO"), Tipo = (String) doc.get("TIPO"), Codigo = (String) doc.get("CODIGO");
Object costoc = (Object) doc.get("COSTO"), costov = (Object) doc.get("PRECIO");
Document qty = (Document) doc.get("STOCK");
Object cantidad = (Object) qty.get("ACTUAL"), cantidad1 = (Object) qty.get("MINIMO");
try {
double i = (double) cantidad;
double k = (double) cantidad1;
if (i <= k) {
String Stock = "Reponer";
model.addRow(new Object[]{item, Codigo, Tipo, costoc, costov, Stock});
reponer = false;
} else {
String Stock = "Suficiente";
model.addRow(new Object[]{item, Codigo, Tipo, costoc, costov, Stock});
}
} catch (Exception e) {
String Stock = "Sin Informacion";
model.addRow(new Object[]{item, Codigo, Tipo, costoc, costov, Stock});
}
}
table.setModel(model);
color c = new color(5);
//Esre bloque de comentarios hace que sucedan algunos errores y hace que no cargue bien la interfaz
table.getColumnModel().getColumn(5).setCellRenderer(c);
table.getColumnModel().getColumn(0).setPreferredWidth(70);
table.getColumnModel().getColumn(1).setPreferredWidth(20);
table.getColumnModel().getColumn(2).setPreferredWidth(20);
table.getColumnModel().getColumn(3).setPreferredWidth(20);
table.getColumnModel().getColumn(4).setPreferredWidth(40);
} catch (MongoException e) {
e.printStackTrace();
} finally {
cursor.close();
}
}
/*public Image getIconImage() {
Image retValue = Toolkit.getDefaultToolkit().
getImage(ClassLoader.getSystemResource("Media/flame.png"));
return retValue;
}*/
public void llenar() {
MongoCollection<Document> coll = db.getCollection("productos");
MongoCursor<Document> cursor = coll.find().iterator();
DefaultTableModel model = Main.tabla();
try {
while (cursor.hasNext()) {
Document doc = cursor.next();
String item = (String) doc.get("ARTICULO"), Tipo = (String) doc.get("TIPO"), Codigo = (String) doc.get("CODIGO");
Object costoc = (Object) doc.get("COSTO"), costov = (Object) doc.get("PRECIO");
Document qty = (Document) doc.get("STOCK");
Object cantidad = (Object) qty.get("ACTUAL"), cantidad1 = (Object) qty.get("MINIMO");
try {
double i = (double) cantidad;
double k = (double) cantidad1;
if (i <= k) {
String Stock = "Reponer";
model.addRow(new Object[]{item, Codigo, Tipo, costoc, costov, Stock});
reponer = false;
} else {
String Stock = "Suficiente";
model.addRow(new Object[]{item, Codigo, Tipo, costoc, costov, Stock});
}
} catch (Exception e) {
String Stock = "Sin Informacion";
model.addRow(new Object[]{item, Codigo, Tipo, costoc, costov, Stock});
}
}
if (reponer == false) {
JOptionPane.showMessageDialog(null, "Atención hay artículos que necesitan reposición", "¡¡ATENCIÓN!!", JOptionPane.WARNING_MESSAGE);
}
table.setModel(model);
color c = new color(5);
//Esre bloque de comentarios hace que sucedan algunos errores y hace que no cargue bien la interfaz
table.getColumnModel().getColumn(5).setCellRenderer(c);
table.getColumnModel().getColumn(0).setPreferredWidth(70);
table.getColumnModel().getColumn(1).setPreferredWidth(20);
table.getColumnModel().getColumn(2).setPreferredWidth(20);
table.getColumnModel().getColumn(3).setPreferredWidth(20);
table.getColumnModel().getColumn(4).setPreferredWidth(40);
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
}
}
private void bBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBuscarActionPerformed
busca();
}//GEN-LAST:event_bBuscarActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
Agregar c = new Agregar();
c.setVisible(true);
dispose(); // TODO add your handling code here:
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void bmostrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bmostrarActionPerformed
llenar(); // TODO add your handling code here:
}//GEN-LAST:event_bmostrarActionPerformed
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
if (!Character.isLetter(evt.getKeyChar())) {
evt.consume();
}
jTextField1.setText(jTextField1.getText().toUpperCase());
busca();
}//GEN-LAST:event_jTextField1KeyReleased
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
System.exit(0);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
this.dispose();
JFrame obj = new Agregar();
obj.setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped
/*String t=jTextField1.getText();
if(t.length()>0)
{
char prim=t.charAt(0);
t=Character.toUpperCase(prim)+t.substring(1,t.length());
jTextField1.setText(t);
}*/// TODO add your handling code here:
}//GEN-LAST:event_jTextField1KeyTyped
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
try {
int row = table.getSelectedRow();
String codigo = table.getValueAt(row, 1).toString();
Actualizar obj = new Actualizar(codigo);
obj.setVisible(true);
this.dispose();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Selecciona una fila de la tabla porfavor", "ERROR !!!!", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
try {
int row = table.getSelectedRow();
String codigo = table.getValueAt(row, 1).toString();
int resp = JOptionPane.showConfirmDialog(null, "¿Seguro que desea eliminar este productos?", "PREGUNTA", JOptionPane.YES_NO_OPTION);
if (JOptionPane.OK_OPTION == resp) {
MongoCollection<Document> collection = db.getCollection("productos");
Document findDocument = new Document("CODIGO", codigo);
collection.findOneAndDelete(findDocument);
JOptionPane.showMessageDialog(null, "Producto eliminado");
llenar();
} else {
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Selecciona una fila de la tabla porfavor", "ERROR !!!!", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
Ventas c = new Ventas();
c.setVisible(true);
dispose();// TODO add your handling code here:
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
Reportes r = new Reportes();
r.setVisible(true);
dispose();
}//GEN-LAST:event_jButton6ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bBuscar;
private javax.swing.JButton bmostrar;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTable table;
// End of variables declaration//GEN-END:variables
}
|
package com.stk123.spring.support.checkpoints;
import com.stk123.spring.dto.checkpoints.CheckResult;
public class ResultTrueOrFalse implements Result {
private final static CheckResult CHECKRESULT_TRUE = new CheckResult("");
private final static CheckResult CHECKRESULT_FALSE = new CheckResult("");
private CheckResult cr;
private String message;
public ResultTrueOrFalse(boolean passed){
cr = passed ? CHECKRESULT_TRUE : CHECKRESULT_FALSE;
}
public ResultTrueOrFalse(boolean passed, String message){
cr = passed ? CHECKRESULT_TRUE : CHECKRESULT_FALSE;
}
@Override
public CheckResult getCheckResult() {
return cr;
}
}
|
package com.union.express.web.rolepermission.dao;
import com.union.express.web.rolepermission.model.RolePermission;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* Created by wq on 2016/10/6.
*/
public interface IRolePermissionRepository extends PagingAndSortingRepository<RolePermission,String>{
}
|
package ru.vyarus.dropwizard.guice.module.context;
import ru.vyarus.dropwizard.guice.module.context.info.BundleItemInfo;
import ru.vyarus.dropwizard.guice.module.context.info.ExtensionItemInfo;
import ru.vyarus.dropwizard.guice.module.context.info.ItemInfo;
import ru.vyarus.dropwizard.guice.module.context.info.ModuleItemInfo;
import ru.vyarus.dropwizard.guice.module.context.info.sign.DisableSupport;
import ru.vyarus.dropwizard.guice.module.context.info.sign.ScanSupport;
import ru.vyarus.dropwizard.guice.module.installer.FeatureInstaller;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
* Common filters for configuration information filtering in
* {@link ConfigurationInfo#getItems(ConfigItem, Predicate)} and
* {@link ConfigurationInfo#getItems(Predicate)}.
* Use {@link Predicate#and(Predicate)}, {@link Predicate#or(Predicate)} and {@link Predicate#negate()}
* to reuse default filters.
*
* @author Vyacheslav Rusakov
* @since 06.07.2016
*/
public final class Filters {
private Filters() {
}
// --------------------------------------------------------------------------- GENERIC
/**
* Filter for enabled items. Not all items support disable ({@link DisableSupport}).
* Items not supporting disable considered enabled (so it's safe to apply filter for
* all items).
*
* @param <T> expected info container type (if used within single configuration type)
* @return enabled items filter
*/
public static <T extends ItemInfo> Predicate<T> enabled() {
return input -> !(input instanceof DisableSupport) || ((DisableSupport) input).isEnabled();
}
/**
* Filter for items disabled in specified scope. Not all items support disable ({@link DisableSupport}).
* Items not supporting disable considered enabled (so it's safe to apply filter for
* all items).
*
* @param scope target scope
* @param <T> expected info container type (if used within single configuration type)
* @return items disabled in scope filter
*/
public static <T extends ItemInfo> Predicate<T> disabledBy(final Class<?> scope) {
return input -> input instanceof DisableSupport && ((DisableSupport) input).getDisabledBy().contains(scope);
}
/**
* Filter for items registered with classpath scan. Not all items support classpath scan
* {@link ScanSupport}. Items not supporting scan are considered not resolved by scan
* (so it's safe to apply filter for all items).
*
* @param <T> expected info container type (if used within single configuration type)
* @return items from classpath scan filter
*/
public static <T extends ItemInfo> Predicate<T> fromScan() {
return input -> input instanceof ScanSupport && ((ScanSupport) input).isFromScan();
}
/**
* Shortcut for {@link #registrationScope(Class)} for special scopes (like classpath scan, bundles lookup etc).
*
* @param specialScope special scope type
* @param <T> expected info container type (if used within single configuration type)
* @return items registered in specified context filter
*/
public static <T extends ItemInfo> Predicate<T> registrationScope(final ConfigScope specialScope) {
return registrationScope(specialScope.getType());
}
/**
* Filter for items registered by specified context. Context class could be
* {@link io.dropwizard.Application}, {@link ru.vyarus.dropwizard.guice.module.installer.scanner.ClasspathScanner},
* {@link ru.vyarus.dropwizard.guice.bundle.GuiceyBundleLookup} and
* classes implementing {@link ru.vyarus.dropwizard.guice.module.installer.bundle.GuiceyBundle}.
* Safe to apply filter for all items.
* <p>
* Note: counts only actual registration, ignoring duplicate (rejected) registrations
* (see {@link #registeredBy(Class)} for filter counting all registrations).
*
* @param scope scope class
* @param <T> expected info container type (if used within single configuration type)
* @return items registered in specified context filter
* @see ConfigScope for the list of all special scopes
*/
public static <T extends ItemInfo> Predicate<T> registrationScope(final Class<?> scope) {
return input -> input.getRegistrationScopes().contains(scope);
}
/**
* Shortcut for {@link #registeredBy(Class)} for special scopes (like classpath scan, bundles lookup etc).
*
* @param specialScope special scope type
* @param <T> expected info container type (if used within single configuration type)
* @return items registered in specified context filter
*/
public static <T extends ItemInfo> Predicate<T> registeredBy(final ConfigScope specialScope) {
return registeredBy(specialScope.getType());
}
/**
* In contrast to {@link #registrationScope(Class)} this filter returns item for all scopes registered it
* (not only for first registered scope).
*
* @param type context class
* @param <T> expected info container type (if used within single configuration type)
* @return items registered in specified context filter
* @see ConfigScope for the list of all special scopes
*/
public static <T extends ItemInfo> Predicate<T> registeredBy(final Class<?> type) {
return input -> input.getRegisteredBy().contains(type);
}
/**
* Filter used for multi-type searches to filter out item types.
* In order to filter out only one type, may be used in conjunction with
* {@link Predicate#negate()}.
*
* @param types item types to match
* @return items of type filter
*/
public static Predicate<ItemInfo> type(final ConfigItem... types) {
final List<ConfigItem> target = Arrays.asList(types);
return input -> target.contains(input.getItemType());
}
// --------------------------------------------------------------------------- BUNDLES
/**
* Filter for bundles resolved by lookup mechanism. Use only for {@link ConfigItem#Bundle} items.
*
* @return bundles resolved by lookup filter
*/
public static Predicate<BundleItemInfo> lookupBundles() {
return BundleItemInfo::isFromLookup;
}
/**
* Filter for transitive bundles: bundles registered only by other bundles (and never directly).
*
* @return transitive bundled filter
*/
public static Predicate<BundleItemInfo> transitiveBundles() {
return BundleItemInfo::isTransitive;
}
// --------------------------------------------------------------------------- EXTENSIONS
/**
* Filter for extensions installed by specified installer. Use only for {@link ConfigItem#Extension} items.
*
* @param type installer class
* @return extensions installed by specified installer filter
*/
public static Predicate<ExtensionItemInfo> installedBy(final Class<? extends FeatureInstaller> type) {
return input -> type.equals(input.getInstalledBy());
}
// --------------------------------------------------------------------------- MODULES
/**
* Filter for overriding modules. Use only for {@link ConfigItem#Module} items.
*
* @return overriding modules filter
*/
public static Predicate<ModuleItemInfo> overridingModule() {
return ModuleItemInfo::isOverriding;
}
}
|
package adminTest.subscriptionTest;
import com.codeborne.selenide.Selenide;
import io.qameta.allure.Severity;
import io.qameta.allure.SeverityLevel;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import portal.admin.order_subscription_page.new_subscriptions_page.NewSubscriptionFinishPage;
import portal.admin.order_subscription_page.new_subscriptions_page.NewSubscriptionPage;
import portal.admin.order_subscription_page.new_subscriptions_page.NewSubscriptionPageOne;
import portal.admin.order_subscription_page.subscription_profile_pages.HeaderSubscriptionRequestPage;
import portal.admin.order_subscription_page.subscription_profile_pages.SubscriptionProfilePage;
import portal.admin.order_subscription_page.subscription_profile_pages.SubscriptionRequestPage;
import portal.annotations.Admin;
import portal.annotations.TestType;
import portal.data.EmailMessage;
import portal.data.LinkProvider;
import portal.data.SubscriptionData;
import portal.data.UserData;
import portal.data.enumdata.component.*;
import portal.email.EmailSteps;
import portal.listener.BaseTestExtension;
import portal.providers.DataProvider;
import portal.providers.MainPageProvider;
import portal.providers.SubscriptionPageFactory;
import portal.utils.DateTime;
import portal.utils.Status;
import java.util.Map;
import static com.codeborne.selenide.Selenide.switchTo;
import static portal.data.enumdata.ModeCharge.FACT;
import static portal.data.enumdata.ModeCharge.FIX;
import static portal.data.enumdata.Status.NEW;
import static portal.data.enumdata.Status.TEST;
import static portal.data.enumdata.SubscriptionIdName.*;
import static portal.data.enumdata.SubscriptionName.*;
import static portal.data.enumdata.TabName.REQUESTS;
import static portal.data.enumdata.TypeSubscription.TYPE_COMMERCIAL;
import static portal.data.enumdata.TypeSubscription.TYPE_TESTING;
import static portal.data.enumdata.component.BackupComponent.*;
import static portal.data.enumdata.component.CloudStorageComponent.STORAGE;
import static portal.data.enumdata.component.InternetComponent.INTERNET_IP;
import static portal.data.enumdata.component.InternetComponent.INTERNET_SPEED;
import static portal.data.enumdata.component.MicrosoftComponent.*;
import static portal.data.enumdata.component.OpenstackComponent.*;
import static portal.data.enumdata.component.VMwareComponent.*;
@Admin.newSubscription
@ExtendWith(BaseTestExtension.class)
public class AdminNewSubscriptionTest {
private final DataProvider dataProvider = new DataProvider();
private final SubscriptionData subscriptionData = dataProvider.subscriptionData();
private final LinkProvider linkProvider = dataProvider.linkProvider();
private final UserData userData = dataProvider.userData();
private final EmailMessage emailMessage = dataProvider.emailMessage();
private final EmailSteps emailSteps = new EmailSteps();
private final Status status = new Status();
private final DateTime dateTime = new DateTime();
private final MainPageProvider mainPageProvider = new MainPageProvider();
private final NewSubscriptionPageOne newSubscriptionPageOne = new NewSubscriptionPageOne();
private final SubscriptionPageFactory subscriptionPageFactory = new SubscriptionPageFactory();
private final NewSubscriptionPage newVMwareProtectPage = subscriptionPageFactory.getNewSubscriptionPage(PROTECT);
private final NewSubscriptionPage newVMware3GHzPage = subscriptionPageFactory.getNewSubscriptionPage(GHZ);
private final NewSubscriptionPage newVMwareClosePage = subscriptionPageFactory.getNewSubscriptionPage(CLOSE);
private final NewSubscriptionPage newVMwareIXPage = subscriptionPageFactory.getNewSubscriptionPage(IX);
private final NewSubscriptionPage newOpenstackPage = subscriptionPageFactory.getNewSubscriptionPage(OPENSTACK_CSS);
private final NewSubscriptionPage newInternetPage = subscriptionPageFactory.getNewSubscriptionPage(INTERNET_CSS);
private final NewSubscriptionPage newMicrosoftPage = subscriptionPageFactory.getNewSubscriptionPage(MICROSOFT_CSS);
private final NewSubscriptionPage newBackupPage = subscriptionPageFactory.getNewSubscriptionPage(BACKUP_CSS);
private final NewSubscriptionPage newCloudStoragePage = subscriptionPageFactory.getNewSubscriptionPage(CLOUD_STORAGE_CSS);
private final SubscriptionRequestPage vmwareRequestProtectPage = subscriptionPageFactory.getRequestPage(PROTECT);
private final SubscriptionRequestPage vMware3GHzRequestPage = subscriptionPageFactory.getRequestPage(GHZ);
private final SubscriptionRequestPage vMwareCloseRequestPage = subscriptionPageFactory.getRequestPage(CLOSE);
private final SubscriptionRequestPage vMwareIXRequestPage = subscriptionPageFactory.getRequestPage(IX);
private final SubscriptionRequestPage openstackRequestPage = subscriptionPageFactory.getRequestPage(OPENSTACK_CSS);
private final SubscriptionRequestPage backupRequestPage = subscriptionPageFactory.getRequestPage(BACKUP_CSS);
private final SubscriptionRequestPage internetRequestPage = subscriptionPageFactory.getRequestPage(INTERNET_CSS);
private final SubscriptionRequestPage microsoftRequestPage = subscriptionPageFactory.getRequestPage(MICROSOFT_CSS);
private final SubscriptionRequestPage cloudStorageRequestPage = subscriptionPageFactory.getRequestPage(CLOUD_STORAGE_CSS);
private final NewSubscriptionFinishPage newSubscriptionFinishPage = new NewSubscriptionFinishPage();
private final SubscriptionProfilePage subscriptionProfilePage = new SubscriptionProfilePage();
private final HeaderSubscriptionRequestPage headerSubscriptionRequestPage = new HeaderSubscriptionRequestPage();
private final String date = dateTime.getTodayDate();
private String time;
private final Map<Enum, String> vmwareData = dataProvider.getComponentsValue(VMwareComponent.values());
private final Map<Enum, String> openstackData = dataProvider.getComponentsValue(OpenstackComponent.values());
private final Map<Enum, String> internetData = dataProvider.getComponentsValue(InternetComponent.values());
private final Map<Enum, String> backupData = dataProvider.getComponentsValue(BackupComponent.values());
private final Map<Enum, String> microsoftData = dataProvider.getComponentsValue(MicrosoftComponent.values());
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ VMware защищенная коммерческая")
@TestType.e2e
void createVMwareCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmwareProtectName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(VMWARE_PROTECT.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareProtectPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFact())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(USB, vmwareData.get(USB))
.setValue(NOTE, VMWARE_PROTECT.getCommercialNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmwareProtectName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_PROTECT.getOrderNote())
.checkTariffType(FACT)
.checkStartDate(date, time);
vmwareRequestProtectPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF))
.checkValue(USB, vmwareData.get(USB));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.CRITICAL)
@DisplayName("Заказ VMware защищенная коммерческая + Резервное копирование + Резервированный доступ в Интернет + Программы Microsoft")
@TestType.e2e
void createVMwareCommercialPlus() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerCheckEmail())
.setSubscription(subscriptionData.vmwareProtectName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setPaperOrder(VMWARE_PROTECT.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareProtectPage
.setValue(SSD, vmwareData.get(SSD))
.setValue(NOTE, VMWARE_PROTECT.getCommercialNote());
newInternetPage
.setValue(INTERNET_SPEED, internetData.get(INTERNET_SPEED))
.setValue(INTERNET_IP, internetData.get(INTERNET_IP))
.setValue(NOTE, INTERNET.getCommercialNote());
newBackupPage
.setValue(BACKUP_VOLUME, backupData.get(BACKUP_VOLUME))
.setValue(VM_COUNT, backupData.get(VM_COUNT))
.setValue(TRAFFIC_MIN, backupData.get(TRAFFIC_MIN))
.setValue(TRAFFIC_SPEED, backupData.get(TRAFFIC_SPEED))
.clickOn(CLOUD_PLACEMENT, subscriptionData.setCloud())
.setValue(NOTE, BACKUP.getCommercialNote());
newVMwareProtectPage.checkBox(subscriptionData.checkBoxMicrosoft());
newMicrosoftPage
.setValue(PROJECT_SERVER, microsoftData.get(PROJECT_SERVER))
.setValue(NOTE, MICROSOFT.getCommercialNote());
newVMwareProtectPage.clickButton();
newSubscriptionFinishPage
.checkNumberOfSubscription(4)
.checkNameOfSubscription(0, subscriptionData.vmwareProtectName())
.checkNameOfSubscription(1, subscriptionData.backupName())
.checkNameOfSubscription(2, subscriptionData.accessInternetName())
.checkNameOfSubscription(3, subscriptionData.microsoftName());
emailSteps.checkTextOfMessageAndDoRead(
emailMessage.newSubscriptionEmailSubject(),
subscriptionData.vmwareProtectName(),
subscriptionData.backupName(),
subscriptionData.accessInternetName(),
subscriptionData.microsoftName(),
VMWARE_PROTECT.getOrderNote(),
userData.emailSalesManagerForEmail());
//todo добавить клик на номер бумажного заказа
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ VMware защищенная тестовая")
@TestType.e2e
void createVMwareTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmwareProtectName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(VMWARE_PROTECT.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareProtectPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFix())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(USB, vmwareData.get(USB))
.setValue(NOTE, VMWARE_PROTECT.getTestNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmwareProtectName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_PROTECT.getOrderNote())
.checkTariffType(FIX);
vmwareRequestProtectPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF))
.checkValue(USB, vmwareData.get(USB));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ VMware 3Ггц коммерческая")
@TestType.e2e
void createVMware3GHzCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmware3GHzName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(VMWARE_3GHZ.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMware3GHzPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFact())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(USB, vmwareData.get(USB))
.setValue(NOTE, VMWARE_3GHZ.getCommercialNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmware3GHzName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_3GHZ.getOrderNote())
.checkTariffType(FACT)
.checkStartDate(date, time);
vMware3GHzRequestPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF))
.checkValue(USB, vmwareData.get(USB));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ VMware 3Ггц тестовая")
@TestType.e2e
void createVMware3GHzTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmware3GHzName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(VMWARE_3GHZ.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMware3GHzPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFix())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(USB, vmwareData.get(USB))
.setValue(NOTE, VMWARE_3GHZ.getTestNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmware3GHzName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_3GHZ.getOrderNote())
.checkTariffType(FIX);
vMware3GHzRequestPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF))
.checkValue(USB, vmwareData.get(USB));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ VMware IX коммерческая")
@TestType.e2e
void createVMwareIXCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmwareIXName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(VMWARE_IX.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareIXPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFact())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(USB, vmwareData.get(USB))
.setValue(NOTE, VMWARE_IX.getCommercialNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmwareIXName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_IX.getOrderNote())
.checkTariffType(FACT)
.checkStartDate(date, time);
vMwareIXRequestPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF))
.checkValue(USB, vmwareData.get(USB));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ VMware IX тестовая")
@TestType.e2e
void createVMwareIXTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmwareIXName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(VMWARE_IX.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareIXPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFix())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(USB, vmwareData.get(USB))
.setValue(NOTE,VMWARE_IX.getTestNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmwareIXName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_IX.getOrderNote())
.checkTariffType(FIX);
vMwareIXRequestPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF))
.checkValue(USB, vmwareData.get(USB));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.CRITICAL)
@DisplayName("Заказ VMware закрытая коммерческая")
@TestType.e2e
void createVMwareCloseCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmwareCloseName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(VMWARE_CLOSE.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareClosePage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFact())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(NOTE, VMWARE_CLOSE.getCommercialNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmwareCloseName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_CLOSE.getOrderNote())
.checkTariffType(FACT)
.checkStartDate(date, time);
vMwareCloseRequestPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.CRITICAL)
@DisplayName("Заказ VMware закрытая тестовая")
@TestType.e2e
void createVMwareCloseTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.vmwareCloseName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(VMWARE_CLOSE.getOrderNote())
.clickButton();
//*************Step 2**********************
newVMwareClosePage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFix())
.setValue(VCPU, vmwareData.get(VCPU))
.setValue(VRAM, vmwareData.get(VRAM))
.setValue(HDD_7K, vmwareData.get(HDD_7K))
.setValue(HDD_10K, vmwareData.get(HDD_10K))
.setValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.setValue(SSD, vmwareData.get(SSD))
.setValue(SSD_AF, vmwareData.get(SSD_AF))
.setValue(NOTE, VMWARE_CLOSE.getTestNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.vmwareCloseName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(VMWARE_CLOSE.getOrderNote())
.checkTariffType(FIX);
vMwareCloseRequestPage
.checkValue(VCPU, vmwareData.get(VCPU))
.checkValue(VRAM, vmwareData.get(VRAM))
.checkValue(HDD_7K, vmwareData.get(HDD_7K))
.checkValue(HDD_10K, vmwareData.get(HDD_10K))
.checkValue(HDD_HYBRID, vmwareData.get(HDD_HYBRID))
.checkValue(SSD, vmwareData.get(SSD))
.checkValue(SSD_AF, vmwareData.get(SSD_AF));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.CRITICAL)
@DisplayName("Заказ Openstack V3, коммерческая")
@TestType.e2e
void createOpenstackCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.openstackName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(OPENSTACK.getOrderNote())
.clickButton();
//*************Step 2**********************
newOpenstackPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFact())
.setValue(OPENSTACK_VCPU, openstackData.get(OPENSTACK_VCPU))
.setValue(OPENSTACK_VRAM, openstackData.get(OPENSTACK_VRAM))
.setValue(OPENSTACK_HDD_7K, openstackData.get(OPENSTACK_HDD_7K))
.setValue(OPENSTACK_HDD_10K, openstackData.get(OPENSTACK_HDD_10K))
.setValue(OPENSTACK_SSD_SDS, openstackData.get(OPENSTACK_SSD_SDS))
.setValue(NOTE, OPENSTACK.getCommercialNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.openstackName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(OPENSTACK.getOrderNote())
.checkTariffType(FACT)
.checkStartDate(date, time);
openstackRequestPage
.checkValue(OPENSTACK_VCPU, openstackData.get(OPENSTACK_VCPU))
.checkValue(OPENSTACK_VRAM, openstackData.get(OPENSTACK_VRAM))
.checkValue(OPENSTACK_HDD_7K, openstackData.get(OPENSTACK_HDD_7K))
.checkValue(OPENSTACK_HDD_10K, openstackData.get(OPENSTACK_HDD_10K))
.checkValue(OPENSTACK_SSD_SDS, openstackData.get(OPENSTACK_SSD_SDS));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.CRITICAL)
@DisplayName("Заказ Openstack V3, тестовая")
@TestType.e2e
void createOpenstackTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.openstackName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(OPENSTACK.getOrderNote())
.clickButton();
//*************Step 2**********************
newOpenstackPage
.clickOn(SCHEME_PRICING, subscriptionData.tariffFact())
.setValue(OPENSTACK_VCPU, openstackData.get(OPENSTACK_VCPU))
.setValue(OPENSTACK_VRAM, openstackData.get(OPENSTACK_VRAM))
.setValue(OPENSTACK_HDD_7K, openstackData.get(OPENSTACK_HDD_7K))
.setValue(OPENSTACK_HDD_10K, openstackData.get(OPENSTACK_HDD_10K))
.setValue(OPENSTACK_SSD_SDS, openstackData.get(OPENSTACK_SSD_SDS))
.setValue(NOTE, OPENSTACK.getTestNote())
.checkBox(subscriptionData.checkBoxBackup())
.checkBox(subscriptionData.checkBoxInet())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.openstackName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(OPENSTACK.getOrderNote())
.checkTariffType(FACT);
openstackRequestPage
.checkValue(OPENSTACK_VCPU, openstackData.get(OPENSTACK_VCPU))
.checkValue(OPENSTACK_VRAM, openstackData.get(OPENSTACK_VRAM))
.checkValue(OPENSTACK_HDD_7K, openstackData.get(OPENSTACK_HDD_7K))
.checkValue(OPENSTACK_HDD_10K, openstackData.get(OPENSTACK_HDD_10K))
.checkValue(OPENSTACK_SSD_SDS, openstackData.get(OPENSTACK_SSD_SDS));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ резервное копирование, коммерческая")
@TestType.e2e
void createBackupCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.backupName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(BACKUP.getOrderNote())
.clickButton();
//*************Step 2**********************
newBackupPage
.setValue(BACKUP_VOLUME, backupData.get(BACKUP_VOLUME))
.setValue(VM_COUNT, backupData.get(VM_COUNT))
.setValue(TRAFFIC_MIN, backupData.get(TRAFFIC_MIN))
.setValue(TRAFFIC_SPEED, backupData.get(TRAFFIC_SPEED))
.clickOn(CLOUD_PLACEMENT, subscriptionData.setCloud())
.setValue(NOTE, BACKUP.getCommercialNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.backupName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(BACKUP.getOrderNote())
.checkStartDate(date, time);
backupRequestPage
.checkValue(BACKUP_VOLUME, backupData.get(BACKUP_VOLUME))
.checkValue(VM_COUNT, backupData.get(VM_COUNT))
.checkValue(TRAFFIC_MIN, backupData.get(TRAFFIC_MIN))
.checkValue(TRAFFIC_SPEED, backupData.get(TRAFFIC_SPEED))
.checkValue(CLOUD_PLACEMENT, subscriptionData.setCloud());
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ резервное копирование, тестовая")
@TestType.e2e
void createBackupTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.backupName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(BACKUP.getOrderNote())
.clickButton();
//*************Step 2**********************
newBackupPage
.setValue(BACKUP_VOLUME, backupData.get(BACKUP_VOLUME))
.setValue(VM_COUNT, backupData.get(VM_COUNT))
.setValue(TRAFFIC_MIN, backupData.get(TRAFFIC_MIN))
.setValue(TRAFFIC_SPEED, backupData.get(TRAFFIC_SPEED))
.clickOn(CLOUD_PLACEMENT, subscriptionData.setCloud())
.setValue(NOTE, BACKUP.getTestNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.backupName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage.checkPaperOrder(BACKUP.getOrderNote());
backupRequestPage
.checkValue(BACKUP_VOLUME, backupData.get(BACKUP_VOLUME))
.checkValue(VM_COUNT, backupData.get(VM_COUNT))
.checkValue(TRAFFIC_MIN, backupData.get(TRAFFIC_MIN))
.checkValue(TRAFFIC_SPEED, backupData.get(TRAFFIC_SPEED))
.checkValue(CLOUD_PLACEMENT, subscriptionData.setCloud());
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ резервированный доступ в интернет, коммерческая")
@TestType.e2e
void createAccessInternetCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.accessInternetName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(INTERNET.getOrderNote())
.clickButton();
//*************Step 2**********************
newInternetPage
.setValue(INTERNET_SPEED, internetData.get(INTERNET_SPEED))
.setValue(INTERNET_IP, internetData.get(INTERNET_IP))
.setValue(NOTE, INTERNET.getCommercialNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.accessInternetName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkStartDate(date, time)
.checkPaperOrder(INTERNET.getOrderNote());
internetRequestPage
.checkValue(INTERNET_SPEED, internetData.get(INTERNET_SPEED))
.checkValue(INTERNET_IP, internetData.get(INTERNET_IP));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.BLOCKER)
@DisplayName("Заказ резервированный доступ в интернет, тестовая")
@TestType.e2e
void createAccessInternetTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.accessInternetName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(INTERNET.getOrderNote())
.clickButton();
//*************Step 2**********************
newInternetPage
.setValue(INTERNET_SPEED, internetData.get(INTERNET_SPEED))
.setValue(INTERNET_IP, internetData.get(INTERNET_IP))
.setValue(NOTE, INTERNET.getTestNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.accessInternetName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage.checkPaperOrder(INTERNET.getOrderNote());
internetRequestPage
.checkValue(INTERNET_SPEED, internetData.get(INTERNET_SPEED))
.checkValue(INTERNET_IP, internetData.get(INTERNET_IP));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.NORMAL)
@DisplayName("Заказ Microsoft, коммерческая")
@TestType.e2e
void createMicrosoftCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.microsoftName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(MICROSOFT.getOrderNote())
.clickButton();
//*************Step 2**********************
newMicrosoftPage
.setValue(VISIO_PROFESSIONAL, microsoftData.get(VISIO_PROFESSIONAL))
.setValue(SHAREPOINT_SERVER_STANDARD, microsoftData.get(SHAREPOINT_SERVER_STANDARD))
.setValue(SERVER_SUITE_STANDARD, microsoftData.get(SERVER_SUITE_STANDARD))
.setValue(SQL_SERVER_STANDARD_CORE, microsoftData.get(SQL_SERVER_STANDARD_CORE))
.setValue(EXCHANGE_BASIC, microsoftData.get(EXCHANGE_BASIC))
.setValue(EXCHANGE_ENTERPRISE_PLUS, microsoftData.get(EXCHANGE_ENTERPRISE_PLUS))
.setValue(VISIO_STANDARD, microsoftData.get(VISIO_STANDARD))
.setValue(PROJECT_PROFESSIONAL, microsoftData.get(PROJECT_PROFESSIONAL))
.setValue(WINDOWS_SERVER_DATA_CENTER, microsoftData.get(WINDOWS_SERVER_DATA_CENTER))
.setValue(SQL_SERVER_ENTERPRISE, microsoftData.get(SQL_SERVER_ENTERPRISE))
.setValue(OFFICE_STANDARD, microsoftData.get(OFFICE_STANDARD))
.setValue(EXCHANGE_ENTERPRISE, microsoftData.get(EXCHANGE_ENTERPRISE))
.setValue(OFFICE_PROFESSIONAL_PLUS, microsoftData.get(OFFICE_PROFESSIONAL_PLUS))
.setValue(PROJECT_SERVER, microsoftData.get(PROJECT_SERVER))
.setValue(WINDOWS_SERVER_STANDARD, microsoftData.get(WINDOWS_SERVER_STANDARD))
.setValue(REMOTE_DESKTOP_SERVICE, microsoftData.get(REMOTE_DESKTOP_SERVICE))
.setValue(SQL_SERVER_STANDARD, microsoftData.get(SQL_SERVER_STANDARD))
.setValue(EXCHANGE_STANDARD_PLUS, microsoftData.get(EXCHANGE_STANDARD_PLUS))
.setValue(PROJECT, microsoftData.get(PROJECT))
.setValue(SHAREPOINT_SERVER_PROFESSIONAL, microsoftData.get(SHAREPOINT_SERVER_PROFESSIONAL))
.setValue(SERVER_SUITE_DATA_CENTER, microsoftData.get(SERVER_SUITE_DATA_CENTER))
.setValue(SQL_SERVER_WEB, microsoftData.get(SQL_SERVER_WEB))
.setValue(EXCHANGE_STANDARD, microsoftData.get(EXCHANGE_STANDARD))
.setValue(WINDOWS_SERVER_STANDARD_VM, microsoftData.get(WINDOWS_SERVER_STANDARD_VM))
.setValue(RIGHTS_MANAGEMENT_SERVICES, microsoftData.get(RIGHTS_MANAGEMENT_SERVICES))
.setValue(OFFICE_MULTI_LANGUAGE, microsoftData.get(OFFICE_MULTI_LANGUAGE))
.setValue(VISUAL_STUDIO, microsoftData.get(VISUAL_STUDIO))
.setValue(VISUAL_STUDIO_BASIC, microsoftData.get(VISUAL_STUDIO_BASIC))
.setValue(VISUAL_STUDIO_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_PROFESSIONAL))
.setValue(VISUAL_STUDIO_TEST_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_TEST_PROFESSIONAL))
.setValue(VISUAL_STUDIO_ENTERPRISE, microsoftData.get(VISUAL_STUDIO_ENTERPRISE))
.setValue(SHAREPOINT_SERVER, microsoftData.get(SHAREPOINT_SERVER))
.setValue(SHAREPOINT_HOSTING, microsoftData.get(SHAREPOINT_HOSTING))
.setValue(NOTE, MICROSOFT.getCommercialNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.microsoftName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(MICROSOFT.getOrderNote())
.checkTariffType(FIX)
.checkStartDate(date, time);
microsoftRequestPage
.checkValue(VISIO_PROFESSIONAL, microsoftData.get(VISIO_PROFESSIONAL))
.checkValue(SHAREPOINT_SERVER_STANDARD, microsoftData.get(SHAREPOINT_SERVER_STANDARD))
.checkValue(SERVER_SUITE_STANDARD, microsoftData.get(SERVER_SUITE_STANDARD))
.checkValue(SQL_SERVER_STANDARD_CORE, microsoftData.get(SQL_SERVER_STANDARD_CORE))
.checkValue(EXCHANGE_BASIC, microsoftData.get(EXCHANGE_BASIC))
.checkValue(EXCHANGE_ENTERPRISE_PLUS, microsoftData.get(EXCHANGE_ENTERPRISE_PLUS))
.checkValue(VISIO_STANDARD, microsoftData.get(VISIO_STANDARD))
.checkValue(PROJECT_PROFESSIONAL, microsoftData.get(PROJECT_PROFESSIONAL))
.checkValue(WINDOWS_SERVER_DATA_CENTER, microsoftData.get(WINDOWS_SERVER_DATA_CENTER))
.checkValue(SQL_SERVER_ENTERPRISE, microsoftData.get(SQL_SERVER_ENTERPRISE))
.checkValue(OFFICE_STANDARD, microsoftData.get(OFFICE_STANDARD))
.checkValue(EXCHANGE_ENTERPRISE, microsoftData.get(EXCHANGE_ENTERPRISE))
.checkValue(OFFICE_PROFESSIONAL_PLUS, microsoftData.get(OFFICE_PROFESSIONAL_PLUS))
.checkValue(PROJECT_SERVER, microsoftData.get(PROJECT_SERVER))
.checkValue(WINDOWS_SERVER_STANDARD, microsoftData.get(WINDOWS_SERVER_STANDARD))
.checkValue(REMOTE_DESKTOP_SERVICE, microsoftData.get(REMOTE_DESKTOP_SERVICE))
.checkValue(SQL_SERVER_STANDARD, microsoftData.get(SQL_SERVER_STANDARD))
.checkValue(EXCHANGE_STANDARD_PLUS, microsoftData.get(EXCHANGE_STANDARD_PLUS))
.checkValue(PROJECT, microsoftData.get(PROJECT))
.checkValue(SHAREPOINT_SERVER_PROFESSIONAL, microsoftData.get(SHAREPOINT_SERVER_PROFESSIONAL))
.checkValue(SERVER_SUITE_DATA_CENTER, microsoftData.get(SERVER_SUITE_DATA_CENTER))
.checkValue(SQL_SERVER_WEB, microsoftData.get(SQL_SERVER_WEB))
.checkValue(EXCHANGE_STANDARD, microsoftData.get(EXCHANGE_STANDARD))
.checkValue(WINDOWS_SERVER_STANDARD_VM, microsoftData.get(WINDOWS_SERVER_STANDARD_VM))
.checkValue(RIGHTS_MANAGEMENT_SERVICES, microsoftData.get(RIGHTS_MANAGEMENT_SERVICES))
.checkValue(OFFICE_MULTI_LANGUAGE, microsoftData.get(OFFICE_MULTI_LANGUAGE))
.checkValue(VISUAL_STUDIO, microsoftData.get(VISUAL_STUDIO))
.checkValue(VISUAL_STUDIO_BASIC, microsoftData.get(VISUAL_STUDIO_BASIC))
.checkValue(VISUAL_STUDIO_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_PROFESSIONAL))
.checkValue(VISUAL_STUDIO_TEST_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_TEST_PROFESSIONAL))
.checkValue(VISUAL_STUDIO_ENTERPRISE, microsoftData.get(VISUAL_STUDIO_ENTERPRISE))
.checkValue(SHAREPOINT_SERVER, microsoftData.get(SHAREPOINT_SERVER))
.checkValue(SHAREPOINT_HOSTING, microsoftData.get(SHAREPOINT_HOSTING));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.NORMAL)
@DisplayName("Заказ Microsoft, тестовая")
@TestType.e2e
void createMicrosoftTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.microsoftName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(MICROSOFT.getOrderNote())
.clickButton();
//*************Step 2**********************
newMicrosoftPage
.setValue(VISIO_PROFESSIONAL, microsoftData.get(VISIO_PROFESSIONAL))
.setValue(SHAREPOINT_SERVER_STANDARD, microsoftData.get(SHAREPOINT_SERVER_STANDARD))
.setValue(SERVER_SUITE_STANDARD, microsoftData.get(SERVER_SUITE_STANDARD))
.setValue(SQL_SERVER_STANDARD_CORE, microsoftData.get(SQL_SERVER_STANDARD_CORE))
.setValue(EXCHANGE_BASIC, microsoftData.get(EXCHANGE_BASIC))
.setValue(EXCHANGE_ENTERPRISE_PLUS, microsoftData.get(EXCHANGE_ENTERPRISE_PLUS))
.setValue(VISIO_STANDARD, microsoftData.get(VISIO_STANDARD))
.setValue(PROJECT_PROFESSIONAL, microsoftData.get(PROJECT_PROFESSIONAL))
.setValue(WINDOWS_SERVER_DATA_CENTER, microsoftData.get(WINDOWS_SERVER_DATA_CENTER))
.setValue(SQL_SERVER_ENTERPRISE, microsoftData.get(SQL_SERVER_ENTERPRISE))
.setValue(OFFICE_STANDARD, microsoftData.get(OFFICE_STANDARD))
.setValue(EXCHANGE_ENTERPRISE, microsoftData.get(EXCHANGE_ENTERPRISE))
.setValue(OFFICE_PROFESSIONAL_PLUS, microsoftData.get(OFFICE_PROFESSIONAL_PLUS))
.setValue(PROJECT_SERVER, microsoftData.get(PROJECT_SERVER))
.setValue(WINDOWS_SERVER_STANDARD, microsoftData.get(WINDOWS_SERVER_STANDARD))
.setValue(REMOTE_DESKTOP_SERVICE, microsoftData.get(REMOTE_DESKTOP_SERVICE))
.setValue(SQL_SERVER_STANDARD, microsoftData.get(SQL_SERVER_STANDARD))
.setValue(EXCHANGE_STANDARD_PLUS, microsoftData.get(EXCHANGE_STANDARD_PLUS))
.setValue(PROJECT, microsoftData.get(PROJECT))
.setValue(SHAREPOINT_SERVER_PROFESSIONAL, microsoftData.get(SHAREPOINT_SERVER_PROFESSIONAL))
.setValue(SERVER_SUITE_DATA_CENTER, microsoftData.get(SERVER_SUITE_DATA_CENTER))
.setValue(SQL_SERVER_WEB, microsoftData.get(SQL_SERVER_WEB))
.setValue(EXCHANGE_STANDARD, microsoftData.get(EXCHANGE_STANDARD))
.setValue(WINDOWS_SERVER_STANDARD_VM, microsoftData.get(WINDOWS_SERVER_STANDARD_VM))
.setValue(RIGHTS_MANAGEMENT_SERVICES, microsoftData.get(RIGHTS_MANAGEMENT_SERVICES))
.setValue(OFFICE_MULTI_LANGUAGE, microsoftData.get(OFFICE_MULTI_LANGUAGE))
.setValue(VISUAL_STUDIO, microsoftData.get(VISUAL_STUDIO))
.setValue(VISUAL_STUDIO_BASIC, microsoftData.get(VISUAL_STUDIO_BASIC))
.setValue(VISUAL_STUDIO_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_PROFESSIONAL))
.setValue(VISUAL_STUDIO_TEST_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_TEST_PROFESSIONAL))
.setValue(VISUAL_STUDIO_ENTERPRISE, microsoftData.get(VISUAL_STUDIO_ENTERPRISE))
.setValue(SHAREPOINT_SERVER, microsoftData.get(SHAREPOINT_SERVER))
.setValue(SHAREPOINT_HOSTING, microsoftData.get(SHAREPOINT_HOSTING))
.setValue(NOTE, MICROSOFT.getTestNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.microsoftName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(MICROSOFT.getOrderNote())
.checkTariffType(FIX);
microsoftRequestPage
.checkValue(VISIO_PROFESSIONAL, microsoftData.get(VISIO_PROFESSIONAL))
.checkValue(SHAREPOINT_SERVER_STANDARD, microsoftData.get(SHAREPOINT_SERVER_STANDARD))
.checkValue(SERVER_SUITE_STANDARD, microsoftData.get(SERVER_SUITE_STANDARD))
.checkValue(SQL_SERVER_STANDARD_CORE, microsoftData.get(SQL_SERVER_STANDARD_CORE))
.checkValue(EXCHANGE_BASIC, microsoftData.get(EXCHANGE_BASIC))
.checkValue(EXCHANGE_ENTERPRISE_PLUS, microsoftData.get(EXCHANGE_ENTERPRISE_PLUS))
.checkValue(VISIO_STANDARD, microsoftData.get(VISIO_STANDARD))
.checkValue(PROJECT_PROFESSIONAL, microsoftData.get(PROJECT_PROFESSIONAL))
.checkValue(WINDOWS_SERVER_DATA_CENTER, microsoftData.get(WINDOWS_SERVER_DATA_CENTER))
.checkValue(SQL_SERVER_ENTERPRISE, microsoftData.get(SQL_SERVER_ENTERPRISE))
.checkValue(OFFICE_STANDARD, microsoftData.get(OFFICE_STANDARD))
.checkValue(EXCHANGE_ENTERPRISE, microsoftData.get(EXCHANGE_ENTERPRISE))
.checkValue(OFFICE_PROFESSIONAL_PLUS, microsoftData.get(OFFICE_PROFESSIONAL_PLUS))
.checkValue(PROJECT_SERVER, microsoftData.get(PROJECT_SERVER))
.checkValue(WINDOWS_SERVER_STANDARD, microsoftData.get(WINDOWS_SERVER_STANDARD))
.checkValue(REMOTE_DESKTOP_SERVICE, microsoftData.get(REMOTE_DESKTOP_SERVICE))
.checkValue(SQL_SERVER_STANDARD, microsoftData.get(SQL_SERVER_STANDARD))
.checkValue(EXCHANGE_STANDARD_PLUS, microsoftData.get(EXCHANGE_STANDARD_PLUS))
.checkValue(PROJECT, microsoftData.get(PROJECT))
.checkValue(SHAREPOINT_SERVER_PROFESSIONAL, microsoftData.get(SHAREPOINT_SERVER_PROFESSIONAL))
.checkValue(SERVER_SUITE_DATA_CENTER, microsoftData.get(SERVER_SUITE_DATA_CENTER))
.checkValue(SQL_SERVER_WEB, microsoftData.get(SQL_SERVER_WEB))
.checkValue(EXCHANGE_STANDARD, microsoftData.get(EXCHANGE_STANDARD))
.checkValue(WINDOWS_SERVER_STANDARD_VM, microsoftData.get(WINDOWS_SERVER_STANDARD_VM))
.checkValue(RIGHTS_MANAGEMENT_SERVICES, microsoftData.get(RIGHTS_MANAGEMENT_SERVICES))
.checkValue(OFFICE_MULTI_LANGUAGE, microsoftData.get(OFFICE_MULTI_LANGUAGE))
.checkValue(VISUAL_STUDIO, microsoftData.get(VISUAL_STUDIO))
.checkValue(VISUAL_STUDIO_BASIC, microsoftData.get(VISUAL_STUDIO_BASIC))
.checkValue(VISUAL_STUDIO_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_PROFESSIONAL))
.checkValue(VISUAL_STUDIO_TEST_PROFESSIONAL, microsoftData.get(VISUAL_STUDIO_TEST_PROFESSIONAL))
.checkValue(VISUAL_STUDIO_ENTERPRISE, microsoftData.get(VISUAL_STUDIO_ENTERPRISE))
.checkValue(SHAREPOINT_SERVER, microsoftData.get(SHAREPOINT_SERVER))
.checkValue(SHAREPOINT_HOSTING, microsoftData.get(SHAREPOINT_HOSTING));
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.NORMAL)
@DisplayName("Заказ Облачное хранилище, коммерческое")
@TestType.e2e
void createCloudStorageCommercial() {
time = dateTime.getNext2Minutes();
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.cloudStorageName())
.setTypeSubscription(TYPE_COMMERCIAL)
.setDate(date, time)
.setPaperOrder(CLOUD_STORAGE.getOrderNote())
.clickButton();
//*************Step 2**********************
newCloudStoragePage
.clickOn(STORAGE, subscriptionData.tariffDeveloper())
.setValue(NOTE, CLOUD_STORAGE.getCommercialNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.cloudStorageName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status.checkStatus(NEW.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(CLOUD_STORAGE.getOrderNote())
.checkTariffType(FACT)
.checkStartDate(date, time);
cloudStorageRequestPage.checkValue(STORAGE, subscriptionData.tariffDeveloper());
Selenide.closeWindow();
switchTo().window(0);
}
@Severity(value = SeverityLevel.NORMAL)
@DisplayName("Заказ Облачное хранилище, тестовое")
@TestType.e2e
void createCloudStorageTest() {
mainPageProvider.adminLink(linkProvider.newSubscriptionLink());
newSubscriptionPageOne
.setCustomer(userData.customerNewSubscriptionAdmin())
.setSubscription(subscriptionData.cloudStorageName())
.setTypeSubscription(TYPE_TESTING)
.setPaperOrder(CLOUD_STORAGE.getOrderNote())
.clickButton();
//*************Step 2**********************
newCloudStoragePage
.clickOn(STORAGE, subscriptionData.tariffGeneral())
.setValue(NOTE, CLOUD_STORAGE.getTestNote())
.clickButton();
//***************Проверяем правильность заказанных услуг**************************
newSubscriptionFinishPage
.checkNumberOfSubscription(1)
.checkNameOfSubscription(0, subscriptionData.cloudStorageName())
.clickNumberOfSubscription(0);
switchTo().window(1);
status
.checkStatus(NEW.getValue())
.checkTestSubscription(TEST.getValue());
subscriptionProfilePage.clickOnMenu(REQUESTS.getValue());
headerSubscriptionRequestPage
.checkPaperOrder(CLOUD_STORAGE.getOrderNote())
.checkTariffType(FACT);
cloudStorageRequestPage.checkValue(STORAGE, subscriptionData.tariffGeneral());
Selenide.closeWindow();
switchTo().window(0);
}
}
|
package javacollections.flowerbouquet.flowers;
public class Rose extends Flower {
private RoseVariety roseVariety;
public Rose(RoseVariety roseVariety, int stemLength, FreshnessLevel freshnessLevel,
double cost) {
super(stemLength, freshnessLevel, cost);
this.roseVariety = roseVariety;
}
public RoseVariety getRoseVariety() {
return roseVariety;
}
public void setRoseVariety(RoseVariety roseVariety) {
this.roseVariety = roseVariety;
}
@Override
public String toString() {
return super.toString().replace("{",
"{roseVariety=" + roseVariety
+ ", ");
}
}
|
package com.kic.Controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kic.DAO.BoardDAO;
public class DeleteAction implements Action
{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
int id=Integer.parseInt(request.getParameter("id"));
BoardDAO dao=BoardDAO.getDAO();
dao.deleteData(id);
return"/list.do";
}
}
|
package cn.kgc.service;
import cn.kgc.domain.SumFind;
import java.util.List;
public interface SumFindService {
public List<SumFind> sumfind(String license);
}
|
import java.util.*;
class binary
{
public static void main(String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.try");
n=sc.nextInt();
int c=0;
String arr[]=new String[n];
int k=0;
while(k<n)
{
System.out.println("Enter no.");
int l=sc.nextInt();
System.out.println("Enter element");
arr[k]=sc.next();
if(l!=arr[k].length())
{
System.out.println("error size");
}
k++;
}
for(int i=0;i<n;i++)
{
c=frequency(arr[i]);
System.out.println(c);
}
}
static int frequency(String str)
{
String s="";
int c=0;
for(int i=0;i<str.length();i++)
{
for(int j=i;j<str.length();j++)
{
if((str.charAt(i)=='1'))
{
if(str.charAt(j)=='0')
{
s=s+str.charAt(j);
}
else if(str.charAt(j)=='1')
{
c++;s="";
}
}
}
}
return c;
}
}
|
package com.pmm.sdgc.dao;
import com.pmm.sdgc.model.CargoGeral;
import com.pmm.sdgc.model.Lotacao;
import com.pmm.sdgc.model.LotacaoSub;
import com.pmm.sdgc.model.Solicitacao;
import com.pmm.sdgc.model.SolicitacaoSub;
import com.pmm.sdgc.model.UserLogin;
import com.pmm.sdgc.model.UserPermissaoAcesso;
import com.pmm.sdgc.model.UsuarioAcesso;
import com.pmm.sdgc.ws.model.ModelPermissaoAcessoWs;
import com.pmm.sdgc.ws.model.ModelUserPermissaoAcessoWs;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author dreges
*/
@Stateless
public class UserPermissaoAcessoDao {
@PersistenceContext
EntityManager em;
@EJB
FuncionalDao daoFuncional;
@EJB
UserLoginDao daoUserLogin;
@EJB
SolicitacaoDao daoSolicitacao;
@EJB
SolicitacaoSubDao daoSolicitacaoSub;
public void incluir(UserPermissaoAcesso upa) throws Exception {
em.persist(upa);
}
public void alterar(UserPermissaoAcesso upa) throws Exception {
em.merge(upa);
}
public void remover(UserPermissaoAcesso upa) throws Exception {
em.remove(upa);
}
public List<UserPermissaoAcesso> getPermissaoAcessoDeUmFuncional(String id, String chave) throws Exception {
Query q = em.createQuery("select u from UserPermissaoAcesso u where u.userlogin.chave = :chave and u.userMenu.ativo = true and u.userMenu.direcao = 3 and ( (u.lotacao is null and u.lotacaoSub is null) or (u.lotacao.id in (select so.lotacao.id from Solicitacao so where so.ativo = 1 and so.funcional.id =:idfunc)) or (u.lotacaoSub.id in (select ss.lotacaoSub.id from SolicitacaoSub ss where ss.funcional.id = :idfunc and ss.ativo = true))) order by u.userMenu.ordenar");
q.setParameter("idfunc", id);
q.setParameter("chave", chave);
return q.getResultList();
}
public List<ModelUserPermissaoAcessoWs> getPermissaoAcessoDirecao(Integer direcao, String chave) throws Exception {
String e = "select u from UserPermissaoAcesso u where u.userlogin.chave = :pChave and u.userMenu.ativo = true and u.userMenu.direcao = :pDirecao";
Query q = em.createQuery(e);
q.setParameter("pDirecao", direcao);
q.setParameter("pChave", chave);
return ModelUserPermissaoAcessoWs.toModelUserPermissaoAcessoWs(q.getResultList());
}
public ModelPermissaoAcessoWs getPermissaoAcessoDeUmFuncionalDoUsuario(String id, String chave) throws Exception {
// Funcional func = daoFuncional.getUmFuncionalPorIdFuncional(id);
UserLogin usuario = daoUserLogin.getUserLoginPorChave(chave);
Query q = em.createQuery("select p from UserPermissaoAcesso p where p.userlogin.id = :idUsuario");
q.setParameter("idUsuario", usuario.getId());
List<UserPermissaoAcesso> upas = q.getResultList();
ModelPermissaoAcessoWs mpaw = new ModelPermissaoAcessoWs();
mpaw.setAlterar(Boolean.FALSE);
mpaw.setBuscar(Boolean.FALSE);
mpaw.setExcluir(Boolean.FALSE);
mpaw.setIncluir(Boolean.FALSE);
mpaw.setListar(Boolean.FALSE);
boolean secretaria = false;
for (UserPermissaoAcesso upa : upas) {
if (upa.getLotacao() == null && upa.getLotacaoSub() == null) {
//System.out.println("Administrador");
mpaw.setAlterar(upa.getAlterar());
mpaw.setBuscar(upa.getBuscar());
mpaw.setExcluir(upa.getExcluir());
mpaw.setIncluir(upa.getIncluir());
mpaw.setListar(upa.getListar());
return mpaw;
}
if (!(upa.getLotacao() == null)) {
List<Solicitacao> solicitacoes = daoSolicitacao.getSolicitacaoAtiva(id);
for (Solicitacao s : solicitacoes) {
if (s.getLotacao().getId().equals(upa.getLotacao().getId())) {
//System.out.println("Secretaria");
secretaria = true;
mpaw.setAlterar(upa.getAlterar());
mpaw.setBuscar(upa.getBuscar());
mpaw.setExcluir(upa.getExcluir());
mpaw.setIncluir(upa.getIncluir());
mpaw.setListar(upa.getListar());
}
}
} else {
if (secretaria == false) {
List<SolicitacaoSub> solicitacoesSub = daoSolicitacaoSub.getSolicitacaoSubPorIdAtivo(id);
for (SolicitacaoSub ss : solicitacoesSub) {
if (ss.getLotacaoSub().getId().equals(upa.getLotacaoSub().getId())) {
//System.out.println("Setor");
mpaw.setAlterar(upa.getAlterar());
mpaw.setBuscar(upa.getBuscar());
mpaw.setExcluir(upa.getExcluir());
mpaw.setIncluir(upa.getIncluir());
mpaw.setListar(upa.getListar());
}
}
}
}
}
return mpaw;
}
public Boolean getUsuarioPodeCriarUsuario(String chave) throws Exception {
Query q = em.createQuery("select u from UserPermissaoAcesso u where u.userlogin.chave = :chave and u.userMenu.pasta = :pasta and u.userMenu.arquivo = :arquivo and u.userMenu.ativo = true");
q.setParameter("chave", chave);
q.setParameter("pasta", "usuario");
q.setParameter("arquivo", "acesso");
List<UserPermissaoAcesso> acessos = q.getResultList();
if (acessos.isEmpty()) {
return false;
}
return true;
}
public UsuarioAcesso getAcessosUmUsuario(String chave, String menuN1, String link) {
Query q = em.createQuery("select u from UserPermissaoAcesso u where u.userlogin.chave = :chave and u.userMenu.menuN1 = :mn1 and u.userMenu.link = :lnk");
q.setParameter("chave", chave);
q.setParameter("mn1", menuN1);
q.setParameter("lnk", link);
UsuarioAcesso acesso = new UsuarioAcesso();
List<UserPermissaoAcesso> permissoes = q.getResultList();
if (permissoes.isEmpty()) {
acesso.setCompleto(Boolean.FALSE);
acesso.setLotacoes(new ArrayList());
acesso.setSetores(new ArrayList());
return acesso;
}
//UserPermissaoAcesso permissao = permissoes.get(0);
for (UserPermissaoAcesso permissao : permissoes) {
if (permissao.getLotacao() == null && permissao.getLotacaoSub() == null) {
acesso.setLotacoes(new ArrayList());
acesso.setSetores(new ArrayList());
acesso.setCompleto(Boolean.TRUE);
return acesso;
}
if (!(permissao.getLotacaoSub()== null)) {
acesso.getSetores().add(permissao.getLotacaoSub());
acesso.getLotacoes().add(null);
} else {
acesso.getLotacoes().add(permissao.getLotacao());
acesso.getSetores().add(null);
}
}
return acesso;
}
@EJB
LotacaoDao daoLotacao;
public List<Lotacao> getListLotacaoUsuario(String chave) {
Query q = em.createQuery("select distinct u.lotacao from UserPermissaoAcesso u where u.userlogin.chave = :c");
q.setParameter("c", chave);
List<Lotacao> lista = q.getResultList();
if (lista.isEmpty()) {
q = em.createQuery("select u from UserPermissaoAcesso u where u.lotacao = null and u.userlogin.chave = :c");
q.setParameter("c", chave);
lista = q.getResultList();
if (!(lista.isEmpty())) {
lista = daoLotacao.getLotacao();
}
}
return lista;
}
public List<Lotacao> getListLotacaoUsuarioContabil(String chave) {
Query q = em.createQuery("select distinct u.lotacao from UserPermissaoAcesso u where u.userlogin.chave = :c and u.userMenu.id = 7");
q.setParameter("c", chave);
List<Lotacao> lista = q.getResultList();
if (lista.isEmpty()) {
q = em.createQuery("select u from UserPermissaoAcesso u where u.lotacao = null and u.userlogin.chave = :c");
q.setParameter("c", chave);
lista = q.getResultList();
if (!(lista.isEmpty())) {
lista = daoLotacao.getLotacao();
}
}
return lista;
}
public List<Lotacao> getListLotacaoUsuarioOcorrencia(String chave) {
Query q = em.createQuery("select distinct u.lotacao from UserPermissaoAcesso u where u.userlogin.chave = :c and u.userMenu.id = 77");
q.setParameter("c", chave);
List<Lotacao> lista = q.getResultList();
if (lista.isEmpty()) {
q = em.createQuery("select u from UserPermissaoAcesso u where u.lotacao = null and u.userlogin.chave = :c");
q.setParameter("c", chave);
lista = q.getResultList();
if (!(lista.isEmpty())) {
lista = daoLotacao.getLotacao();
}
}
return lista;
}
public List<Lotacao> getListLotacaoUsuarioSemAdicao(String chave) {
Query q = em.createQuery("select distinct u.lotacao from UserPermissaoAcesso u where u.userlogin.chave = :c and u.lotacaoSub is null");
q.setParameter("c", chave);
List<Lotacao> lista = q.getResultList();
return lista;
}
@EJB
LotacaoSubDao daoLotacaoSub;
public List<LotacaoSub> getListLotacaoSubUsuario(String id,String chave) {
Query q = em.createQuery("select distinct u.lotacaoSub from UserPermissaoAcesso u where u.userlogin.chave = :c");
q.setParameter("c", chave);
List<LotacaoSub> lista = q.getResultList();
if (lista.isEmpty()) {
lista = daoLotacaoSub.getListaLotacaoSub(id);
}
return lista;
}
public List<LotacaoSub> getListLotacaoSubUsuario(String chave) {
Query q = em.createQuery("select distinct u.lotacaoSub from UserPermissaoAcesso u where u.userlogin.chave = :c");
q.setParameter("c", chave);
List<LotacaoSub> lista = q.getResultList();
return lista;
}
public List<CargoGeral> getListCargoGeralUsuario(String chave) {
Query q = em.createQuery("select distinct u.cargoGeral from UserPermissaoAcesso u where u.userlogin.chave = :c");
q.setParameter("c", chave);
List<CargoGeral> lista = q.getResultList();
return lista;
}
}
|
package com.citi.yourbank.vo;
import io.swagger.annotations.ApiModel;
import lombok.Data;
@ApiModel("OwnerDetail")
@Data
public class OwnerDetailVO {
private String userId;
private String firstName;
private String lastName;
}
|
/**
*
*/
package com.adobe.prj.client.ui;
import java.util.List;
import com.adobe.prj.dto.ProjectDetailsDto;
/**
* @author danchara
* For listing project info for requirement (e)
*/
public class ProjectListingUi {
/*
* Displays individual project.
* @param projectDetailsDto Dto of project to be displayed.
*/
public static void displayProjectInformation(ProjectDetailsDto projectDetailsDto){
System.out.println("PROJECT : "+projectDetailsDto.getProjectName());
StringBuilder managerStringBuilder = new StringBuilder("MANAGER : ");
if(projectDetailsDto.getManagerName()!= null){
managerStringBuilder.append(projectDetailsDto.getManagerName());
}
System.out.println(managerStringBuilder.toString());
System.out.println("STAFF : ");
List<String> staffList = projectDetailsDto.getStaff();
int employeeSerialNumber =1;
for(String staffMember : staffList ){
System.out.println("\t\t"+employeeSerialNumber+". "+staffMember);
employeeSerialNumber += 1;
}
System.out.println("\n\n");
}
/*
* Displays project listing .
* @param projectDetailsDtoList list of ProjectDetailsDto
*/
public static void displayProjectListing(List<ProjectDetailsDto> projectDetailsDtoList){
for(ProjectDetailsDto projectDetailsDto :projectDetailsDtoList ){
displayProjectInformation(projectDetailsDto);
}
}
}
|
package com.riddit.Riddit.controller;
import com.riddit.Riddit.model.Text;
import com.riddit.Riddit.service.TextService;
import com.riddit.Riddit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class TextController {
@Autowired
private TextService textService;
@Autowired
private UserService userService;
/* TODO: order by: post date (Descending)
votes (Ascending or Descending)
comment number (Descending) */
@RequestMapping("/text")
public List<Text> getAllTexts() {
return textService.getAllTexts();
}
// TODO: Add option to fetch comments
@RequestMapping("/text/{id}")
public Text getText(@PathVariable Long id) {
return textService.getText(id);
}
@RequestMapping(method = RequestMethod.POST, value = "/text")
public void addText(@RequestBody Text text, @RequestParam String userId) {
text.setUser(userService.getUser(userId));
textService.addText(text);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/text/{id}")
public void deleteText(@PathVariable Long id) {
textService.deleteText(id);
}
// TODO: Add method to vote
}
|
package org.kobic.genome.project.dao;
public interface ProjectDao {
// test
// add test
// test minseo
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.innovaciones.reporte.service;
import com.innovaciones.reporte.dao.UsuarioRolesDAO;
import com.innovaciones.reporte.model.UsuarioRoles;
import com.innovaciones.reporte.model.Usuarios;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author pisama
*/
@Service
@ManagedBean(name = "usuarioRolesService")
@ViewScoped
public class UsuarioRolesServiceImpl implements UsuarioRolesService, Serializable {
private UsuarioRolesDAO usuarioRolesDAO;
public void setUsuarioRolesDAO(UsuarioRolesDAO usuarioRolesDAO) {
this.usuarioRolesDAO = usuarioRolesDAO;
}
@Override
@Transactional
public UsuarioRoles addUsuarioRoles(UsuarioRoles usuarioRoles) {
return usuarioRolesDAO.addUsuarioRoles(usuarioRoles);
}
@Override
@Transactional
public List<UsuarioRoles> addUsuarioRoles(List<UsuarioRoles> listUsuarioRoles) {
List<UsuarioRoles> result = new ArrayList<UsuarioRoles>();
if (!listUsuarioRoles.isEmpty()) {
List<UsuarioRoles> rolesActuales = getUsuariosRolesByUsuario(listUsuarioRoles.get(0).getIdUsuario());
for (UsuarioRoles rolesActuale : rolesActuales) {
deleteUsuarioRoles(rolesActuale);
}
//deleteUsuarioRoles(rolesActuales);
}
for (int i = 0; i < listUsuarioRoles.size(); i++) {
result.add(addUsuarioRoles(listUsuarioRoles.get(i)));
}
return result;
}
@Override
@Transactional
public UsuarioRoles deleteUsuarioRoles(UsuarioRoles usuarioRoles) {
return usuarioRolesDAO.deleteUsuarioRoles(usuarioRoles);
}
@Override
@Transactional
public List<UsuarioRoles> deleteUsuarioRoles(List<UsuarioRoles> listUsuarioRoles) {
for (int i = 0; i < listUsuarioRoles.size(); i++) {
deleteUsuarioRoles(listUsuarioRoles.get(i));
}
return listUsuarioRoles;
}
@Override
@Transactional
public List<UsuarioRoles> getUsuariosRolesByUsuario(Usuarios usuarios) {
return usuarioRolesDAO.getUsuariosRolesByUsuario(usuarios);
}
}
|
/*******************************************************************************
Name: Sarah Redmon
Date: 1/23/19
Instructor: Ms. Tucker
Class: GasPanel
Purpose: To show the total amount and cost of KWH in a GUI
*******************************************************************************
*/
/*------------------------------------------------------------------------------
FEEDBACK FROM INSTRUCTOR:
Sarah, great job. Your exit button will not work if the form is blank.
The code for exit is embedded within the if statement to check the text fields.
It's OK to exit at any time. Otherwise, great work.
-------------------------------------------------------------------------------*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.text.DecimalFormat;
public class GasPanel extends JPanel
{
/*------------------------------------------------------------------------------
Initializes variables, JLabels, JTextFields, and JButtons for program
------------------------------------------------------------------------------
*/
private int numRef, numWashDry, numOven, numMicro, numCoff, numComp, numTV;
private JLabel headingLabel, refLabel, washDryLabel, ovenLabel, microLabel, coffLabel, compLabel,
tvLabel, KWHUsedLabel, KWHCostLabel, KWHUsedAnswer, KWHCostAnswer;
private JTextField refAnswer, washDryAnswer, ovenAnswer, microAnswer, coffAnswer, compAnswer,
tvAnswer;
private JButton calculate, clear, exit;
public GasPanel()
{
/*------------------------------------------------------------------------------
Asks for user's input and shows text fields along with showing a header
------------------------------------------------------------------------------
*/
headingLabel = new JLabel("------------------ GAS PANEL ------------------");
refLabel = new JLabel("How many refrigerators do you have? ");
refAnswer = new JTextField(2);
washDryLabel = new JLabel("How many washers/dryers do you have? ");
washDryAnswer = new JTextField(2);
ovenLabel = new JLabel("How many ranges/ovens do you have? ");
ovenAnswer = new JTextField(2);
microLabel = new JLabel("How many microwaves do you have? ");
microAnswer = new JTextField(2);
coffLabel = new JLabel("How many coffee machines do you have? ");
coffAnswer = new JTextField(2);
compLabel = new JLabel("How many computers do you have? ");
compAnswer = new JTextField(2);
tvLabel = new JLabel("How many TVs do you have? ");
tvAnswer = new JTextField(2);
/*------------------------------------------------------------------------------
Button listener is added and adds in buttons, listeners, and labels
------------------------------------------------------------------------------
*/
ButtonListener listener = new ButtonListener();
calculate = new JButton("Calculate");
clear = new JButton("Clear");
exit = new JButton("Exit");
calculate.addActionListener(new ButtonListener());
clear.addActionListener(new ButtonListener());
exit.addActionListener(new ButtonListener());
KWHUsedLabel = new JLabel("KWH Used: ");
KWHUsedAnswer = new JLabel("-----");
KWHCostLabel = new JLabel("Total Cost: $");
KWHCostAnswer = new JLabel("-----");
/*------------------------------------------------------------------------------
Adds in the data for calculation & display
------------------------------------------------------------------------------
*/
add (headingLabel);
add (refLabel);
add (refAnswer);
add (washDryLabel);
add (washDryAnswer);
add (ovenLabel);
add (ovenAnswer);
add (microLabel);
add (microAnswer);
add (coffLabel);
add (coffAnswer);
add (compLabel);
add (compAnswer);
add (tvLabel);
add (tvAnswer);
add (calculate);
add (clear);
add (exit);
add (KWHUsedLabel);
add (KWHUsedAnswer);
add (KWHCostLabel);
add (KWHCostAnswer);
/*------------------------------------------------------------------------------
Display options
------------------------------------------------------------------------------
*/
setPreferredSize (new Dimension(275, 275));
setBackground (Color.pink);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String refString = refAnswer.getText();
String washdryString = washDryAnswer.getText();
String ovenString = ovenAnswer.getText();
String microString = microAnswer.getText();
String coffString = coffAnswer.getText();
String compString = compAnswer.getText();
String tvString = tvAnswer.getText();
if (refString.length() > 0 && washdryString.length() > 0 && ovenString.length() > 0
&& microString.length() > 0 && coffString.length() > 0 && compString.length() > 0
&& tvString.length() > 0) {
if (event.getSource() == calculate) {
/*------------------------------------------------------------------------------
If calculate is clicked on
* Initialize variables & constants
* Set up Decimal Format
* Receive answers, make them into strings, and turn them into number for calculations
* Calculate and display
------------------------------------------------------------------------------
*/
double KWHcost, KWHused;
final double COSTPERKWH = 9.047e-2;
final int KWH_REF = 57, KWH_WASHDRY = 63, KWH_OVEN = 24, KWH_MICRO = 11, KWH_COFF = 10,
KWH_COMP = 21, KWH_TV = 23;
DecimalFormat format1DecimalPlace = new DecimalFormat ("####.##");
numRef = Integer.parseInt(refString);
numWashDry = Integer.parseInt(washdryString);
numOven = Integer.parseInt(ovenString);
numMicro = Integer.parseInt(microString);
numCoff = Integer.parseInt(coffString);
numComp = Integer.parseInt(compString);
numTV = Integer.parseInt(tvString);
KWHused = ((KWH_REF * numRef) + (KWH_WASHDRY * numWashDry) + (KWH_OVEN * numOven) + (KWH_MICRO * numMicro) + (KWH_COFF * numCoff) + (KWH_COMP * numComp) + (KWH_TV * numTV));
KWHUsedAnswer.setText(format1DecimalPlace.format(KWHused));
KWHcost = (COSTPERKWH * KWHused);
KWHCostAnswer.setText(format1DecimalPlace.format(KWHcost));
}
if (event.getSource() == clear) {
/*------------------------------------------------------------------------------
If clear is clicked-empties text fields & places cursor over refAnswer text field
------------------------------------------------------------------------------
*/
refAnswer.requestFocusInWindow();
refAnswer.setText("");
washDryAnswer.setText("");
ovenAnswer.setText("");
microAnswer.setText("");
coffAnswer.setText("");
compAnswer.setText("");
tvAnswer.setText("");
KWHUsedAnswer.setText("-----");
KWHCostAnswer.setText("-----");
}
if (event.getSource() == exit) {
/*------------------------------------------------------------------------------
If exit is clicked-closes program
------------------------------------------------------------------------------
*/
System.exit(0);
}
} else {
KWHUsedAnswer.setText("Invalid input");
KWHCostAnswer.setText("Invalid input");
}
}
}
}
|
/* ------------------------------------------------------------------------------
* 软件名称:BB语音
* 公司名称:乐多科技
* 开发作者:Yongchao.Yang
* 开发时间:2016年3月3日/2016
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.ace.web.service
* fileName:ShowFun.java
* -------------------------------------------------------------------------------
*/
package com.ace.database.module;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.rednovo.ace.constant.Constant;
import com.rednovo.ace.entity.Gift;
import com.rednovo.ace.entity.GiftDetail;
import com.rednovo.ace.globalData.UserManager;
import com.rednovo.tools.DateUtil;
/**
* @author yongchao.Yang/2016年3月3日
*/
public class GiftModule extends BasicModule {
public GiftModule() {
}
public Gift getGift(String id) {
return this.getGiftDao().getGift(id);
}
/**
* 赠送礼物明细
*
* @param detail
* @return
* @author Yongchao.Yang
* @since 2016年3月4日下午1:29:17
*/
public String addGiftDetail(String senderId, String receiverId, String giftId, int giftCnt) {
Gift g = this.getGiftDao().getGift(giftId);
if (g == null) {
return "500";
}
BigDecimal consumeVal = g.getSendPrice().multiply(new BigDecimal(giftCnt));
GiftDetail gcd = new GiftDetail();
gcd.setUserId(senderId);
gcd.setChannel(Constant.logicType.SEND_GIFT.getValue());
gcd.setCreateTime(DateUtil.getStringDate());
gcd.setDescription(senderId + "消费" + consumeVal.floatValue() + "金币,送给用户(" + receiverId + ")" + giftCnt + "个" + g.getName());
gcd.setGiftCnt(giftCnt);
gcd.setGiftId(giftId);
gcd.setGiftName(g.getName());
gcd.setPrice(g.getSendPrice());
gcd.setRelateUserId(receiverId);
gcd.setRelateUserName(UserManager.getUser(receiverId).getNickName());
gcd.setTotalValue(consumeVal);
gcd.setUserName("");
String exeRes = this.getGiftDao().addGiftChangeDetail(gcd, Constant.ChangeType.REDUCE);
if (!Constant.OperaterStatus.SUCESSED.getValue().equals(exeRes)) {// 添加礼物送出记录
return exeRes;
}
// 添加接收明细
gcd.setUserId(receiverId);
gcd.setUserName("");
gcd.setRelateUserId(senderId);
gcd.setRelateUserName("");
gcd.setDescription(receiverId + "收到" + senderId + "礼物(" + g.getName() + ")" + giftCnt + "个,消费金币" + consumeVal.floatValue());
return this.getGiftDao().addGiftChangeDetail(gcd, Constant.ChangeType.ADD);
}
/**
* 获取礼物进出账明细
*
* @param userId
* @param beginTime
* @param endTime
* @param type
* @param page
* @param pageSize
* @return
* @author Yongchao.Yang
* @since 2016年3月6日下午4:23:18
*/
public HashMap<String, ArrayList<GiftDetail>> getGiftDetailList(String userId, String beginTime, String endTime, Constant.ChangeType type, int page, int pageSize) {
return this.getGiftDao().getGiftDetailList(userId, beginTime, endTime, type, page, pageSize);
}
public ArrayList<Gift> getSynGift() {
return this.getGiftDao().getGift();
}
/**
* 添加或者修改礼物
* @param gift
* @return
*/
public String addOrUpdateGift(Gift gift){
return this.getGiftDao().addOrUpdateGift(gift);
}
/**
* 查询上架,下架,待上架数据
* @param status
* @return
*/
public List<Gift> getGiftByStatus(String status){
return this.getGiftDao().getGiftByStatus(status);
}
/**
* 获取需要同步的收礼信息
* @param synId
* @param maxCnt
* @return
*/
public ArrayList<GiftDetail> getSynReceiveGiftDetailList(String synId, int maxCnt){
return this.getGiftDao().getSynReceiveGiftDetailList(synId, maxCnt);
}
}
|
package cn.com.hy.control;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import cn.com.hy.service.GetPlatformDataService;
import cn.com.hy.service.SyncJJXXDate;
import cn.com.hy.util.CommonUtil;
import cn.com.hy.util.DateUtils;
import cn.com.hy.util.JsonUtil;
@Controller
@RequestMapping("/data")
public class DataController {
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(DataController.class);
@Resource
GetPlatformDataService gpd;
/**
* WangY
* http请求,获取数据
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/getDatas", produces = "application/json;charset=utf-8")
@ResponseBody
public String getDatas(HttpServletRequest request, HttpServletResponse response) {
String queryMethodResult = "";
///前端传递数据参数
String methodName = request.getParameter("methodName");
String dataObjectCode = request.getParameter("dataObjectCode");
String conditions = request.getParameter("conditions");
if (CommonUtil.isNullOrBlank(methodName)|| CommonUtil.isNullOrBlank(dataObjectCode) ) {
/// 没有传递函数名
logger.info("code : -1, message:请求参数中conditions、dataObjectCode 不存在");
queryMethodResult = "{code:-1,message:请求参数中conditions、dataObjectCode 不存在}";
} else {
/************ 常见数据的初始化 *******************/
/// 返回结果字段
String returnFields = request.getParameter("returnFields");
if (conditions == null) {
conditions = "";
}
if (returnFields == null) {
returnFields = "";
}
/// 每页条目数量没传值默认给20条
int pageSize = 20;
String pageSizeStr = request.getParameter("pageSize");
///未传分页大小
if (!CommonUtil.isNullOrBlank(pageSizeStr) ) {
pageSize = Integer.parseInt(pageSizeStr);
}
/// 分页查询页面,默认给他第一页
String pageNumberString = request.getParameter("pageNumber");
int pageNumber = 1;
if (!CommonUtil.isNullOrBlank( pageNumberString) ){
pageNumber = Integer.parseInt(pageNumberString);
}
// 是否格式化
boolean formatted = Boolean.parseBoolean(request.getParameter("formatted"));
// xml或json
String resultStyle = request.getParameter("resultStyle");
/****************系统中方法问题**********************/
if (methodName.equals("count")) {///调用查询条数方法
queryMethodResult = this.getResultByCount(dataObjectCode, conditions);
}else if (methodName.equals("query")) {//普通查询方法
///query 查询方法
queryMethodResult = this.getResultByQuery(dataObjectCode, conditions, returnFields, pageSize, formatted,resultStyle);
}else if (methodName.equals("pageQuery")) {//分页查询方法
queryMethodResult = this.getResultByPageQuery(dataObjectCode, conditions, returnFields, pageSize, pageNumber,formatted, resultStyle);
} else if (methodName.equals("queryJJXX")) {// 接警信息,从大平台后端获取数据
/// 传递时间到后台
String dateStart = request.getParameter("D1");
///
String JJBHString = request.getParameter("JJBH");
/// 刑事警情类别
String XSJQString = request.getParameter("D2");
// 时间的格式化
queryMethodResult = this.getResultByQueryJJXX(dataObjectCode, conditions, returnFields,dateStart,JJBHString,XSJQString);
}///20170420 王勇合肥用于系统同步数据
else if (methodName.equals("querySyncJJXX")) {//合肥微勘后台服务使用查询
///传递时间到后台
String dateStart = request.getParameter("DStart");
///传递结束
String dateEnd = request.getParameter("DEnd");
///接警编号
String JJBHString = request.getParameter("JJBH");
///调用
queryMethodResult = this.getResultByQuerySyncJJXX(dataObjectCode, conditions, returnFields, dateStart, dateEnd, JJBHString);
}else {
logger.info("code:-2, message: 传递methodName不存在,请检查");
queryMethodResult = "{code:-2, message: 传递methodName 存在问题请检查}";
}
}
//回调方法
String callback = request.getParameter("callback");
if (StringUtils.isEmpty(callback)){
return queryMethodResult;
}else{
return callback + "(" + queryMethodResult + ")";
}
}
/**
* 查询数据条数
* methodName=count
* @param dataObjectCode
* @param conditions
* @return
*/
private String getResultByCount(String dataObjectCode, String conditions){
return gpd.count(dataObjectCode, conditions).toString();
}
/**
* query 方法调取数据
* methodName= query
* @param dataObjectCode
* @param conditions
* @param returnFields
* @param pageSize
* @param formatted
* @param resultStyle
* @return
*/
private String getResultByQuery(String dataObjectCode, String conditions
,String returnFields,int pageSize, boolean formatted, String resultStyle){
if (resultStyle == null) {
resultStyle = "";
}
//未格式化
if (!formatted) {
return gpd.query(dataObjectCode, conditions, returnFields, pageSize);
}
return gpd.query(dataObjectCode, conditions, returnFields, pageSize, formatted,resultStyle);
}
/**
* 分页查询 WangY 20171018
* methodName=pageQuery
* @param dataObjectCode
* @param conditions
* @param returnFields
* @param pageSize
* @param pageNumber
* @param formatted
* @param resultStyle
* @return
*/
private String getResultByPageQuery(String dataObjectCode, String conditions,String returnFields,int pageSize, int pageNumber
,boolean formatted, String resultStyle){
if (resultStyle == null) {
resultStyle = "";
}
if (!formatted) {
return gpd.pageQuery(dataObjectCode, conditions, returnFields, pageSize, pageNumber);
}
return gpd.pageQuery(dataObjectCode, conditions, returnFields, pageSize, pageNumber,formatted, resultStyle);
}
/**
* 查询警情警情方法
* method=queryJJXX
* @param dataObjectCode
* @param conditions
* @param returnFields
* @param dateStart
* @param JJBHString
* @param XSJQString
* @return
*/
private String getResultByQueryJJXX(String dataObjectCode, String conditions
,String returnFields,String dateStart,String JJBHString,String XSJQString){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
//传递数据 conditions 不为空
if (! "".equals(conditions)) {
conditions += " and ";
}
if (!CommonUtil.isNullOrBlank(JJBHString)) {
conditions += "JJBH='" + JJBHString + "'";
} else {
/// conditions 传递参数过来
if (conditions.contains("JJBH")) {
conditions += " and ";
}
/// 刑事警情
if (!CommonUtil.isNullOrBlank(XSJQString)) {
conditions += " BJLX ='" + XSJQString + "'";
}
if ( conditions.contains("BJLX")) {
conditions += " and ";
}
///20170207 王勇
String currentDate = simpleDateFormat.format(new Date());
//没传日期,请求今天的数据
if (CommonUtil.isNullOrBlank(dateStart)) {
//String currentDate = simpleDateFormat.format(new Date());
dataObjectCode = "DWD_DPT_JCJ_JJXX_ONEDAY";
/*
* 当前日期使用like进行
* String currentDateStart = currentDate + "000000";
String currentDateEnd = currentDate + "235959";*/
conditions += "JJRQSJ like '" + currentDate + "%'";
/*conditions += "JJRQSJ>= to_date('" + currentDateStart
+ "' ,'yyyymmddhh24miss') AND JJRQSJ<= to_date('" + currentDateEnd
+ "' ,'yyyymmddhh24miss')";*/
} else {
Date d = DateUtils.getUtilDateByString(dateStart, "yyyy-MM-dd");
String dateStartFormt = DateUtils.getDateTime(d, "yyyyMMdd");
if (dateStartFormt.equals(currentDate)) {
dataObjectCode = "DWD_DPT_JCJ_JJXX_ONEDAY";
conditions += "JJRQSJ like '" + currentDate + "%'";
}else {
String specialDateStart = dateStartFormt + "000000";
String specialDateEnd = dateStartFormt + "235959";
// System.out.println(currentDate);
dataObjectCode = "DWD_DPTJCJ_JJXX";
conditions += "JJRQSJ>= to_date('" + specialDateStart
+ "' ,'yyyymmddhh24miss') AND JJRQSJ<= to_date('" + specialDateEnd
+ "' ,'yyyymmddhh24miss')";
}
}
}
return this.getResultByQuery(dataObjectCode, conditions, returnFields, 500,false,null);
}
/**
* WangY 20171018 ,合肥使用
* methodName = querySyncJJXX
* @param dataObjectCode
* @param conditions
* @param returnFields
* @param dateStart
* @param dateEnd
* @param JJBHString
* @return
*/
private String getResultByQuerySyncJJXX(String dataObjectCode, String conditions
,String returnFields,String dateStart ,String dateEnd,String JJBHString){
Map<String, String> dataObjectCodeConditionMap = new HashMap<String, String>();
// 时间的格式化
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
if (!conditions.equals("")) {
conditions += " and ";
}
if (JJBHString != null && JJBHString != "") {
conditions += "JJBH='" + JJBHString + "'";
} else {
/// 传条件值条件值
if (conditions.contains("JJBH")) {
conditions += " and ";
}
///20170420 王勇
///查询接警信息
if (dataObjectCode.equals("DWD_DPTJCJ_JJXX") || dataObjectCode.equals("DWD_DPT_AJ_JBXX") || dataObjectCode.equals("DWD_DPTJCJ_CJXX")) {
dataObjectCodeConditionMap.clear();
dataObjectCodeConditionMap.putAll(new SyncJJXXDate().getDataObjectCodeConditioMap(dataObjectCode,dateStart, dateEnd));
}
}
String conditionTempStr = conditions;
//保存两个结果
List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
listMap.clear();
///获取objectCode
for (Map.Entry<String, String> entry : dataObjectCodeConditionMap.entrySet()) {
dataObjectCode = entry.getKey();
conditions = conditionTempStr + entry.getValue();
List<Map<String, String>> listMapTemp = new ArrayList<Map<String, String>>();
//查询总共有多少条
int queryCounts = 0;
String queryCountStr = this.getResultByCount(dataObjectCode, conditions);
if (!CommonUtil.isNullOrBlank(queryCountStr)) {
logger.info("test条数:" + queryCounts);
queryCounts = Integer.parseInt(queryCountStr);
}
String queryResult = this.getResultByQuery(dataObjectCode, conditions, returnFields, queryCounts,false,null);
listMapTemp = JsonUtil.parseMap2JavaBean(queryResult, new TypeToken<List<Map<String, String>>>() {}.getType());
if (listMapTemp.size() > 0) {
listMap.addAll(listMapTemp);
}
}
return new Gson().toJson(listMap);
}
}
|
package screens;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
public class HomeScreen extends BaseScreen {
public HomeScreen(AndroidDriver driver) {
super(driver);
}
String loginButton = "//android.widget.TextView[@text='Profil']";
public void clickProfile() throws Exception {
waitForElementVisible(By.xpath(loginButton)).click();
}
}
|
package edu.kmi.primejavaC.JWC.Model;
import java.sql.SQLException;
import edu.kmi.primejavaC.JWC.Controller.FrontController;
/**
* Created by JINU on 2017. 6. 8..
*/
public class DB_Test {
public static void main(String[] args) throws SQLException {
FrontController dao = new FrontController();
//dao.idCheck("tes2t", "testtest");
dao.open();
dao.delete("test23", "123");
//dao.checkUser("test", "test");
//dao.typelist("남자", "B", "서울");
dao.close();
//dao.dataDelete("test");
//dao.dataProfile("test", "진우짱", 25, "여자", "서울", 1088387684,"안녕하세요반가워요","B","죽어","AB");
}
}
|
package com.prasnottar.nepalidateconverter.core;
import java.util.Calendar;
/**
* Created by bibek on 6/24/17.
*/
interface CommonEnglishDateConverter {
//INPUT : NEPALI YEAR, MONTH, DAYS OR NEPALIDATE OBJECT
//step-1 : STARTING POINT FOR BOTH NEPALI DATE AND ENGLISH DATE
int STARTING_ENGLISH_YEAR = 1943;
int STARTING_ENGLISH_MONTH = 4;
int STARTING_ENGLISH_DAY = 14;
int STARTING_DAY_OF_WEEK = Calendar.WEDNESDAY;
int STARTING_NEPALI_DAY = 1;
int[] DAYS_IN_MONTHS_IN_ENGLISH_DATE
= new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] DAYS_IN_MONTHS_IN_ENGLISH_DATE_IN_LEAP_YEAR = new int[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String PATTERN_ONE = "yyyy/MM/dd";
}
|
public class InvalidValueException extends ValueException
{
public InvalidValueException(String invalid_argument, String invalid_value)
{
super("Niedozwolona wartość \"" + invalid_value + "\" dla klucza " + invalid_argument);
}
}
|
package kr.co.people_gram.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.util.ArrayList;
public class SubPeopleSearch_Activity extends AppCompatActivity {
private EditText serachET;
private ArrayList<SubPeopleListDTO> people_dto_list;
private ArrayList<SubPeopleListDTO_Temp> people_dto_list_temp;
private SubPeopleListAdapter people_adapter_list;
private String searchTEXT = "";
private ListView sf_people_list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_people_search_);
people_dto_list = new ArrayList<SubPeopleListDTO>();
people_dto_list_temp = SubPeopleFragment.people_dto_list_temp;
sf_people_list = (ListView) findViewById(R.id.sf_people_list);
sf_people_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
finish();
final SubPeopleListDTO dto = (SubPeopleListDTO) sf_people_list.getItemAtPosition(position);
RequestParams params = new RequestParams();
params.put("uid", SharedPreferenceUtil.getSharedPreference(SubPeopleSearch_Activity.this, "uid"));
params.put("people_uid", dto.get_profile_uid());
HttpClient.post("/people/peoplePopupView", params, new AsyncHttpResponseHandler() {
public void onStart() {
//dialog = ProgressDialog.show(getActivity(), "", "데이터 수신중");
}
public void onFailure() {
}
public void onFinish() {
//dialog.dismiss();
}
@Override
public void onSuccess(String response) {
if(dto.get_profile_type().equals("")) {
Intent intent = new Intent(SubPeopleSearch_Activity.this, YouType_Actvity_step1.class);
intent.putExtra("people_uid", dto.get_profile_uid());
intent.putExtra("people_username", dto.get_profile_username());
intent.putExtra("people_email", dto.get_profile_email());
startActivityForResult(intent, 000001);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
} else {
Intent intent = new Intent(SubPeopleSearch_Activity.this, SubPeopleListPopup_Activity.class);
intent.putExtra("people_uid", dto.get_profile_uid());
intent.putExtra("people_email", dto.get_profile_email());
intent.putExtra("people_username", dto.get_profile_username());
intent.putExtra("people_mood", dto.get_profile_mood());
intent.putExtra("people_type", dto.get_profile_type());
intent.putExtra("people_gubun1", dto.get_profile_gubun1());
intent.putExtra("people_gubun2", dto.get_profile_gubun2());
intent.putExtra("people_speed", dto.get_profile_speed());
intent.putExtra("people_control", dto.get_profile_control());
intent.putExtra("people_result_count", dto.get_profile_cnt());
intent.putExtra("people_friend_count", dto.get_profile_friend_cnt());
intent.putExtra("people_coaching", response);
startActivityForResult(intent, 000001);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
}
}
});
}
});
serachET = (EditText) findViewById(R.id.serachET);
TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
people_dto_list.clear();
for(int i = 0; i<people_dto_list_temp.size(); i++) {
searchTEXT = String.valueOf(serachET.getText());
Log.d("people_gram", searchTEXT);
SubPeopleListDTO_Temp dto = people_dto_list_temp.get(i);
if(SoundSearcher.matchString(dto.get_profile_username().toString(), searchTEXT)) {
people_dto_list.add(new SubPeopleListDTO(
dto.get_profile_uid()
, ""
, dto.get_profile_username()
, dto.get_profile_email()
, dto.get_profile_type()
, ""
, dto.get_profile_gubun1()
, dto.get_profile_gubun2()
, dto.get_profile_speed()
, dto.get_profile_control()
, dto.get_profile_cnt()
, dto.get_profile_friend_cnt()
, dto.get_profile_new_cnt()
));
}
/*
if(dto.get_profile_username().contains(searchTEXT)) {
people_dto_list.add(new SubPeopleListDTO(
dto.get_profile_uid()
, ""
, dto.get_profile_username()
, dto.get_profile_email()
, dto.get_profile_type()
, ""
, dto.get_profile_gubun1()
, dto.get_profile_gubun2()
, dto.get_profile_speed()
, dto.get_profile_control()
, dto.get_profile_cnt()
, dto.get_profile_friend_cnt()
, dto.get_profile_new_cnt()
));
} else {
//Log.d("people_gram", "없음");
}
*/
}
people_adapter_list = new SubPeopleListAdapter(SubPeopleSearch_Activity.this, R.layout.sub_people_rowsearch_list, people_dto_list);
sf_people_list.setAdapter(people_adapter_list);
}
@Override
public void afterTextChanged(Editable s) {
}
};
serachET.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(serachET.getWindowToken(), 0);
//finish();
break;
default:
break;
}
return false;
}
});
serachET.addTextChangedListener(watcher);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_close_down_info, R.anim.slide_clode_up_info);
}
}
|
package com.airelogic.artistinfo.model;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class LyricsTest {
@Test
void countNumberOfWordsSimple() {
Lyrics lyrics = new Lyrics("One");
assertEquals(1, lyrics.countNumberOfWords());
}
@Test
void countNumberOfWordsSentence() {
Lyrics lyrics = new Lyrics("One two three four");
assertEquals(4, lyrics.countNumberOfWords());
}
@Test
void countNumberOfWordsDoubleSpaces() {
Lyrics lyrics = new Lyrics(" One two ");
assertEquals(2, lyrics.countNumberOfWords());
}
@Test
void countNumberOfWordsNewLines() {
Lyrics lyrics = new Lyrics("One\n\n\ntwo");
assertEquals(2, lyrics.countNumberOfWords());
}
@Test
void countNumberOfWordsMixed() {
Lyrics lyrics = new Lyrics(" \n\nOne\n\n \n\nTwo \n");
assertEquals(2, lyrics.countNumberOfWords());
}
} |
package classesState;
import lab6.Pessoa;
public class TomouPrimeiraDose extends EstadoVacinacao {
@Override
public void alteraEstado(Pessoa pessoa) {
pessoa.setEstadoVacinacao(new TomarSegundaDose());
pessoa.atualizaEstadoVacina(pessoa);
}
@Override
public String toString() {
return "A pessoa tomou a primeira dose";
}
}
|
import hw3.Experience;
/**
* @(#) Employee.java
*/
public abstract class Employee implements Comparable<Employee> {
private String name;
private String surname;
private Experience experience;
public int computeSalary( ) {
int additionalSalary = 0;
if (this.experience.equals(Experience.LOW)) {
additionalSalary = 200;
}
if (this.experience.equals(Experience.MEDIUM)) {
additionalSalary = 300;
}
if (this.experience.equals(Experience.HIGH)) {
additionalSalary = 400;
}
return additionalSalary;
}
public Employee( String name, String surname, Experience experience ) {
this.name = name;
this.surname = surname;
this.experience = experience;
}
public void increaseExperience( ) {
if (this.experience.equals(Experience.LOW)) {
this.experience = Experience.MEDIUM;
} else if (this.experience.equals(Experience.MEDIUM)) {
this.experience = Experience.HIGH;
}
}
public void setName( String name ) {
this.name = name;
}
public String getName( ) {
return name;
}
public void setSurname( String surname ) {
this.surname = surname;
}
public String getSurname( ) {
return surname;
}
public void setExperience( Experience experience ) {
this.experience = experience;
}
public Experience getExperience( ) {
return experience;
}
public abstract int getCostOfTraining( );
@Override
public int compareTo( Employee o ) {
if (this.experience.equals(o.experience))
return 0;
if ((this.experience.equals(Experience.LOW) && (o.experience
.equals(Experience.MEDIUM) || o.experience
.equals(Experience.HIGH)))
|| (this.experience.equals(Experience.MEDIUM) && o.experience
.equals(Experience.HIGH)))
return 1;
else
return -1;
}
} |
package com.testcases;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.BaseClass.BaseClass;
public class BankManagerLogin extends BaseClass{
@Test
public void LoginTest() {
click("bmlBtn_CSS");
Assert.assertTrue(isElementPresent("addCustomer_CSS")," login not sucess");
}
}
|
package com.ui.toto.toto.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.logging.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class DuckTestInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = Logger.getLogger(DuckTestInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
logger.info("================ Before Method");
return true;
}
@Override
public void postHandle( HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) {
logger.info("================ Method Executed");
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
logger.info("================ Method Completed");
}
}
|
package com.xinhua.api.domain.xinXXGBean;
import com.apsaras.aps.increment.domain.AbstractIncRequest;
import java.io.Serializable;
/**
* Created by lirs_wb on 2015/8/28.
*信息修改 请求
*/
public class XinXXGRequest extends AbstractIncRequest implements Serializable {
/**
* 银行交易日期
*/
private String bankDate;
/**
*银行交易时间
*/
private String transExeTime;
/**
*银行代码
*/
private String bankCode;
/**
*地区代码
*/
private String regionCode;
/**
*网点代码
*/
private String branch;
/**
*柜员代码
*/
private String teller;
/**
*交易流水号
*/
private String transRefGUID;
/**
*处理标志
*/
private String transType;
/**
*保险公司代码
*/
private String carrierCode;
/**
*银行交易渠道
*/
private String channel;
/**
*银行编码
*/
private String bankName;
/**
投保日期
*/
private String submissionDate;
/**
*缴费方式
*/
private String paymentMode;
/**
*缴费形式
*/
private String paymentMethod;
/**
*保单密码
*/
private String password;
/**
*账户姓名
*/
private String acctHolderName;
/**
*帐户类型
*/
private String bankAcctType;
/**
*银行账户 20字节
*/
private String accountNumber;
/**
*单证名称
*/
private String formName;
/**
*单证印刷号
*/
private String providerFormNumber;
/**
*投保人姓名
*/
private String tbrName;
/**
*投保人性别
*/
private String tbrSex;
/**
*投保人出生日期
*/
private String tbrBirth;
/**
*投保人证件类型
*/
private String tbrIdType;
/**
*投保人证件号码
*/
private String tbrIdNo;
/**
*投保人职业代码
*/
private String occupation_code;
/**
*投保人手机号码
*/
private String tbrMobile;
/**
*投保人地址
*/
private String tbrAddr;
/**
*投保人邮政编码
*/
private String tbrPostCode;
/**
*投保人与被保人关系
*/
private String tbrBbrRela;
/**
*被保人姓名
*/
private String bbrName;
/**
*被保人性别
*/
private String bbrSex;
/**
*被保人出生日期
*/
private String bbrBirth;
/**
*被保人证件类型
*/
private String bbrIdType;
/**
*被保人证件号码
*/
private String bbrIdNo;
/**
*被保人手机号码
*/
private String bbrMobile;
/**
*被保人邮政编码
*/
private String bbrPostCode;
/**
*投保人与被保人关系
*/
private String isdToPolH;
/**
*被保人告知版别
*/
private String tellerVer;
/**
*被保人告知编码
*/
private String tellerCode;
/**
*被保人告知内容
*/
private String tellerCont;
/**
*被保人告知备注
*/
private String tellerRemark;
/**
*受益人姓名
*/
private String syrName;
/**
*受益人性别
*/
private String syrSex;
/**
*受益人出生日期
*/
private String syrBirth;
/**
*受益人证件类型
*/
private String syrIdType;
/**
*受益人证件号码
*/
private String syrIdNo;
/**
*受益人手机号码
*/
private String cusCPhNo;
/**
*受益人办公电话
*/
private String cusOffPhNo;
/**
*受益人家庭电话
*/
private String cusFmyPhNo;
/**
*受益人地址
*/
private String syrAddr;
/**
*受益人邮寄地址
*/
private String cusPostAddr;
/**
*受益人邮寄邮编
*/
private String cusPostCode;
/**
*受益人与投保人关系
*/
private String bFToPolH;
/**
*受益人与被保人关系
*/
private String syrBbrRela;
/**
*当事人名称
*/
private String fullName;
/**
*当事人性别
*/
private String gender;
/**
*当事人出生日期
*/
private String birthDate;
/**
*当事人证件类型
*/
private String govtIDTC;
/**
*当事人证件号码
*/
private String govtID;
/**
*当事人电话类别
*/
private String phoneTypeCode;
/**
*当事人电话号码
*/
private String dialNumber;
/**
*当事人地址类别
*/
private String addressTypeCode;
/**
*当事人地址
*/
private String line1;
/**
*当事人地址邮编
*/
private String zip;
/**
*告知项目数
*/
private String tellInfoCount;
/**
*告知版别
*/
private String tellVersion;
/**
*告知编码
*/
private String tellCode;
/**
*告知内容
*/
private String tellContent;
/**
*告知备注
*/
private String tellRemark;
/**
*被关联方
*/
private String originatingObjectType;
/**
*关联方
*/
private String relatedObjectType;
/**
*关系代码
*/
private String relationRoleCode;
/**
* 用于无法处理的字段
*/
private String no;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getBankDate() {
return bankDate;
}
public void setBankDate(String bankDate) {
this.bankDate = bankDate;
}
public String getTransExeTime() {
return transExeTime;
}
public void setTransExeTime(String transExeTime) {
this.transExeTime = transExeTime;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getTeller() {
return teller;
}
public void setTeller(String teller) {
this.teller = teller;
}
public String getTransRefGUID() {
return transRefGUID;
}
public void setTransRefGUID(String transRefGUID) {
this.transRefGUID = transRefGUID;
}
public String getTransType() {
return transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public String getCarrierCode() {
return carrierCode;
}
public void setCarrierCode(String carrierCode) {
this.carrierCode = carrierCode;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getSubmissionDate() {
return submissionDate;
}
public void setSubmissionDate(String submissionDate) {
this.submissionDate = submissionDate;
}
public String getPaymentMode() {
return paymentMode;
}
public void setPaymentMode(String paymentMode) {
this.paymentMode = paymentMode;
}
public String getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(String paymentMethod) {
this.paymentMethod = paymentMethod;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAcctHolderName() {
return acctHolderName;
}
public void setAcctHolderName(String acctHolderName) {
this.acctHolderName = acctHolderName;
}
public String getBankAcctType() {
return bankAcctType;
}
public void setBankAcctType(String bankAcctType) {
this.bankAcctType = bankAcctType;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public String getProviderFormNumber() {
return providerFormNumber;
}
public void setProviderFormNumber(String providerFormNumber) {
this.providerFormNumber = providerFormNumber;
}
public String getTbrName() {
return tbrName;
}
public void setTbrName(String tbrName) {
this.tbrName = tbrName;
}
public String getTbrSex() {
return tbrSex;
}
public void setTbrSex(String tbrSex) {
this.tbrSex = tbrSex;
}
public String getTbrBirth() {
return tbrBirth;
}
public void setTbrBirth(String tbrBirth) {
this.tbrBirth = tbrBirth;
}
public String getTbrIdType() {
return tbrIdType;
}
public void setTbrIdType(String tbrIdType) {
this.tbrIdType = tbrIdType;
}
public String getTbrIdNo() {
return tbrIdNo;
}
public void setTbrIdNo(String tbrIdNo) {
this.tbrIdNo = tbrIdNo;
}
public String getOccupation_code() {
return occupation_code;
}
public void setOccupation_code(String occupation_code) {
this.occupation_code = occupation_code;
}
public String getTbrMobile() {
return tbrMobile;
}
public void setTbrMobile(String tbrMobile) {
this.tbrMobile = tbrMobile;
}
public String getTbrAddr() {
return tbrAddr;
}
public void setTbrAddr(String tbrAddr) {
this.tbrAddr = tbrAddr;
}
public String getTbrPostCode() {
return tbrPostCode;
}
public void setTbrPostCode(String tbrPostCode) {
this.tbrPostCode = tbrPostCode;
}
public String getTbrBbrRela() {
return tbrBbrRela;
}
public void setTbrBbrRela(String tbrBbrRela) {
this.tbrBbrRela = tbrBbrRela;
}
public String getBbrName() {
return bbrName;
}
public void setBbrName(String bbrName) {
this.bbrName = bbrName;
}
public String getBbrSex() {
return bbrSex;
}
public void setBbrSex(String bbrSex) {
this.bbrSex = bbrSex;
}
public String getBbrBirth() {
return bbrBirth;
}
public void setBbrBirth(String bbrBirth) {
this.bbrBirth = bbrBirth;
}
public String getBbrIdType() {
return bbrIdType;
}
public void setBbrIdType(String bbrIdType) {
this.bbrIdType = bbrIdType;
}
public String getBbrIdNo() {
return bbrIdNo;
}
public void setBbrIdNo(String bbrIdNo) {
this.bbrIdNo = bbrIdNo;
}
public String getBbrMobile() {
return bbrMobile;
}
public void setBbrMobile(String bbrMobile) {
this.bbrMobile = bbrMobile;
}
public String getBbrPostCode() {
return bbrPostCode;
}
public void setBbrPostCode(String bbrPostCode) {
this.bbrPostCode = bbrPostCode;
}
public String getIsdToPolH() {
return isdToPolH;
}
public void setIsdToPolH(String isdToPolH) {
this.isdToPolH = isdToPolH;
}
public String getTellerVer() {
return tellerVer;
}
public void setTellerVer(String tellerVer) {
this.tellerVer = tellerVer;
}
public String getTellerCode() {
return tellerCode;
}
public void setTellerCode(String tellerCode) {
this.tellerCode = tellerCode;
}
public String getTellerCont() {
return tellerCont;
}
public void setTellerCont(String tellerCont) {
this.tellerCont = tellerCont;
}
public String getTellerRemark() {
return tellerRemark;
}
public void setTellerRemark(String tellerRemark) {
this.tellerRemark = tellerRemark;
}
public String getSyrName() {
return syrName;
}
public void setSyrName(String syrName) {
this.syrName = syrName;
}
public String getSyrSex() {
return syrSex;
}
public void setSyrSex(String syrSex) {
this.syrSex = syrSex;
}
public String getSyrBirth() {
return syrBirth;
}
public void setSyrBirth(String syrBirth) {
this.syrBirth = syrBirth;
}
public String getSyrIdType() {
return syrIdType;
}
public void setSyrIdType(String syrIdType) {
this.syrIdType = syrIdType;
}
public String getSyrIdNo() {
return syrIdNo;
}
public void setSyrIdNo(String syrIdNo) {
this.syrIdNo = syrIdNo;
}
public String getCusCPhNo() {
return cusCPhNo;
}
public void setCusCPhNo(String cusCPhNo) {
this.cusCPhNo = cusCPhNo;
}
public String getCusOffPhNo() {
return cusOffPhNo;
}
public void setCusOffPhNo(String cusOffPhNo) {
this.cusOffPhNo = cusOffPhNo;
}
public String getCusFmyPhNo() {
return cusFmyPhNo;
}
public void setCusFmyPhNo(String cusFmyPhNo) {
this.cusFmyPhNo = cusFmyPhNo;
}
public String getSyrAddr() {
return syrAddr;
}
public void setSyrAddr(String syrAddr) {
this.syrAddr = syrAddr;
}
public String getCusPostAddr() {
return cusPostAddr;
}
public void setCusPostAddr(String cusPostAddr) {
this.cusPostAddr = cusPostAddr;
}
public String getCusPostCode() {
return cusPostCode;
}
public void setCusPostCode(String cusPostCode) {
this.cusPostCode = cusPostCode;
}
public String getbFToPolH() {
return bFToPolH;
}
public void setbFToPolH(String bFToPolH) {
this.bFToPolH = bFToPolH;
}
public String getSyrBbrRela() {
return syrBbrRela;
}
public void setSyrBbrRela(String syrBbrRela) {
this.syrBbrRela = syrBbrRela;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getGovtIDTC() {
return govtIDTC;
}
public void setGovtIDTC(String govtIDTC) {
this.govtIDTC = govtIDTC;
}
public String getGovtID() {
return govtID;
}
public void setGovtID(String govtID) {
this.govtID = govtID;
}
public String getPhoneTypeCode() {
return phoneTypeCode;
}
public void setPhoneTypeCode(String phoneTypeCode) {
this.phoneTypeCode = phoneTypeCode;
}
public String getDialNumber() {
return dialNumber;
}
public void setDialNumber(String dialNumber) {
this.dialNumber = dialNumber;
}
public String getAddressTypeCode() {
return addressTypeCode;
}
public void setAddressTypeCode(String addressTypeCode) {
this.addressTypeCode = addressTypeCode;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getTellInfoCount() {
return tellInfoCount;
}
public void setTellInfoCount(String tellInfoCount) {
this.tellInfoCount = tellInfoCount;
}
public String getTellVersion() {
return tellVersion;
}
public void setTellVersion(String tellVersion) {
this.tellVersion = tellVersion;
}
public String getTellCode() {
return tellCode;
}
public void setTellCode(String tellCode) {
this.tellCode = tellCode;
}
public String getTellContent() {
return tellContent;
}
public void setTellContent(String tellContent) {
this.tellContent = tellContent;
}
public String getTellRemark() {
return tellRemark;
}
public void setTellRemark(String tellRemark) {
this.tellRemark = tellRemark;
}
public String getOriginatingObjectType() {
return originatingObjectType;
}
public void setOriginatingObjectType(String originatingObjectType) {
this.originatingObjectType = originatingObjectType;
}
public String getRelatedObjectType() {
return relatedObjectType;
}
public void setRelatedObjectType(String relatedObjectType) {
this.relatedObjectType = relatedObjectType;
}
public String getRelationRoleCode() {
return relationRoleCode;
}
public void setRelationRoleCode(String relationRoleCode) {
this.relationRoleCode = relationRoleCode;
}
@Override
public String toString() {
return "XinXXGRequest{" +
"bankDate='" + bankDate + '\'' +
", transExeTime='" + transExeTime + '\'' +
", bankCode='" + bankCode + '\'' +
", regionCode='" + regionCode + '\'' +
", branch='" + branch + '\'' +
", teller='" + teller + '\'' +
", transRefGUID='" + transRefGUID + '\'' +
", transType='" + transType + '\'' +
", carrierCode='" + carrierCode + '\'' +
", channel='" + channel + '\'' +
", bankName='" + bankName + '\'' +
", submissionDate='" + submissionDate + '\'' +
", paymentMode='" + paymentMode + '\'' +
", paymentMethod='" + paymentMethod + '\'' +
", password='" + password + '\'' +
", acctHolderName='" + acctHolderName + '\'' +
", bankAcctType='" + bankAcctType + '\'' +
", accountNumber='" + accountNumber + '\'' +
", formName='" + formName + '\'' +
", providerFormNumber='" + providerFormNumber + '\'' +
", tbrName='" + tbrName + '\'' +
", tbrSex='" + tbrSex + '\'' +
", tbrBirth='" + tbrBirth + '\'' +
", tbrIdType='" + tbrIdType + '\'' +
", tbrIdNo='" + tbrIdNo + '\'' +
", occupation_code='" + occupation_code + '\'' +
", tbrMobile='" + tbrMobile + '\'' +
", tbrAddr='" + tbrAddr + '\'' +
", tbrPostCode='" + tbrPostCode + '\'' +
", tbrBbrRela='" + tbrBbrRela + '\'' +
", bbrName='" + bbrName + '\'' +
", bbrSex='" + bbrSex + '\'' +
", bbrBirth='" + bbrBirth + '\'' +
", bbrIdType='" + bbrIdType + '\'' +
", bbrIdNo='" + bbrIdNo + '\'' +
", bbrMobile='" + bbrMobile + '\'' +
", bbrPostCode='" + bbrPostCode + '\'' +
", isdToPolH='" + isdToPolH + '\'' +
", tellerVer='" + tellerVer + '\'' +
", tellerCode='" + tellerCode + '\'' +
", tellerCont='" + tellerCont + '\'' +
", tellerRemark='" + tellerRemark + '\'' +
", syrName='" + syrName + '\'' +
", syrSex='" + syrSex + '\'' +
", syrBirth='" + syrBirth + '\'' +
", syrIdType='" + syrIdType + '\'' +
", syrIdNo='" + syrIdNo + '\'' +
", cusCPhNo='" + cusCPhNo + '\'' +
", cusOffPhNo='" + cusOffPhNo + '\'' +
", cusFmyPhNo='" + cusFmyPhNo + '\'' +
", syrAddr='" + syrAddr + '\'' +
", cusPostAddr='" + cusPostAddr + '\'' +
", cusPostCode='" + cusPostCode + '\'' +
", bFToPolH='" + bFToPolH + '\'' +
", syrBbrRela='" + syrBbrRela + '\'' +
", fullName='" + fullName + '\'' +
", gender='" + gender + '\'' +
", birthDate='" + birthDate + '\'' +
", govtIDTC='" + govtIDTC + '\'' +
", govtID='" + govtID + '\'' +
", phoneTypeCode='" + phoneTypeCode + '\'' +
", dialNumber='" + dialNumber + '\'' +
", addressTypeCode='" + addressTypeCode + '\'' +
", line1='" + line1 + '\'' +
", zip='" + zip + '\'' +
", tellInfoCount='" + tellInfoCount + '\'' +
", tellVersion='" + tellVersion + '\'' +
", tellCode='" + tellCode + '\'' +
", tellContent='" + tellContent + '\'' +
", tellRemark='" + tellRemark + '\'' +
", originatingObjectType='" + originatingObjectType + '\'' +
", relatedObjectType='" + relatedObjectType + '\'' +
", relationRoleCode='" + relationRoleCode + '\'' +
", no='" + no + '\'' +
'}';
}
}
|
package com.udomomo.blackjack.card;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ScoreTest {
@Test
void totalScoreWithoutFace() {
List<Card> cards = new ArrayList<>(Arrays.asList(new Card(Suit.Club, 7), new Card(Suit.Heart, 5)));
List<Integer> totalScore = Score.totalScore(cards);
assertEquals(1, totalScore.size());
assertTrue(totalScore.contains(Integer.parseInt("12")));
}
@Test
void totalScoreWithFace() {
// The rank of 11, 12, 13 are regarded as 10 points.
List<Card> cards = new ArrayList<>(Arrays.asList(new Card(Suit.Club, 3), new Card(Suit.Heart, 12)));
List<Integer> totalScore = Score.totalScore(cards);
assertEquals(1, totalScore.size());
assertTrue(totalScore.contains(Integer.parseInt("13")));
}
@Test
void totalScoreWithAce() {
// The rank of Ace is regarded as 1 or 11 points.
// totalScore() returns all possible scores, except busting ones.
List<Card> cards = new ArrayList<>(
Arrays.asList(new Card(Suit.Club, 3), new Card(Suit.Heart, 1), new Card(Suit.Diamond, 1)));
List<Integer> totalScore = Score.totalScore(cards);
assertEquals(2, totalScore.size());
assertTrue(totalScore.contains(Integer.parseInt("5")));
assertTrue(totalScore.contains(Integer.parseInt("15")));
}
@Test
void totalScoreWithAllBust() {
// If the score is busting in any case, totalScore() returns an empty list.
List<Card> cards = new ArrayList<>(
Arrays.asList(new Card(Suit.Club, 10), new Card(Suit.Heart, 9), new Card(Suit.Diamond, 8)));
List<Integer> totalScore = Score.totalScore(cards);
assertTrue(totalScore.isEmpty());
}
}
|
package com.xnarum.thonline.entity.idd011;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class HajjFlightScheduleQueryResponseBody {
@XmlElement(name="THName", nillable=true)
private String name;
@XmlElement(name="THAcct", nillable=true)
private String accountNo;
@XmlElement(name="THICNo", nillable=true)
private String icNo;
@XmlElement(name="THFltNoAwy", nillable=true)
private String departureFlightNo;
@XmlElement(name="THFltNoRet", nillable=true)
private String returnFlightNo;
@XmlElement(name="THPlaneNoAwy", nillable=true)
private String departurePlaneNo;
@XmlElement(name="THPlaneNoRet", nillable=true)
private String returnPlaneNo;
@XmlElement(name="THChkInLocAwy", nillable=true)
private String departureCheckinLocation;
@XmlElement(name="THChkInLocRet", nillable=true)
private String returnCheckinLocation;
@XmlElement(name="THChkInDateAwy", nillable=true)
private String departureCheckinDate;
@XmlElement(name="THChkInDateRet", nillable=true)
private String returnCheckinDate;
@XmlElement(name="THChkInTimeAwy", nillable=true)
private String departureCheckinTime;
@XmlElement(name="THChkInTimeRet", nillable=true)
private String returnCheckinTime;
@XmlElement(name="THDuration", nillable=true)
private String totalDaysAtHolyLand;
@XmlElement(name="THBroughtTo", nillable=true)
private String firstBroughtTo;
@XmlElement(name="THIhram", nillable=true)
private String ihramInMiqat;
@XmlElement(name="THDateArrival", nillable=true)
private String arrivalDate;
@XmlElement(name="THTimeArrival", nillable=true)
private String arrivalTime;
@XmlElement(name="THAirport", nillable=true)
private String airportCode;
@XmlElement(name="PDFLetter", nillable=true)
private byte [] pdfLetter;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcNo() {
return icNo;
}
public void setIcNo(String icNo) {
this.icNo = icNo;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getDepartureFlightNo() {
return departureFlightNo;
}
public void setDepartureFlightNo(String departureFlightNo) {
this.departureFlightNo = departureFlightNo;
}
public String getReturnFlightNo() {
return returnFlightNo;
}
public void setReturnFlightNo(String returnFlightNo) {
this.returnFlightNo = returnFlightNo;
}
public String getDeparturePlaneNo() {
return departurePlaneNo;
}
public void setDeparturePlaneNo(String departurePlaneNo) {
this.departurePlaneNo = departurePlaneNo;
}
public String getReturnPlaneNo() {
return returnPlaneNo;
}
public void setReturnPlaneNo(String returnPlaneNo) {
this.returnPlaneNo = returnPlaneNo;
}
public String getDepartureCheckinLocation() {
return departureCheckinLocation;
}
public void setDepartureCheckinLocation(String departureCheckinLocation) {
this.departureCheckinLocation = departureCheckinLocation;
}
public String getReturnCheckinLocation() {
return returnCheckinLocation;
}
public void setReturnCheckinLocation(String returnCheckinLocation) {
this.returnCheckinLocation = returnCheckinLocation;
}
public String getDepartureCheckinDate() {
return departureCheckinDate;
}
public void setDepartureCheckinDate(String departureCheckinDate) {
this.departureCheckinDate = departureCheckinDate;
}
public String getReturnCheckinDate() {
return returnCheckinDate;
}
public void setReturnCheckinDate(String returnCheckinDate) {
this.returnCheckinDate = returnCheckinDate;
}
public String getDepartureCheckinTime() {
return departureCheckinTime;
}
public void setDepartureCheckinTime(String departureCheckinTime) {
this.departureCheckinTime = departureCheckinTime;
}
public String getReturnCheckinTime() {
return returnCheckinTime;
}
public void setReturnCheckinTime(String returnCheckinTime) {
this.returnCheckinTime = returnCheckinTime;
}
public String getTotalDaysAtHolyLand() {
return totalDaysAtHolyLand;
}
public void setTotalDaysAtHolyLand(String totalDaysAtHolyLand) {
this.totalDaysAtHolyLand = totalDaysAtHolyLand;
}
public String getFirstBroughtTo() {
return firstBroughtTo;
}
public void setFirstBroughtTo(String firstBroughtTo) {
this.firstBroughtTo = firstBroughtTo;
}
public String getIhramInMiqat() {
return ihramInMiqat;
}
public void setIhramInMiqat(String ihramInMiqat) {
this.ihramInMiqat = ihramInMiqat;
}
public String getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getAirportCode() {
return airportCode;
}
public void setAirportCode(String airportCode) {
this.airportCode = airportCode;
}
public byte[] getPdfLetter() {
return pdfLetter;
}
public void setPdfLetter(byte[] pdfLetter) {
this.pdfLetter = pdfLetter;
}
}
|
package ForLoop;
//Print 1-2+3-4...10
public class Series3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=1;i<=10;i++)
{
if(i%2==0)
System.out.print("-"+i);
else if (i==1)
System.out.print(i);
else
System.out.print("+"+i);
}
}
}
|
package Familia;
import POO.Adulto;
import POO2.Humano;
public interface Familia {
Adulto getPadre();
Adulto getMadre();
Humano[] getHijos();
Adulto[] getTios();
Adulto[] getAbuelas();
Adulto[] getAbuelos();
void ejecutarAccion();
}
|
package com.sheygam.loginarchitectureexample.business.contactList;
import com.sheygam.loginarchitectureexample.data.dao.Contact;
import java.util.List;
import io.reactivex.Single;
/**
* Created by Gleb on 16.02.2018.
*/
public interface IContactsListInteractor {
Single<List<Contact>> loadList();
void logout();
}
|
package com.EmployeeManag.service;
import java.util.List;
import com.EmployeeManag.entity.Employee;
public interface EmployeeServiceInterface {
Employee addEmployee(Employee employee);
List<Employee> getEmployees();
Employee getEmployee(int id);
Employee editEmployee(Employee employee);
String deleteEmployee(int id);
}
|
package com.git.cloud.workflow.webservice;
import javax.jws.WebService;
/**
* 调用工作流对应web service接口类
* @author yangtao
* @version 1.0 2014-09-17
*/
@WebService(name = "IBpmWebService", targetNamespace = "http://com.git.workflow.webservice")
public interface IBpmWebService {
/**
* 流程发布
* @param fileXML 流程 xml 定义
* @return 流程定义的ID和节点的ID集合
*/
public String deployProcessDefinition(byte[] processDefinitionXML);
/**
* 创建流程实例
* @param processDefinitionId 流程定义的ID
* @param uid 用户ID
* @return 流程实例ID
*/
public long buildProcessInstance(long processDefinitionId,String uid);
/**
* 根据服务请求信息创建流程实例
* @param processDefinitionId 流程模板ID
* @param uid 用户ID
* @param params 参数key-value
* @return
*/
public long buildProcessInstanceFromReq(long processDefinitionId,String uid,String params);
/**
* 启动流程实例
* @param processInstanceID 流程实例ID
* @param businessInstanceID 业务流程实例ID
* @return
*/
public boolean startProcessInstance(long processInstanceID,String instanceID,String params);
/**
* 启动流程实例
* @param processDefinitionId 工作流定义的流程实例ID
* @param instanceId 业务定义的流程实例ID
* @param params 流程实例参数
* @return 创建成功与否的标识
*/
public String startProcessInstanceInConsole(long processInstanceId,String instanceId,String params);
/**
* 根据TokenId 驱动流程向下流转
* @param tokenId 流程实例令牌ID
* @return
*/
public String signalAutoTask(long tokenId);
/**
* 强制结束流程实例
* @param instanceId 流程实例Id
* @return
*/
public String forceEndProcessInstance(long instanceId);
/**
* 根据工作流节点id获取 token id
* @param nodeId 工作流节点Id
* @param instanceId 工作流实例Id
* @return
*/
public Long getTokenIdByNode(long nodeId,long instanceId);
/**
* 添加流程全部变量
* @param jsonData
* @param processInstanceId 流程实例Id
* @return
*/
public String setWorkFlowGlobalParams(String jsonData,long processInstanceId);
/**
* 根据工作流节点id获取 token id 并向下流转
* @param nodeId 工作流节点Id
* @param processInstanceId 工作流实例Id
* @return
*/
public String getTokenIdByNodeAndSignal(long nodeId,long processInstanceId);
/**
* 提交人工任务
* @param taskId 任务ID
* @return
*/
public String commitTaskById(long taskId);
/**
* 同意人工任务
* @param taskId 任务ID
* @param nodeId 节点ID
* @return
*/
public String agreeTask(long taskId,long nodeId);
/**
* 驳回人工任务
* @param taskId 任务ID
* @param nodeId 节点ID
* @return
*/
public String disagreeTask(long taskId,long nodeId);
/**
* 同意自动任务
* @param taskId 任务ID
* @param nodeId 节点ID
* @return
*/
public String agreeAutoNode(long tokenId,long nodeId);
/**
* 驳回自动任务
* @param taskId 任务ID
* @param nodeId 节点ID
* @return
*/
public String disagreeAutoNode(long tokenId,long nodeId);
/**
* 插入单个工作流全局参数
* @param processInstanceId 工作流实例id
* @param keyName 参数key
* @param keyValue 参数值
* @return
*/
public String setProcessGlobalParams(String keyName,String keyValue,long processInstanceId);
/**
* 任意流转
* @param processDefinitionId
* @param processInstanceId
* @param wfNodeName
* @return
*/
public String getUnlimitedTurn(Long processDefinitionId,Long processInstanceId,Long wfNodeId,Long sourceNodeId);
public String getUnlimitedTurnTokenId(Long processDefinitionId,Long processInstanceId,Long wfNodeId,Long sourceNodeId,Long tokenId);
/**
* 聚合任务取消
* @param instanceId
* @param wfNodeId
* @param tokenId
* @return
*/
public String joinTaskCancle(long instanceId,long wfNodeId,long tokenId);
}
|
package com.mysql.test;
import java.sql.Connection;
import jdbctools.JdbcTools;
public class TestConnection {
public static void main(String[] args) {
Connection connection=null;
connection=JdbcTools.getConnection();
System.out.println(connection);
}
}
|
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class SecretaryTest {
@Test
void getChanges() {
List<Soldier> general1Soldiers=new ArrayList<>();
general1Soldiers.add(new Soldier(Soldier.MilitaryDegree.CAPTAIN,1));
general1Soldiers.add(new Soldier(Soldier.MilitaryDegree.CAPTAIN,2));
General general1=new General("Jacek", 500, general1Soldiers);
List<Soldier> general2Soldiers=new ArrayList<>();
general2Soldiers.add(new Soldier(Soldier.MilitaryDegree.CAPTAIN,1));
general2Soldiers.add(new Soldier(Soldier.MilitaryDegree.CAPTAIN,2));
general2Soldiers.add(new Soldier(Soldier.MilitaryDegree.PRIVATE,4));
General general2=new General("Jan", 500, general2Soldiers);
List<General> generals=new ArrayList<>();
generals.add(general1);
generals.add(general2);
Secretary secretary=new Secretary(generals);
general1.buySoldier(Soldier.MilitaryDegree.CAPTAIN);
general1.training(general1Soldiers);
general1.goToWar(general2);
assertEquals("------------------------------------------------------\n" +
"ZMIANY U GENERALA: Jacek\n" +
"BEFORE: Gold: 500\n" +
"AFTER: Gold: 511\n" +
"BEFORE: Power: 9\n" +
"AFTER: Power: 30\n" +
"BEFORE: Soldier number 0 - Degree: CAPTAIN Experience: 1\n" +
"AFTER: Soldier number 0 - Degree: CAPTAIN Experience: 3\n" +
"BEFORE: Soldier number 1 - Degree: CAPTAIN Experience: 2\n" +
"AFTER: Soldier number 1 - Degree: CAPTAIN Experience: 4\n" +
"AFTER: Soldier number 2 - Degree: CAPTAIN Experience: 3\n" +
"\n" +
"\n" +
"PODJĘTE DZIALANIA OD POCZĄTKU:\n" +
"\n" +
"Zakup żołnierza CAPTAIN\n" +
"Szkolenie żołnierzy 3\n" +
"Wojna z generałem Jan\n" +
"------------------------------------------------------\n" +
"\n" +
"------------------------------------------------------\n" +
"ZMIANY U GENERALA: Jan\n" +
"BEFORE: Gold: 500\n" +
"AFTER: Gold: 450\n" +
"BEFORE: Power: 13\n" +
"AFTER: Power: 6\n" +
"BEFORE: Soldier number 0 - Degree: CAPTAIN Experience: 1\n" +
"AFTER: Soldier number 0 - DEAD\n" +
"BEFORE: Soldier number 1 - Degree: CAPTAIN Experience: 2\n" +
"AFTER: Soldier number 1 - Degree: CAPTAIN Experience: 1\n" +
"BEFORE: Soldier number 2 - Degree: PRIVATE Experience: 4\n" +
"AFTER: Soldier number 2 - Degree: PRIVATE Experience: 3\n" +
"\n" +
"\n" +
"PODJĘTE DZIALANIA OD POCZĄTKU:\n" +
"\n" +
"Wojna z generałem Jan\n" +
"------------------------------------------------------\n" +
"\n",secretary.getChanges(),"Drukowanie zmian i podjętych działań");
}
} |
package com.Exam.dto;
import java.util.Date;
public class ProductDTO {
int maSP;
String tenSP;
int donGia;
String donVi;
public int getMaSP() {
return maSP;
}
public void setMaSP(int maSP) {
this.maSP = maSP;
}
public String getTenSP() {
return tenSP;
}
public void setTenSP(String tenSP) {
this.tenSP = tenSP;
}
public int getDonGia() {
return donGia;
}
public void setDonGia(int donGia) {
this.donGia = donGia;
}
public String getDonVi() {
return donVi;
}
public void setDonVi(String donVi) {
this.donVi = donVi;
}
public ProductDTO() {
super();
}
public ProductDTO(int maSP, String tenSP, int donGia, String donVi, int soLuong) {
super();
this.maSP = maSP;
this.tenSP = tenSP;
this.donGia = donGia;
this.donVi = donVi;
}
}
|
package Problem_17406;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int[][] arr;
static int[][] map;
static int N;
static int M;
static int K;
static int[][] rotate;
static int answer = Integer.MAX_VALUE;
static boolean[] isvisited;
public static void getAnswer() {
for (int i = 1; i <= N; i++) {
int sum = 0;
for (int j = 1; j <= M; j++) {
sum += arr[i][j];
}
answer = answer > sum ? sum : answer;
}
}
public static void solution(int num) {
int[][] temp = new int[N+1][M+1];
for(int i = 1; i<=N;i++) {
for(int j = 1; j<=M;j++) {
temp[i][j] = arr[i][j];
}
}
if(num == K) {
getAnswer();
return;
}
else {
for(int i = 0; i <K ; i++) {
if(!isvisited[i]) {
rotate(rotate[i][0], rotate[i][1], rotate[i][2]);
isvisited[i] = true;
solution(num+1);
isvisited[i] = false;
for(int k = 1; k<=N;k++) {
for(int j = 1; j<=M;j++) {
arr[k][j] = temp[k][j];
}
}
}
}
}
}
public static void init() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
arr[i][j] = map[i][j];
}
}
}
public static void print() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
System.out.printf("%d\t", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] temp = br.readLine().split(" ");
N = Integer.parseInt(temp[0]);
M = Integer.parseInt(temp[1]);
K = Integer.parseInt(temp[2]);
arr = new int[N + 1][M + 1];
map = new int[N + 1][M + 1];
rotate = new int[K][3];
isvisited = new boolean[K];
for (int i = 1; i <= N; i++) {
temp = br.readLine().split(" ");
for (int j = 1; j <= M; j++) {
arr[i][j] = Integer.parseInt(temp[j - 1]);
map[i][j] = arr[i][j];
}
}
for (int i = 0; i < K; i++) {
temp = br.readLine().split(" ");
rotate[i][0] = Integer.parseInt(temp[0]);
rotate[i][1] = Integer.parseInt(temp[1]);
rotate[i][2] = Integer.parseInt(temp[2]);
}
solution(0);
System.out.println(answer);
}
public static void rotate(int r, int c, int s) {
for (int k = 1; k <= s; k++) {
int temp = arr[r - k][c - k]; // 왼쪽 상단의 값 temp에 저장
for (int i = r - k; i < r + k; i++) // 왼쪽 상단 --> 왼쪽 하단
arr[i][c - k] = arr[i + 1][c - k];
for (int j = c - k; j < c + k; j++) // 왼쪽 하단 --> 오른쪽 하단
arr[r + k][j] = arr[r + k][j + 1];
for (int i = r + k; i > r - k; i--) // 오른쪽 하단 --> 오른쪽 상단
arr[i][c + k] = arr[i - 1][c + k];
for (int j = c + k; j > c - k; j--) // 오른쪽 상단 --> 왼쪽 상단
arr[r - k][j] = arr[r - k][j - 1];
arr[r - k][c - k + 1] = temp;
}
}
}
|
package services.users;
import java.sql.SQLException;
import java.util.List;
import userdao.AuthDAO;
import userdao.RolesDAO;
import userdao.UserDAO;
import userdaoimp.AuthDaoImpl;
import userdaoimp.NotificationDaoImpl;
import userdaoimp.RoleDaoImpl;
import userdaoimp.UserDaoImpl;
import admin.dao.NotificationsDAO;
import bean.bookbean.BookBean;
import bean.bookbean.BookIssueBean;
import bean.users.AuthBean;
import bean.users.NotificationBean;
import bean.users.RolesBean;
import bean.users.UserBean;
public class UserService {
private UserDAO userDAO = new UserDaoImpl();
private AuthDAO authDAO = new AuthDaoImpl();
private RolesDAO roleDAO = new RoleDaoImpl();
private NotificationsDAO nDAO = new NotificationDaoImpl();
public int insert(UserBean c) throws ClassNotFoundException, SQLException {
return userDAO.insert(c);
}
public int update(int id, UserBean c) throws ClassNotFoundException, SQLException {
return userDAO.update(id, c);
}
public int delete(int id) throws ClassNotFoundException, SQLException {
return userDAO.delete(id);
}
public int softDelete(int id) throws ClassNotFoundException, SQLException {
return userDAO.softDelete(id);
}
public List<UserBean> getAll() throws ClassNotFoundException, SQLException {
return userDAO.getAll();
}
public UserBean getById(int id) throws ClassNotFoundException, SQLException {
return userDAO.getById(id);
}
public AuthBean getByEmail(String email) throws ClassNotFoundException, SQLException {
return authDAO.getByEmail(email);
}
public RolesBean getRoleById(int id) throws ClassNotFoundException, SQLException {
return roleDAO.getById(id);
}
public AuthBean getByEmailAndPass(String email, String password) throws ClassNotFoundException, SQLException {
return authDAO.getByEmailAndPass(email, password);
}
public int requestBook(BookIssueBean i) throws ClassNotFoundException, SQLException {
return userDAO.requestBook(i);
}
public BookIssueBean getBookIssueById(int id) throws ClassNotFoundException, SQLException {
return userDAO.getBookIssueById(id);
}
public BookIssueBean getBookIssueRequestByBookId(int id, int approve) throws ClassNotFoundException, SQLException {
return userDAO.getBookIssueRequestByBookId(id, approve);
}
public BookIssueBean getBookIssueRequestByBookIdUserId(int id, int userId,int approve) throws ClassNotFoundException, SQLException {
return userDAO.getBookIssueRequestByBookIdUserId(id, userId,approve);
}
public int removeRequestBookByBookBeanUserBean(BookBean b, UserBean ub) throws ClassNotFoundException, SQLException {
return userDAO.removeRequestBookByBookBeanUserBean(b, ub);
}
public Long getBookIssueLimit(UserBean user) throws ClassNotFoundException, SQLException{
return userDAO.getBookIssueLimit(user);
}
public BookIssueBean getBookIssueRequestByBookBeanUserBean(BookBean id, UserBean userId,int approve, String status) throws ClassNotFoundException, SQLException {
return userDAO.getBookIssueRequestByBookBeanUserBean(id, userId,approve, status);
}
public List<NotificationBean> getAllNotificationByUser(UserBean ub){
return nDAO.getAllNotificationByUser(ub);
}
public AuthBean getEmailByUser(UserBean ub) throws ClassNotFoundException, SQLException{
return authDAO.getEmailByUser(ub);
}
public List<UserBean> getAllUsersByKeyWord(String keyWord) throws ClassNotFoundException, SQLException {
return userDAO.searchUserByKeyWord(keyWord);
}
public int insertNotification(NotificationBean nb) throws ClassNotFoundException, SQLException{
return nDAO.insert(nb);
}
public Long getNotificationsCount(UserBean ub){
return nDAO.getNotificationsCount(ub);
}
public int updateNotificationAsRead(int id, NotificationBean bean) throws ClassNotFoundException, SQLException {
return nDAO.updateStatus(id, bean);
}
public int softDeleteNotification(int id) throws ClassNotFoundException, SQLException{
return nDAO.softDeleteNotification(id);
}
}
|
package com.example.adivinanumero;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int numeroMachine = (int) (Math.random() * 10) + 1;
int cont = 0;
// contador
TextView boxCont;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mbtnPlay = findViewById(R.id.btnPlay);
boxCont = findViewById(R.id.boxTxtPlays);
final TextView resRecord = findViewById(R.id.boxTxtRecord);
//Mostramos el record actual:
SharedPreferences prefs = getSharedPreferences("recordPersonal", Context.MODE_PRIVATE);
int record_actual = prefs.getInt("recordPersonal", 10000);
if (record_actual>=10000)
resRecord.setText("Aun no hay record");
else
resRecord.setText(String.format("Tu record es %d", record_actual));
final EditText minputNumber = findViewById(R.id.inputNumber);
mbtnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cont++;
boxCont.setText(String.format("Número de intentos %s", cont));
Log.e("MainActivity", "" + numeroMachine);
String textoNum = minputNumber.getText().toString();
int numberUser = Integer.parseInt(textoNum);
String msg = "";
if (numberUser == numeroMachine) {
msg = "Has acertado el número";
boxCont.setText(String.format("Has acertado a los %s intentos \n Introduce otro número para seguir jugando.", cont));
//Leer si hay un record ya guardado:
SharedPreferences prefs = getSharedPreferences("recordPersonal", Context.MODE_PRIVATE);
int record_actual = prefs.getInt("recordPersonal", 10000);
//Comprobar si lo hemos mejorado:
if (cont < record_actual) {
//Hay un nuevo record
resRecord.setText(String.format("Tu record es %d", cont));
//Guardar en las preferencias el nuevo record:
prefs.edit().putInt("recordPersonal", cont).apply();
}
//Inventamos nuevo numero para la siguiente partida:
numeroMachine = (int) (Math.random() * 10) + 1;
Log.e("MainActivity", "" + numeroMachine);
//Volvemos a poner intentos a cero para la nueva partida
cont = 0;
} else {
msg = "No has acertado el número";
}
minputNumber.setText("");
Toast.makeText(MainActivity.this,
String.format("Respuesta %s", msg), Toast.LENGTH_SHORT).show();
}
});
}
}
|
package rdfsynopsis.test;
import static org.junit.Assert.assertEquals;
import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import rdfsynopsis.analyzer.Analyzer;
import rdfsynopsis.analyzer.TripleStreamAnalyzer;
import rdfsynopsis.dataset.InMemoryDataset;
import rdfsynopsis.statistics.ClassHierarchy;
import rdfsynopsis.statistics.OntologyRatio;
import rdfsynopsis.util.Namespace;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.vocabulary.FOAF;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.VCARD;
public class OntologyRatioTest {
InMemoryDataset ds;
Logger log = Logger.getLogger(OntologyRatioTest.class);
Namespace exampleNs = new Namespace("ex", "http://example.com/");
Resource maxRes;
Resource petraRes;
@Before
public void setUpBefore() throws Exception {
ds = new InMemoryDataset();
Model m = ds.getModel();
String maxMusterName = "Maximilian Mustermann";
String petraMusterName = "Petra Mustermann";
String maxUri = "http://example.com/MaxMustermann";
String petraUri = "http://example.com/PetraMustermann";
// add two literals, first with datatype String (implicit in addLiteral())
maxRes = m.createResource(maxUri).addLiteral(VCARD.FN, maxMusterName);
petraRes = m.createResource(petraUri).addProperty(VCARD.FN, petraMusterName);
petraRes.addProperty(FOAF.knows, maxRes);
maxRes.addProperty(FOAF.knows, petraRes);
// output graph for debugging
StringWriter out = new StringWriter();
m.write(out, "TTL");
log.debug(out.toString());
}
@Test
public void noOntology() {
OntologyRatio or = new OntologyRatio();
or.processSparqlDataset(ds);
double delta = 0.0000001;
assertEquals(0.0, or.getOntologyRatio(), delta);
}
@Test
public void simpleOntology() {
OntologyRatio or = new OntologyRatio();
Model m = ds.getModel();
Resource manClass = m.createResource(exampleNs.getFullTerm("Man"));
Resource womanClass = m.createResource(exampleNs.getFullTerm("Woman"));
// class instantiation
m.add(maxRes, RDF.type, manClass);
m.add(petraRes, RDF.type, womanClass);
m.add(maxRes, RDF.type, FOAF.Person);
m.add(petraRes, RDF.type, FOAF.Person);
// class hierarchy
m.add(manClass, RDFS.subClassOf, FOAF.Person);
m.add(womanClass, RDFS.subClassOf, FOAF.Person);
// class definitions
m.add(womanClass, RDF.type, RDFS.Class);
m.add(womanClass, RDF.type, OWL.Class);
m.add(manClass, RDF.type, RDFS.Class);
m.add(manClass, RDF.type, OWL.Class);
m.add(FOAF.Person, RDF.type, RDFS.Class);
// property definitions
m.add(RDF.type, RDF.type, RDF.Property);
m.add(RDFS.subClassOf, RDF.type, RDF.Property);
or.processSparqlDataset(ds);
// 2 non-term resources: ex:MaxMustermann, ex:PetraMustermann
// 5 term resources: ex:Woman, ex:Man, foaf:Person, rdf:type, rdfs:subClassOf
// OntologyRatio = 5/7
double delta = 0.0000001;
assertEquals(5.0/7.0, or.getOntologyRatio(), delta);
}
@Test
public void noOntologyTripleStream() {
OntologyRatio or = new OntologyRatio();
Analyzer tsa = new TripleStreamAnalyzer(ds)
.addCriterion(or);
tsa.performAnalysis(null);
double delta = 0.0000001;
assertEquals(0.0, or.getOntologyRatio(), delta);
}
@Test
public void simpleOntologyTripleStream() {
OntologyRatio or = new OntologyRatio();
Model m = ds.getModel();
Resource manClass = m.createResource(exampleNs.getFullTerm("Man"));
Resource womanClass = m.createResource(exampleNs.getFullTerm("Woman"));
// class instantiation
m.add(maxRes, RDF.type, manClass);
m.add(petraRes, RDF.type, womanClass);
m.add(maxRes, RDF.type, FOAF.Person);
m.add(petraRes, RDF.type, FOAF.Person);
// class hierarchy
m.add(manClass, RDFS.subClassOf, FOAF.Person);
m.add(womanClass, RDFS.subClassOf, FOAF.Person);
// class definitions
m.add(womanClass, RDF.type, RDFS.Class);
m.add(womanClass, RDF.type, OWL.Class);
m.add(manClass, RDF.type, RDFS.Class);
m.add(manClass, RDF.type, OWL.Class);
m.add(FOAF.Person, RDF.type, RDFS.Class);
// property definitions
m.add(RDF.type, RDF.type, RDF.Property);
m.add(RDFS.subClassOf, RDF.type, RDF.Property);
Analyzer tsa = new TripleStreamAnalyzer(ds)
.addCriterion(or);
tsa.performAnalysis(null);
// 2 non-term resources: ex:MaxMustermann, ex:PetraMustermann
// 5 term resources: ex:Woman, ex:Man, foaf:Person, rdf:type, rdfs:subClassOf
// OntologyRatio = 5/7
double delta = 0.0000001;
assertEquals(5.0/7.0, or.getOntologyRatio(), delta);
}
}
|
package design_pattern.singleton;
public class B_EagerInitiWithStaticBlock {
private static B_EagerInitiWithStaticBlock instance;
// static block enables to handle exception
static {
try {
System.out.println("Thread Name: " + Thread.currentThread().getName());
instance = new B_EagerInitiWithStaticBlock();
} catch (Exception ex) {
System.out.println("B_EagerInitiWithStaticBlock: Unable to create singleton instance");
throw new RuntimeException("B_EagerInitiWithStaticBlock: Unable to create singleton instance");
}
}
private B_EagerInitiWithStaticBlock() {
}
public static B_EagerInitiWithStaticBlock getInstance() {
System.out.println("getInstance(): Thread Name: " + Thread.currentThread().getName());
return instance;
}
}
|
package exercises.chapter3.ex5;
import static net.mindview.util.Print.print;
/**
* @author Volodymyr Portianko
* @date.created 02.03.2016
*/
public class Exercise5 {
public static void main(String[] args) {
Dog dog1 = new Dog("spot", "Ruff!");
Dog dog2 = new Dog("scruffy", "Wurf!");
print(dog1);
print(dog2);
}
}
class Dog {
String name;
String says;
public Dog(String name, String says) {
this.name = name;
this.says = says;
}
@Override
public String toString() {
return name + " says " + says;
}
}
|
package com.metoo.foundation.service;
import java.util.List;
import java.util.Map;
import com.metoo.foundation.domain.PlantingTrees;
public interface IPlantingtreesService {
/**
* 保存一个PlantingTrees 对象
* @param instance
* @return
*/
boolean save(PlantingTrees instance);
boolean update(PlantingTrees instance);
List<PlantingTrees> query(String query, Map params, int begin, int max);
boolean delete(Long id);
}
|
package com.disfile.cn;
import com.disfile.cn.annotation.MyAutoried;
import com.disfile.cn.annotation.MyService;
import com.disfile.cn.util.PkgUtil;
import org.apache.commons.lang3.StringUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class MyClassPathResources {
public MyClassPathResources(){} //手动无参构造器
private static ConcurrentMap<String,Object> beans = null; //my 容器 -使用线程安全的ConcurrenctMap接口
public MyClassPathResources(String packageName){
/**初始化bean*/
initBeans(packageName);
//3.遍历容器所有加载好的bean,判断属性是否有myAutoriod ,有-属性注入。
filedsSet(beans);
}
private void initBeans(String packageName) {
//1.扫描packageName下的所有类
Set<Class<?>> classes = PkgUtil.getClzFromPkg(packageName);
//2.拿到类--判断是否有myService注解。 有-实例化-存到容器beans
beans = new ConcurrentHashMap<String,Object>();
try {
for(Class c : classes){
Annotation myService = c.getAnnotation(MyService.class);
if(null != myService){
Object obj = c.newInstance();
String beanId = c.getSimpleName();
beanId = toLowerCase(beanId);
beans.put(beanId,obj) ; //容器存值 -key:beanId(默认为类小写) -value:类对象
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private void filedsSet(ConcurrentMap<String, Object> beans){
if(beans.isEmpty())
throw new RuntimeException("该包下沒有需要实例化的bean");
try {
for (Map.Entry<String, Object> entry : beans.entrySet()) {
Object obj = entry.getValue();
Class clazz = obj.getClass();
Field[] fileds =clazz.getDeclaredFields();
for(Field f :fileds){
Annotation myAutoried = f.getAnnotation(MyAutoried.class);
if(null != myAutoried){
String filedName = f.getName();
filedName = toLowerCase(filedName);
f.setAccessible(true); //私有属性 能被访问
f.set(obj,beans.get(filedName));
}
}
}
}catch (IllegalAccessException e){
e.printStackTrace();
}
}
String toLowerCase(String beanId){
if(StringUtils.isEmpty(beanId))
return null;
StringBuilder sb = new StringBuilder(beanId);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
return sb.toString();
}
/**从my容器中获取对象*/
public Object getMyBean(String userServiceImpl) {
if(StringUtils.isEmpty(userServiceImpl))
throw new RuntimeException("实例化对象不能为空");
Object obj = beans.get(userServiceImpl);
if(null == obj)
throw new RuntimeException("该"+userServiceImpl+"未被初始化");
return obj;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.