Разработка сервера приложений

Анализ информационной системы "Бурятия.INFO". Построение функциональной модели "Как надо", диаграммы прецедентов, диаграммы последовательности действий, диаграммы классов. Разработка программного приложения в интегрированной среде Intellij IDEA.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 13.04.2014
Размер файла 1,3 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

import java.io.IOException;

import java.util.logging.FileHandler;

import java.util.logging.Level;

import java.util.logging.Logger;

/**

* Date: 09.12.12

* Time: 22:15

*

* @author DoSOfRR

*/

public class ServerLogger {

public final static String DEFAULT_LOG_NAME = "log.html";

public final static String DEFAULT_NAME = "Server logger";

private Logger logger;

public ServerLogger() throws IOException {

init(DEFAULT_NAME, DEFAULT_LOG_NAME);

}

public ServerLogger(String name) throws IOException {

init(name, DEFAULT_LOG_NAME);

}

public ServerLogger(String name, String filename) throws IOException {

init(name, filename);

}

private void init(String name, String filename) throws IOException {

FileHandler fh = new FileHandler(filename);

fh.setFormatter(new HTMLFormatter());

logger = Logger.getLogger(name);

logger.addHandler(fh);

}

public void log(Level level, String msg) {

logger.log(level, msg);

}

public void log(Level level, String msg, Throwable ex) {

logger.log(level, msg, ex);

}

}

package com.gmail.dosofredriver.ajax.serviceserver.util.parser;

import java.util.Set;

/**

* Date: 07.03.13

* Time: 21:27

*

* @author DoSOfRR

*/

public class MethodStruct {

public Class [] argsTypes;

public String methodName;

public Set params;

public MethodStruct(String methodName, Set params, Class [] argsTypes) {

this.methodName = methodName;

this.argsTypes = argsTypes;

this.params = params;

}

}

package com.gmail.dosofredriver.ajax.serviceserver.util.parser;

import com.gmail.dosofredriver.ajax.serviceserver.util.collections.DefaultOrderComparator;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import java.util.*;

/**

* Date: 29.03.13

* Time: 3:22

*

* @author DoSOfRR

*/

public class Parser {

public static final String KEY_METHODNAME = "methodName";

public static final String KEY_PARAMS = "params";

public static MethodStruct parseRequest(String query) throws Exception {

Map<String, String> strParams = new TreeMap(new DefaultOrderComparator());

JSONParser parser = new JSONParser();

String methodName;

Set params;

JSONObject jsonObject = (JSONObject)parser.parse(query);

//get method name from request

methodName = (String) jsonObject.get(KEY_METHODNAME);

//get params from request

JSONArray ja = (JSONArray) jsonObject.get(KEY_PARAMS);

for (Object param : ja) {

strParams.put(

(String) ((JSONObject) param).get("type"),

(String) ((JSONObject) param).get("value")

);

}

//get classes from strings

Class [] classes = getClasses(strParams.keySet());

//get parameters

params = getInstances(getMap(classes, strParams.values()));

return new MethodStruct(methodName, params, classes);

}

public static Class [] getClasses(Set<String> classNames) throws ClassNotFoundException {

Class [] result = new Class[classNames.size()];

int i=0;

for(String name : classNames) {

switch (name) {

case "int" : result[i] = int.class; break;

case "long" : result[i] = long.class; break;

case "boolean" : result[i] = boolean.class;break;

default : result[i] = Class.forName(name);

}

i++;

}

return result;

}

private static Set getInstances(Map<Class, String> args) throws Exception {

Set result = new TreeSet(new DefaultOrderComparator());

for (Map.Entry<Class, String> entry : args.entrySet()) {

switch (entry.getKey().toString()) {

case "boolean" : result.add(Boolean.parseBoolean(entry.getValue())); break;

case "long" : result.add(Long.parseLong(entry.getValue())); break;

case "int" : result.add(Integer.parseInt(entry.getValue())); break;

default : result.add(getInstance(entry.getKey(), entry.getValue()));

}

}

return result;

}

private static<T> T getInstance(Class<T> tClass, String value) throws Exception {

return (T)tClass.getConstructor(String.class).newInstance(value);

}

private static Map<Class, String> getMap(Class [] classes, Collection<String> values) {

Map<Class, String> result = new TreeMap(new DefaultOrderComparator());

int i = 0;

for (String value : values) {

result.put(classes[i], value);

i++;

}

return result;

}

}

package com.gmail.dosofredriver.ajax.serviceserver.util.view;

/**

* Date: 07.03.13

* Time: 22:32

*

* @author DoSOfRR

*/

public enum Commands {

Start_Server, Stop_Server, Restart_Server, SwitchOFF_Server, Deploy, Undeploy, Help, Undefined, Exit

}

package com.gmail.dosofredriver.ajax.serviceserver.util.view;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.io.IOException;

import java.io.OutputStream;

/**

* Date: 07.03.13

* Time: 22:45

*

* @author DoSOfRR

*/

public class ConsoleView implements ViewInterface {

private OutputStream os;

/*

* Creates an console view.

*

* @param os

* Specifies output stream that will be used to print messages.

*/

public ConsoleView(OutputStream os) {

this.os = os;

}

public ConsoleView() {

//System.out as default output stream.

this.os = System.out;

}

@Override

public void showDefault() throws IOException {

os.write("Welcome to server administration panel.\n".getBytes());

os.write("\nType \"-help\" to print help \n".getBytes());

}

@Override

public void showHelp() throws IOException {

os.write("\nType \"-start\" to start server.".getBytes());

os.write("\nType \"-stop\" to stop server.".getBytes());

os.write("\nType \"-restart\" to restart server.".getBytes());

os.write("\nType \"-help\" to get help.".getBytes());

}

@Override

public void showMessage(String message) throws IOException {

os.write(message.getBytes());

}

@Override

public void showAuthorize() throws IOException {

throw new NotImplementedException();

}

@Override

public Commands readMessage(byte[] message) throws IOException {

String strmsg = new String(message);

switch (strmsg) {

case "-start" : return Commands.Start_Server;

case "-stop" : return Commands.Stop_Server;

case "-help" : return Commands.Help;

case "-restart" : return Commands.Restart_Server;

default : return Commands.Undefined;

}

}

}

package com.gmail.dosofredriver.ajax.serviceserver.util.view;

import java.io.IOException;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;

/**

* Date: 07.03.13

* Time: 21:47

*

* @author DoSOfRR

*/

/*

* This interface realizes view for admin panel. With that interface you can specify

* your view without changing <code>Commander</code> controller.

*/

public interface ViewInterface {

BlockingQueue<Commands> messages = new LinkedBlockingQueue<>();

/*

* This method is used to show initial interface and/or message.

* Here you can write some tips for users, or send HTML form, for example.

*/

public void showDefault() throws IOException;

/*

* Show help, that can describe commands, params etc.

*/

public void showHelp() throws IOException;

/*

* Show some message that server send to user.

*/

public void showMessage(String message) throws IOException;

/*

* Show authorize form/message.

*/

public void showAuthorize() throws IOException;

/*

* This method will invoked when an message will arrived.

* Method should parseRequest incoming <code>message</code> and

* return result as <code>Commands</code> enum.

*/

public Commands readMessage(byte [] message) throws IOException;

}

Размещено на Allbest.ru


Подобные документы

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.