Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions homework-g596-kozlova/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>homework-g596-kozlova</artifactId>
<packaging>pom</packaging>
<version>1.0.0</version>

<properties>
<spring.boot.version>1.4.2.RELEASE</spring.boot.version>
</properties>

<dependencies>
<dependency>
Expand All @@ -27,6 +33,46 @@
<artifactId>homework-tests</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jeval</groupId>
<artifactId>jeval</artifactId>
<version>0.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лишняя зависимость. У меня из-за неё не собиралось

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>ru.mipt.java2016</groupId>
<artifactId>homework-tests</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package ru.mipt.java2016.homework.g596.kozlova.task4;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@EnableAutoConfiguration
@Configuration
@ComponentScan(basePackageClasses = Application.class)
public class Application {

@Bean
public Calculator calculator() {
return Calculator.INSTANCE;
}

@Bean
public EmbeddedServletContainerCustomizer customizer(
@Value("${ru.mipt.java2016.homework.g596.kozlova.task4.httpPort:9001}") int port) {
return container -> container.setPort(port);
}

public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package ru.mipt.java2016.homework.g596.kozlova.task4;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import ru.mipt.java2016.homework.base.task1.ParsingException;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Array;
import java.util.Map;
import java.util.HashMap;

@Repository
public class BillingDao {

private static final Logger LOG = LoggerFactory.getLogger(BillingDao.class);

@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

@PostConstruct
public void postConstruct() {
jdbcTemplate = new JdbcTemplate(dataSource, false);
LOG.trace("Initializing");
jdbcTemplate.execute("CREATE SCHEMA IF NOT EXISTS billing");
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS billing.users " +
"(username VARCHAR PRIMARY KEY, password VARCHAR, enabled BOOLEAN)");
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS billing.variables " +
"(username VARCHAR, name VARCHAR, value DOUBLE, expression VARCHAR)");
createNewUser("userName", "password", true);
}

public boolean createNewUser(String userName, String password, boolean enabled) {
try {
loadUser(userName);
return false;
} catch (EmptyResultDataAccessException e) {
jdbcTemplate.update("INSERT INTO billing.users VALUES (?, ?, ?)",
new Object[]{userName, password, enabled});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут можно было не создавать массив, просто передать все аргументы:
jdbcTemplate.update("INSERT INTO billing.users VALUES (?, ?, ?)", userName, password, enabled);

return true;
}
}

public BillingUser loadUser(String userName) throws EmptyResultDataAccessException {
LOG.trace("Querying for user " + userName);
return jdbcTemplate.queryForObject(
"SELECT username, password, enabled FROM billing.users WHERE username = ?",
new Object[]{userName},
new RowMapper<BillingUser>() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Анонимные классы с единственным методом нынче заменяют на лямбда функции обычно. Получается компактнее и (по крайней мере, когда привыкнешь) читабельнее

@Override
public BillingUser mapRow(ResultSet resultSet, int numberOfRow) throws SQLException {
return new BillingUser(
resultSet.getString("userName"),
resultSet.getString("password"),
resultSet.getBoolean("enabled")
);
}
}
);
}

public Variable getVariable(String userName, String variable) {
return jdbcTemplate.queryForObject(
"SELECT userName, name, value, expression FROM billing.variables WHERE userName = ? AND name = ?",
new Object[]{userName, variable},
new RowMapper<Variable>() {
@Override
public Variable mapRow(ResultSet resultSet, int numberOfRow) throws SQLException {
return new Variable(
resultSet.getString("userName"),
resultSet.getString("name"),
resultSet.getDouble("value"),
resultSet.getString("expression"));
}
}
);
}

public Map<String, String> getVariables(String userName) {
try {
return jdbcTemplate.queryForObject(
"SELECT userName, name, value, expression FROM billing.variables WHERE userName = ?",
new Object[]{userName},
new RowMapper<Map<String, String>>() {
@Override
public Map<String, String> mapRow(ResultSet resultSet, int numberOfRow) throws SQLException {
Map<String, String> map = new HashMap<>();
while (!resultSet.next()) {
map.put(resultSet.getString("name"), Double.toString(resultSet.getDouble("value")));
}
return map;
}
}
);
} catch (EmptyResultDataAccessException e) {
return new HashMap<>();
}
}

public void deleteVariable(String userName, String name) throws ParsingException {
try {
getVariable(userName, name);
jdbcTemplate.update("DELETE FROM billing.variables WHERE userName = ? AND name = ?",
new Object[]{userName, name});
} catch (EmptyResultDataAccessException e) {
throw new ParsingException("Can't delete");
}
}

