Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lils2013 container #104

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
1 change: 1 addition & 0 deletions OWNER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Tsoy Alexander Vladimirovich, CA-11
146 changes: 142 additions & 4 deletions src/main/java/track/container/Container.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,172 @@
package track.container;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import track.container.config.Bean;
import track.container.config.Property;

import static track.container.config.ValueType.REF;
import static track.container.config.ValueType.VAL;


/**
* Основной класс контейнера
* У него определено 2 публичных метода, можете дописывать свои методы и конструкторы
*/
public class Container {

private List<Bean> beans;
private Map<String, Object> objByName;
private Map<String, Object> objByClassName;

// Реализуйте этот конструктор, используется в тестах!
public Container(List<Bean> beans) {
this.beans = beans;
objByName = new HashMap<>();
objByClassName = new HashMap<>();
}

public Map<String, Object> getMapByName() {
return objByName;
}

public Map<String, Object> getMapByClass() {
return objByClassName;
}

/**
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
*/
public Object getById(String id) {
public Object getById(String id) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, CyclicReferenceException, InvocationTargetException {
for (Bean bean : beans) {
String objId = bean.getId();
if (objId.equals(id)) {
Object object = objByName.get(objId);
if (object == null) {
Class<?> cls = Class.forName(bean.getClassName());
object = (Object) cls.newInstance();
if (bean.getProperties() != null) {
for (Map.Entry<String, Property> entry : bean.getProperties().entrySet()) {
if (entry.getValue().getType() == VAL) {
parseValue(entry, cls, object);
} else if (entry.getValue().getType() == REF) {
parseRef(bean, entry, cls, object);
}
}
}
objByName.put(id, object);
objByClassName.put(bean.getClassName(), object);
}
return object;
}
}
return null;
}

/**
* Вернуть объект по имени класса
* Например, Car car = (Car) container.getByClass("track.container.beans.Car")
*/
public Object getByClass(String className) {
public Object getByClass(String className) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, CyclicReferenceException, InvocationTargetException {
for (Bean bean : beans) {
String clsName = bean.getClassName();
if (clsName.equals(className)) {
Copy link
Owner

Choose a reason for hiding this comment

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

Код дублируетс

Object object = objByClassName.get(clsName);
if (object == null) {
Class<?> cls = Class.forName(bean.getClassName());
object = (Object) cls.newInstance();
if (bean.getProperties() != null) {
for (Map.Entry<String, Property> entry : bean.getProperties().entrySet()) {
if (entry.getValue().getType() == VAL) {
parseValue(entry, cls, object);
} else if (entry.getValue().getType() == REF) {
parseRef(bean, entry, cls, object);
}
}
}
objByClassName.put(clsName, object);
objByName.put(bean.getId(), object);
}
return object;
}
}
return null;
}

private void parseRef(Bean bean, Map.Entry<String, Property> entry, Class<?> cls, Object object) throws ClassNotFoundException, CyclicReferenceException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
Class[] arg = new Class[1];
Class<?> cls1 = null;
Object object1 = null;
String id1 = entry.getValue().getValue();
for (Bean bean1 : beans) {
String objId1 = bean1.getId();
if (objId1.equals(id1)) {
cls1 = Class.forName(bean1.getClassName());
if (bean.getProperties() != null) {
for (Map.Entry<String, Property> entry1 : bean.getProperties().entrySet()) {
if (entry1.getValue().getType() == REF &&
Copy link
Owner

Choose a reason for hiding this comment

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

Уже выше проверили что REF

entry1.getValue().getValue().equals(bean.getId())) {
throw new CyclicReferenceException();
}
}
}
object1 = getById(objId1);
}
}
arg[0] = cls1;
Method[] methods = cls.getMethods();
Method method = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("set" +
entry.getValue().getName().substring(0, 1).toUpperCase() +
entry.getValue().getName().substring(1))) {
method = methods[i];
}
}
method.invoke(object, object1);
}

private void parseValue(Map.Entry<String, Property> entry, Class<?> cls, Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class[] arg = new Class[1];
Object value;
try {
value = Integer.parseInt(entry.getValue().getValue());
arg[0] = int.class;
} catch (NumberFormatException e) {
Copy link
Owner

Choose a reason for hiding this comment

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

Не все типы

try {
value = Double.parseDouble(entry.getValue().getValue());
arg[0] = double.class;
} catch (NumberFormatException ex) {
value = entry.getValue().getValue();
arg[0] = String.class;
}
}
Method[] methods = cls.getMethods();
Method method = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("set" +
entry.getValue().getName().substring(0, 1).toUpperCase() +
entry.getValue().getName().substring(1))) {
method = methods[i];
}
}
method.invoke(object, value);
}
}

