Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions OWNER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Sinevich Valeriya Alexandrovna

74 changes: 66 additions & 8 deletions src/main/java/arhangel/dim/container/BeanGraph.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package arhangel.dim.container;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Iterator;

/**
*
*/
public class BeanGraph {



// Граф представлен в виде списка связности для каждой вершины
private Map<BeanVertex, List<BeanVertex>> vertices = new HashMap<>();

Expand All @@ -16,35 +19,90 @@ public class BeanGraph {
* @param value - объект, привязанный к вершине
*/
public BeanVertex addVertex(Bean value) {
return null;
BeanVertex newBeanVertex = new BeanVertex(value);
List<BeanVertex> edges = new LinkedList<>();
if (!vertices.containsKey(newBeanVertex)) {
vertices.put(newBeanVertex, edges);
}
return newBeanVertex;
}

/**
* Соединить вершины ребром
* @param from из какой вершины
* @param to в какую вершину
*/
public void addEdge(BeanVertex from ,BeanVertex to) {
public void addEdge(BeanVertex from,BeanVertex to) {
List<BeanVertex> edges = vertices.get(from);
edges.add(to);

}

/**
* Проверяем, связаны ли вершины
*/
public boolean isConnected(BeanVertex v1, BeanVertex v2) {
return false;
List<BeanVertex> edges1 = vertices.get(v1);
List<BeanVertex> edges2 = vertices.get(v1);
return (edges1.contains(v2) || edges2.contains(v1));
}

/**
* Получить список вершин, с которыми связана vertex
*/
public List<BeanVertex> getLinked(BeanVertex vertex) {
return null;
List<BeanVertex> edges = vertices.get(vertex);
return edges;
}

/**
* Количество вершин в графе
*/
public int size() {
return 0;
return vertices.size();
}

public void dfs(BeanVertex start, List<BeanVertex> sortedVertices, Map<BeanVertex, Integer> colouredVertices)
throws CycleReferenceException {
List<BeanVertex> edges = vertices.get(start);
for (BeanVertex child : edges) {
if (colouredVertices.containsKey(child) && colouredVertices.get(child) == 0) {
throw new CycleReferenceException("cycle found");
}
if (!sortedVertices.contains(child)) {
sortedVertices.add(child);
try {
colouredVertices.put(child, 0);
dfs(child, sortedVertices, colouredVertices);
colouredVertices.put(child, 1);
} catch (CycleReferenceException e) {
throw e;
}
}
}
}

public List<BeanVertex> sort() throws CycleReferenceException {
List<BeanVertex> sortedVertices = new LinkedList<>();
Map<BeanVertex, Integer> colouredVertices = new HashMap<>();
Iterator it = vertices.entrySet().iterator();
while (it.hasNext()) {
Map.Entry vertex = (Map.Entry) it.next();
BeanVertex beanVertex = (BeanVertex) (vertex.getKey());
if (colouredVertices.containsKey(beanVertex) && colouredVertices.get(beanVertex) == 0) {
throw new CycleReferenceException("cycle found");
}
if (!sortedVertices.contains(beanVertex)) {
try {
colouredVertices.put(beanVertex, 0);
dfs(beanVertex, sortedVertices, colouredVertices);
colouredVertices.put(beanVertex, 1);
} catch (CycleReferenceException e) {
throw e;
}
}
sortedVertices.add(beanVertex);
}
return sortedVertices;
}
}
82 changes: 79 additions & 3 deletions src/main/java/arhangel/dim/container/BeanXmlReader.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,27 @@
package arhangel.dim.container;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
* Created by valeriyasin on 3/15/16.
=======
import java.util.List;

/**
*
>>>>>>> 5044e64aedcc627f70c5d919734be1e8583b899e
*/
public class BeanXmlReader {
private static final String TAG_BEAN = "bean";
Expand All @@ -13,9 +31,67 @@ public class BeanXmlReader {
private static final String ATTR_REF = "ref";
private static final String ATTR_BEAN_ID = "id";
private static final String ATTR_BEAN_CLASS = "class";
private static final String TAG_GEAR = "gear";
private static final String TAG_ENGINE = "engine";

public List<Bean> parseBeans(String pathToFile) {
return null;
}

public List<Bean> parseBeans(String pathToFile) throws InvalidConfigurationException {
List<Bean> graphWithoutEdges = new LinkedList<>();

try {
File inputFile = new File(pathToFile);
//System.out.println(pathToFile);
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();
try {
Document doc = documentBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList beans = doc.getElementsByTagName(TAG_BEAN);


for (int i = 0; i < beans.getLength(); ++i) {
Node bean = beans.item(i);
NamedNodeMap attributes = bean.getAttributes();
Node idAttrib = attributes.getNamedItem(ATTR_BEAN_ID);
// System.out.printf(idAttrib.toString());
Node classAttrib = attributes.getNamedItem(ATTR_BEAN_CLASS);
//System.out.printf(classAttrib.toString());
NodeList properties = ((Element) bean).getElementsByTagName(TAG_PROPERTY);
HashMap<String, Property> propertyHashMap = new HashMap<>();
//System.out.println(properties.getLength());

for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
NamedNodeMap propertyAttributes = property.getAttributes();
Node nameAttrib = propertyAttributes.getNamedItem(ATTR_NAME);
String propertyType = nameAttrib.getNodeValue();
Property newProp;
if (propertyAttributes.getNamedItem(ATTR_REF) != null) {
//System.out.println(propertyType);
Node refAttrib = propertyAttributes.getNamedItem(ATTR_REF);
String refAttrString = refAttrib.getNodeValue();
//System.out.println("REFEERENCE" + refAttrString);
newProp = new Property(propertyType, refAttrString, ValueType.REF);
} else {
//System.out.println(propertyType);
Node valAttrib = propertyAttributes.getNamedItem(ATTR_VALUE);
String valAttrString = valAttrib.getNodeValue();
//System.out.println(valAttrString);
newProp = new Property(propertyType, valAttrString, ValueType.VAL);
}
propertyHashMap.put(nameAttrib.getNodeValue(), newProp);
}
Bean newBean = new Bean(idAttrib.getNodeValue(), classAttrib.getNodeValue(), propertyHashMap);
//BeanVertex newBeanVertex = new BeanVertex(newBean);
graphWithoutEdges.add(newBean);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
} catch (Exception e) {
throw new InvalidConfigurationException("can't read xml File");
}
return graphWithoutEdges;
}
}
125 changes: 97 additions & 28 deletions src/main/java/arhangel/dim/container/Container.java
Original file line number Diff line number Diff line change
@@ -1,63 +1,132 @@
package arhangel.dim.container;

import arhangel.dim.container.beans.Car;
import arhangel.dim.container.beans.Engine;
import arhangel.dim.container.beans.Gear;

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

/**
* Используйте ваш xml reader чтобы прочитать конфиг и получить список бинов
*/
public class Container {
private List<Bean> beans;
public static void main(String[] args) {
try {
Container container = new Container("config.xml");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

private Map<String, Object> objByName = new HashMap<>();
private Map<String, Object> objByClassName = new HashMap<>();

private Map<String, Bean> beanNames = new HashMap<>();

/**
* Если не получается считать конфиг, то бросьте исключение
* @throws InvalidConfigurationException неверный конфиг
*/
public Container(String pathToConfig) throws InvalidConfigurationException {

// вызываем BeanXmlReader
List<Bean> parsedBeans;
try {
BeanXmlReader xmlReader = new BeanXmlReader();
parsedBeans = xmlReader.parseBeans(pathToConfig);
try {
instantiateBeans(parsedBeans);
} catch (CycleReferenceException | InvalidConfigurationException e) {
throw new InvalidConfigurationException(e.getMessage());
}
} catch (InvalidConfigurationException e) {
throw e;
}
}

/**
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getByName("carBean")
*/
public Object getByName(String name) {
return null;
return objByName.get(name);
}

/**
* Вернуть объект по имени класса
* Например, Car car = (Car) container.getByClass("arhangel.dim.container.Car")
*/
public Object getByClass(String className) {
return null;
return objByClassName.get(className);
}

private void instantiateBean(Bean bean) {

/*
// Примерный ход работы
private void instantiateBeans(List<Bean> beans)
throws InvalidConfigurationException, CycleReferenceException {
GraphBuilder grBuilder = new GraphBuilder();
BeanGraph gr = grBuilder.buildGraph(beans);
try {
List<BeanVertex> sortedBeanVertices = gr.sort();
for (BeanVertex beanVertex : sortedBeanVertices) {
try {
instantiateBean(beanVertex.getBean());
} catch (InvalidConfigurationException | IllegalArgumentException e) {
throw new InvalidConfigurationException(e.getMessage());
}
}
} catch (CycleReferenceException e) {
throw new InvalidConfigurationException(e.getMessage());
}
}

private void instantiateBean(Bean bean)
throws IllegalArgumentException, InvalidConfigurationException {
String className = bean.getClassName();
Class clazz = Class.forName(className);
// ищем дефолтный конструктор
Object ob = clazz.newInstance();


for (String name : bean.getProperties().keySet()) {
// ищем поле с таким именен внутри класса
// учитывая приватные
Field field = clazz.getDeclaredField(name);
// проверяем, если такого поля нет, то кидаем InvalidConfigurationException с описание ошибки

// Делаем приватные поля доступными
field.setAccessible(true);

// Далее определяем тип поля и заполняем его
// Если поле - примитив, то все просто
// Если поле ссылка, то эта ссылка должа была быть инициализирована ранее

*/
String beanName = bean.getName();
try {
Class clazz = Class.forName(className);
try {
Object ob = clazz.newInstance();
for (String name : bean.getProperties().keySet()) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
if (bean.getProperties().get(name).getType() == ValueType.VAL) {
Object value = bean.getProperties().get(name).getValue();
field.set(ob, Integer.parseInt(value.toString()));
} else {
if (!objByName.containsKey(bean.getProperties().get(name).getValue())) {
throw new InvalidConfigurationException("invalid reference");
} else {
Object value = getByName(bean.getProperties().get(name).getValue());
String nameCapitalized =
name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
try {
Method method = clazz.getDeclaredMethod("set" + nameCapitalized, value.getClass());
try {
method.invoke(ob, value);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e.getMessage());
}
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
objByName.put(beanName, ob);
objByClassName.put(className, ob);
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(e.getMessage());
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e.getMessage());
}

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/**
* Обнаружена циклическая зависимость
*/
public class CycleReferenceException extends Exception {
public class CycleReferenceException extends Exception {
public CycleReferenceException(String message) {
super(message);
}
Expand Down
Loading