public void addVariable(String userName, String name, Double value, String expression) throws ParsingException {
try {
getVariable(userName, name);
jdbcTemplate.update("DELETE FROM billing.variables WHERE userName = ? AND name = ?",
new Object[]{userName, name});
jdbcTemplate.update("INSERT INTO billing.variables VALUES (?, ?, ?, ?)",
new Object[]{userName, name, value, expression});
} catch (EmptyResultDataAccessException e) {
jdbcTemplate.update("INSERT INTO billing.variables VALUES (?, ?, ?, ?)",
new Object[]{userName, name, value, expression});
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще есть merge. C ним можно обновлять существующие значения и добавлять новые - не нужно будет удалять


public Function getFunction(String userName, String function) {
return jdbcTemplate.queryForObject(
"SELECT userName, name, arguments, expression FROM billing.functions WHERE userName = ? AND name = ?",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А где ты создаешь billing.functions?

new Object[]{userName, function},
new RowMapper<Function>() {
@Override
public Function mapRow(ResultSet resultSet, int numberOfRow) throws SQLException {
return new Function(
resultSet.getString("userName"),
resultSet.getString("name"),
resultSet.getArray("arguments"),
resultSet.getString("expression"));
}
}
);
}

public Map<String, String> getFunctions(String userName) {
try {
return jdbcTemplate.queryForObject(
"SELECT userName, name, arguments, expression FROM billing.functions WHERE userName = ?",
new Object[]{userName},
new RowMapper<Map<String, String>>() {
@Override
public Map<String, String> mapRow(ResultSet resultSet, int numberOfRow) throws SQLException {
Map<String, String> map = new HashMap<>();
while (!resultSet.next()) {
map.put(resultSet.getString("name"), Double.toString(resultSet.getDouble("arguments")));
}
return map;
}
}
);
} catch (EmptyResultDataAccessException e) {
return new HashMap<>();
}
}

public void deleteFunction(String userName, String name) throws ParsingException {
try {
getFunction(userName, name);
jdbcTemplate.update("DELETE FROM billing.functions WHERE userName = ? AND name = ?",
new Object[]{userName, name});
} catch (EmptyResultDataAccessException e) {
throw new ParsingException("Can't delete");
}
}

public void addFunction(String userName, String name, Array arguments, String expression) throws ParsingException {
try {
getVariable(userName, name);
jdbcTemplate.update("DELETE FROM billing.functions WHERE userName = ? AND name = ?",
new Object[]{userName, name});
jdbcTemplate.update("INSERT INTO billing.functions arguments (?, ?, ?, ?)",
new Object[]{userName, name, arguments, expression});
} catch (EmptyResultDataAccessException e) {
jdbcTemplate.update("INSERT INTO billing.functions FUNCTION (?, ?, ?, ?)",
new Object[]{userName, name, arguments, expression});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ru.mipt.java2016.homework.g596.kozlova.task4;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class BillingDatabaseConfiguration {
@Bean
public DataSource billingDataSource(
@Value("${ru.mipt.java2016.homework.g596.kozlova.task4.jdbcUrl}") String jdbcUrlAdress,
@Value("${ru.mipt.java2016.homework.g596.kozlova.task4.userName:}") String userName,
@Value("${ru.mipt.java2016.homework.g596.kozlova.task4.password:}") String password
) {
HikariConfig config = new HikariConfig();
config.setDriverClassName(org.h2.Driver.class.getName());
config.setJdbcUrl(jdbcUrlAdress);
config.setUsername(userName);
config.setPassword(password);
return new HikariDataSource(config);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package ru.mipt.java2016.homework.g596.kozlova.task4;

public class BillingUser {

private final String userName;
private final String password;
private final boolean enabled;

public BillingUser(String u, String p, boolean e) {
if (u.equals(null) || p.equals(null)) {
throw new IllegalArgumentException("Incorrect data");
}
userName = u;
password = p;
enabled = e;
}

public String getUserName() {
return userName;
}

public String getPassword() {
return password;
}

@Override
public String toString() {
return "BillingUser{ userName='" + userName + "\', password='" + password + '\'' + ", enabled=" + enabled + "}";
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
BillingUser that = (BillingUser) obj;
if (!userName.equals(that.userName) || !password.equals(that.password) || enabled != that.enabled) {
return false;
}
return true;
}

@Override
public int hashCode() {
int result = userName.hashCode();
result = 31 * result + password.hashCode();
result = 31 * result + (enabled ? 1 : 0);
return result;
}
}
Loading