class CyclicReferenceException extends Exception {

public CyclicReferenceException() {
}

public CyclicReferenceException(String message) {
super(message);
}
}
28 changes: 27 additions & 1 deletion src/main/java/track/container/JsonConfigReader.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package track.container;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import track.container.config.Bean;
import track.container.config.ConfigReader;
import track.container.config.InvalidConfigurationException;
import track.lections.lection4.Item;
import track.lections.lection4.Person;

/**
* TODO: Реализовать
Expand All @@ -14,6 +19,27 @@ public class JsonConfigReader implements ConfigReader {

@Override
public List<Bean> parseBeans(File configFile) throws InvalidConfigurationException {
return null;

ObjectMapper mapper = new ObjectMapper();
Beans beans = null;
try {
beans = mapper.readValue(configFile, Beans.class);
return Arrays.asList(beans.getBeans());
} catch (IOException e) {
return null;
}
}


}

class Beans {
private Bean[] beans;

public Beans() {
}

public Bean[] getBeans() {
return beans;
}
}
37 changes: 34 additions & 3 deletions src/main/java/track/container/Main.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
package track.container;

import track.container.beans.Car;
import track.container.beans.Engine;
import track.container.beans.Gear;
import track.container.config.Bean;
import track.container.config.ConfigReader;
import track.container.config.InvalidConfigurationException;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
*
*/
public class Main {

public static void main(String[] args) {
public static void main(String[] args) throws Exception {

/*

Expand All @@ -20,7 +32,26 @@ public static void main(String[] args) {
//
// Car car = (Car) container.getByClass("track.container.beans.Car");
// car = (Car) container.getById("carBean");


ConfigReader reader = new JsonConfigReader();
List<Bean> beans = reader.parseBeans(new File("src/main/resources/config.json"));
for (Bean bean : beans) {
System.out.println(bean);
}
Container container = new Container(beans);
Gear gear = (Gear) container.getById("gearBean");
System.out.println(gear);
Engine engine = (Engine) container.getById("engineBean");
System.out.println(engine);
Car car = (Car) container.getById("carBean");
System.out.println(car);
System.out.println(container.getMapByName());
System.out.println(container.getMapByClass());
// Gear gear1 = (Gear) container.getByClass("track.container.beans.Gear");
// System.out.println(gear1);
// Engine engine1 = (Engine) container.getByClass("track.container.beans.Engine");
// System.out.println(engine1);
Car car1 = (Car) container.getByClass("track.container.beans.Car");
System.out.println(car1.getEngine().getPower() + 45);
System.out.println(container.getMapByClass());
}
}
4 changes: 4 additions & 0 deletions src/main/java/track/container/config/Bean.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ public class Bean {
*/
private Map<String, Property> properties; // Набор полей бина ИмяПоля-Значение

public Bean() {

}

public Bean(String id, String className, Map<String, Property> properties) {
this.id = id;
this.className = className;
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/track/container/config/Property.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ public class Property {
private String value; // Значение поля
private ValueType type; // Метка ссылочное значение или примитив

public Property() {
}

public Property(String name, String value, ValueType type) {
this.name = name;
this.value = value;
Expand Down
27 changes: 25 additions & 2 deletions src/main/java/track/lessons/lesson1/CountWords.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package track.lessons.lesson1;

import java.io.File;
import java.util.Scanner;

/**
* Задание 1: Реализовать два метода
Expand Down Expand Up @@ -31,7 +32,17 @@ public class CountWords {
* @return - целое число - сумма всех чисел из файла
*/
public long countNumbers(File file) throws Exception {
return 0;
Scanner scan = new Scanner(file);
long count = 0;
while (scan.hasNext()) {
if (scan.hasNextInt()) {
count += scan.nextInt();
scan.nextLine();
} else {
scan.nextLine();
}
}
return count;
}


Expand All @@ -43,7 +54,19 @@ public long countNumbers(File file) throws Exception {
* @return - результирующая строка
*/
public String concatWords(File file) throws Exception {
return null;
Scanner scan = new Scanner(file);
StringBuilder strbld = new StringBuilder();
while (scan.hasNext()) {
if (scan.hasNextInt()) {
scan.nextLine();
} else {
String next = scan.nextLine();
if (!next.equals("")) {
strbld.append(next + " ");
}
}
}
return strbld.toString().trim();
}

}
Loading