id stringlengths 36 36 | text stringlengths 1 1.25M |
|---|---|
0c69cdd1-1a52-40f5-b944-90dc3abfc322 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Node other = (Node) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
if (this.Direction != other.Direction) {
return false;
}
return true;
} |
295f1c3b-1e65-4d24-997f-2dd2799afd30 | @Override
public int compareTo(Object o) {
return 123;
} |
3f07c9ec-2409-4ca4-a4d4-06d2bfbe1c6c | public void AusgabeXY() {
if (this.vorgaenger != null) {
this.vorgaenger.AusgabeXY();
}
System.out.println("X-Koordinate:" + x + " Y-Koordinate:" + y);
} |
4d95bb0c-4376-4d97-a1f4-2681769f5ab0 | @Override
public String toString() {
return "X:" + x + "Y:" + y;
} |
b4014fab-66e0-4406-94ff-553047777fba | public static void main(String[] args) {
Start start = new Start("b");
start.initSearch();
start.AStarSearch();
} |
da72125a-8748-44e4-9d0e-7df925b8c742 | public static char[][] copy2DCharArray(char[][] original) {
int sizeY = original.length;
char[][] copy = new char[sizeY][];
for (int y = 0; y < sizeY; ++y) {
copy[y] = original[y].clone();
}
return copy;
} |
23bf7e04-1680-4384-8993-ba6d23378df0 | public static void print2DCharArray(char[][] array) {
} |
20f72a5c-1cab-4f17-90f3-2b8ea154d3e3 | public Start(String modus) {
this.modus = modus;
} |
d67ac936-368f-49b5-990e-355ef946e21c | public void initSearch() {
EnvironmentReader reader = null;
String pfad;
switch (modus) {
case "a": {
URL urlreader = ClassLoader.getSystemClassLoader().getResource("resources/blatt4_environment_a.txt");
pfad = urlreader.toString().substring(6);
break;
}
case "b": {
URL urlreader = ClassLoader.getSystemClassLoader().getResource("resources/blatt4_environment_b2.txt");
pfad = urlreader.toString().substring(6);
break;
}
default:
return;
}
try {
reader = new EnvironmentReader(pfad, LINE_COUNT, LINE_LENGTH);
} catch (IOException ex) {
Logger.getLogger(Start.class.getName()).log(Level.SEVERE, null, ex);
}
char[][] environment = reader.getEnvironment();
for (int y = 0; y < 10; ++y) {
String line = "";
for (int x = 0; x < 20; ++x) {
line = line + environment[y][x];
}
System.out.println(line);
}
int startPosX = reader.getStartPosX();
int startPosY = reader.getStartPosY();
int goalPosX = reader.getGoalPosX();
int goalPosY = reader.getGoalPosY();
char goalChar = reader.getGoalChar();
System.out.println("X: " + startPosX + ", Y: " + startPosY);
Node goalNode = new Node(goalPosX, goalPosY, goalChar);
_search = new Search(environment, startPosX, startPosY, goalNode);
} |
1cc7c74f-94f1-443f-b6de-11687a767cca | public final void AStarSearch() {
List<Character> goalPath = _search.startBFS();
System.out.println(goalPath.toString());
} |
db191cf0-15e1-43ba-88f6-eda6f2896cff | public final void BreadthFirstSearch(int fastmode) {
List<Character> goalPath = _search.startBFS();
System.out.println(goalPath.toString());
// ui.Schritte.setText("Auszufuehrende Schritte" + goalPath.toString());
} |
c21d5574-1d8d-4236-94a3-b37a8f93f27a | public final void DepthFirstSearch() {
List<Character> goalPath = _search.startDFS();
System.out.println(goalPath.toString());
// ui.Schritte.setText("Auszufuehrende Schritte" + goalPath.toString());
} |
16961c94-ebf3-4f3e-bedc-56190f82e159 | public Search(char[][] environment, int startPosX, int startPosY, Node goalNode) {
_environment = Start.copy2DCharArray(environment);
_inputEnvironment = Start.copy2DCharArray(environment);
_startPosX = startPosX;
_startPosY = startPosY;
_currentPosX = startPosX;
_currentPosY = startPosY;
_searchStack = new Stack<Character>();
_frontier = new HashSet<Path>();
_bfsQueue = new PriorityQueue<Node>();
GOAL_NODE = goalNode;
} |
da6eaed2-af24-410b-ad00-a9d27efcd272 | private char oppositeDirection(char direction) {
char oppositeDir = ' ';
switch (direction) {
case 'u':
oppositeDir = 'd';
break;
case 'r':
oppositeDir = 'l';
break;
case 'd':
oppositeDir = 'u';
break;
case 'l':
oppositeDir = 'r';
break;
}
return oppositeDir;
} |
aabfb7c8-ebe3-4fee-b6f8-9dd90b31fd53 | public List<Character> startDFS() {
reset(); // Resets all values to the start values, needed if multiple searches are performed
_searchStack.push(START_CHAR);
int schleifenzaehler = 0;
while (!goalInReach() && !_searchStack.isEmpty()) {
if (topIsClear()) {
move(UP);
_environment[_currentPosY][_currentPosX] = UP;
_searchStack.push(UP);
} else if (rightIsClear()) {
move(RIGHT);
_environment[_currentPosY][_currentPosX] = RIGHT;
_searchStack.push(RIGHT);
} else if (bottomIsClear()) {
move(DOWN);
_environment[_currentPosY][_currentPosX] = DOWN;
_searchStack.push(DOWN);
} else if (leftIsClear()) {
move(LEFT);
_environment[_currentPosY][_currentPosX] = LEFT;
_searchStack.push(LEFT);
} else {
char topChar = _searchStack.pop();
move(oppositeDirection(topChar));
}
// Output to the console
++schleifenzaehler;
printEnvironment();
}
System.out.println(schleifenzaehler);
return new ArrayList(_searchStack);
} |
e731dc6b-0635-4fd4-b7a0-820437772b62 | public List<Character> startBFS() {
int schleifenZaehler = 0;
Node startNode = new Node(_startPosX, _startPosY, START_CHAR);
_bfsQueue.add(startNode);
_frontier.add(new Path(startNode));
while (!_frontier.isEmpty()) {
Node currentNode = (Node) _bfsQueue.poll();
Path currentPath = null;
// Choosing the path that ends with the first element on the queue
for (Path path : _frontier) {
if (currentNode.equals(path.getLastNode())) {
currentPath = path;
break;
}
}
if (isGoalNode(currentNode)) {
System.out.println(schleifenZaehler);
reset();
return currentPath.getCharPath();
}
_frontier.remove(currentPath);
moveTo(currentNode);
// Check wether currentNode has any neighbours
// If a neighbour is found a new Path is added to frontier
if (topIsClearOrGoal()) {
move(UP);
_environment[_currentPosY][_currentPosX] = UP;
Node neighbour = new Node(_currentPosX, _currentPosY, UP);
bfsAddNewPathToFrontier(currentPath, neighbour);
move(oppositeDirection(UP));
}
if (rightIsClearOrGoal()) {
move(RIGHT);
_environment[_currentPosY][_currentPosX] = RIGHT;
Node neighbour = new Node(_currentPosX, _currentPosY, RIGHT);
bfsAddNewPathToFrontier(currentPath, neighbour);
move(oppositeDirection(RIGHT));
}
if (bottomIsClearOrGoal()) {
move(DOWN);
_environment[_currentPosY][_currentPosX] = DOWN;
Node neighbour = new Node(_currentPosX, _currentPosY, DOWN);
bfsAddNewPathToFrontier(currentPath, neighbour);
move(oppositeDirection(DOWN));
}
if (leftIsClearOrGoal()) {
move(LEFT);
_environment[_currentPosY][_currentPosX] = LEFT;
Node neighbour = new Node(_currentPosX, _currentPosY, LEFT);
bfsAddNewPathToFrontier(currentPath, neighbour);
move(oppositeDirection(LEFT));
}
// Output to the console
printEnvironment();
++schleifenZaehler;
}
System.out.println(schleifenZaehler);
reset();
return new ArrayList<Character>();
} |
f09d7529-72c5-4b81-892c-369033a2c9b5 | public List<Character> startAstarSearch() {
int schleifenZaehler = 0;
Node node = null;
Astar_openList = new LinkedList<>();
Astar_closedList.add(new Node(_startPosX, _startPosY, 1, heuristik(_startPosX, _startPosY), null));
Astar_closedList = new LinkedList<>();
while (!Astar_openList.isEmpty()) {
if (GOAL_NODE != null) {
node = GOAL_NODE;
this.suche = false;
} else if (this.Astar_openList.isEmpty() == false && this.suche == true) {
node = AStarSearch();
}
}
return new ArrayList<>();
} |
2e3aeaa9-d2be-4a44-9678-32ae104fb3f5 | private Node AStarSearch() {
Node naechstbesterNode;
naechstbesterNode = Astar_openList.get(getLowestCostNode(Astar_openList));
Astar_closedList.add(Astar_openList.remove(getLowestCostNode(Astar_openList)));
if (naechstbesterNode.getX() == GOAL_NODE.getX() && naechstbesterNode.getY() == GOAL_NODE.getY()) {
naechstbesterNode.AusgabeXY();
GOAL_NODE = naechstbesterNode;
return naechstbesterNode;
}
//oberhalb
openlistInRangerPrüfer(naechstbesterNode.getX(), naechstbesterNode.getY() - 1, Astar_openList, Astar_closedList, naechstbesterNode);
//rechts
openlistInRangerPrüfer(naechstbesterNode.getX() + 1, naechstbesterNode.getY(), Astar_openList, Astar_closedList, naechstbesterNode);
//unterhalb
openlistInRangerPrüfer(naechstbesterNode.getX(), naechstbesterNode.getY() + 1, Astar_openList, Astar_closedList, naechstbesterNode);
//links
openlistInRangerPrüfer(naechstbesterNode.getX() - 1, naechstbesterNode.getY(), Astar_openList, Astar_closedList, naechstbesterNode);
return naechstbesterNode;
} |
8b9c374a-fca5-4171-a61a-d2a85945d64c | private int getLowestCostNode(LinkedList<Node> list) {
int best = list.get(0).getKostenSum();
for (int i = 1; i < list.size(); i++) {
if (list.get(i).getKostenSum() < best) {
best = list.get(i).getKostenSum();
}
}
//get first element with best costs
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getKostenSum() == best) {
return i;
}
}
return 0;
} |
f3afe2f1-b631-4258-8225-3801c7e671b9 | private void openlistInRangerPrüfer(int x, int y, LinkedList<Node> openList, LinkedList<Node> closedList, Node vorher) {
if (isPointInList(x, y, closedList) == false && Feld[x][y] == true && isPointInList(x, y, openList) == false) {
openList.add(new Node(x, y, 1, this.heuristik(x, y), vorher));
}
} |
cbe30a09-539e-4e3e-a3e2-467884b4cb7c | private boolean isPointInList(int x, int y, LinkedList<Node> list) {
for (Node list1 : list) {
if (list1.getX() == x && list1.getY() == y) {
return true;
}
}
return false;
} |
1ba2e768-5e8c-4edc-9203-e1981f0cc613 | private int heuristik(int x, int y) {
int dx = x - GOAL_NODE.getX();
if (dx < 0) {
dx = -dx;
}
int dy = y - GOAL_NODE.getY();
if (dy < 0) {
dy = -dy;
}
return dx + dy;
} |
696a938a-f80a-4c13-a2c7-bb89c670df6d | private void bfsAddNewPathToFrontier(Path currentPath, Node neighbour) {
Path newPath = currentPath.expandPath(neighbour);
_frontier.add(newPath);
_bfsQueue.add(neighbour);
} |
0eb9feb6-e659-437c-9a98-78b6de5e6c70 | private void move(char direction) {
switch (direction) {
case UP:
_currentPosY -= 1;
break;
case RIGHT:
_currentPosX += 1;
break;
case DOWN:
_currentPosY += 1;
break;
case LEFT:
_currentPosX -= 1;
break;
}
} |
4e23fc7d-5f50-4bf5-9a5d-d01b898c2c61 | private void moveTo(Node position) {
_currentPosX = position.getX();
_currentPosY = position.getY();
} |
2ad54a7d-510f-45e6-81cd-aa88556acbee | public void printEnvironment() {
for (int y = 0; y < 10; ++y) {
String line = "";
for (int x = 0; x < 20; ++x) {
line = line + _environment[y][x];
}
System.out.println(line);
}
System.out.println();
} |
43be8eef-3b2a-43e4-adb3-1de86e63e452 | private boolean topIsClearOrGoal() {
return topIsClear() || _environment[_currentPosY - 1][_currentPosX] == GOAL_CHAR;
} |
bf254676-b154-4353-ba0b-5a8a5e8bf00f | private boolean bottomIsClearOrGoal() {
return bottomIsClear() || _environment[_currentPosY + 1][_currentPosX] == GOAL_CHAR;
} |
301dd82d-d219-4190-b953-f543fa25f8bc | private boolean leftIsClearOrGoal() {
return leftIsClear() || _environment[_currentPosY][_currentPosX - 1] == GOAL_CHAR;
} |
d1e0ed16-611f-41ba-8e3f-ce99de42a9cc | private boolean rightIsClearOrGoal() {
return rightIsClear() || _environment[_currentPosY][_currentPosX + 1] == GOAL_CHAR;
} |
2f439b6f-d096-403f-9bee-12c620781cb5 | private boolean topIsClear() {
return _environment[_currentPosY - 1][_currentPosX] == ' ';
} |
7e974c32-486a-45c8-9b88-027a52f76963 | private boolean bottomIsClear() {
return _environment[_currentPosY + 1][_currentPosX] == ' ';
} |
6cc837cc-807e-4795-bd9e-7fd631f70a9d | private boolean leftIsClear() {
return _environment[_currentPosY][_currentPosX - 1] == ' ';
} |
6b60fba5-a760-42ba-84ee-6acfe07f6992 | private boolean rightIsClear() {
return _environment[_currentPosY][_currentPosX + 1] == ' ';
} |
2bc2d504-e904-4bcf-b6cb-2feab5a1e629 | private boolean goalInReach() {
if (topIsGoal()) {
_searchStack.push(UP);
} else if (rightIsGoal()) {
_searchStack.push(RIGHT);
} else if (bottomIsGoal()) {
_searchStack.push(DOWN);
} else if (leftIsGoal()) {
_searchStack.push(LEFT);
} else {
return false;
}
return true;
} |
86f9f07b-a905-4c25-9447-241d85ade58a | private boolean topIsGoal() {
return _environment[_currentPosY - 1][_currentPosX] == GOAL_CHAR;
} |
9b80f243-0b52-4d18-9ea8-6077fa1b84d2 | private boolean bottomIsGoal() {
return _environment[_currentPosY + 1][_currentPosX] == GOAL_CHAR;
} |
443160b9-876d-41dc-8b4f-3f53f3b7b8c9 | private boolean leftIsGoal() {
return _environment[_currentPosY][_currentPosX - 1] == GOAL_CHAR;
} |
9955ddec-fa9e-4cb6-88f1-a2758271becf | private boolean rightIsGoal() {
return _environment[_currentPosY][_currentPosX + 1] == GOAL_CHAR;
} |
83994bc8-b2b1-4127-83d9-7b5eec77168d | private boolean isGoalNode(Node currentNode) {
return currentNode.getX() == GOAL_NODE.getX()
&& currentNode.getY() == GOAL_NODE.getY();
} |
73b9271d-8cb8-495e-bdc5-f08b0a281abf | private void reset() {
_environment = Start.copy2DCharArray(_inputEnvironment);
_searchStack.removeAllElements();
_currentPosX = _startPosX;
_currentPosY = _startPosY;
} |
952ec537-3546-44ed-b99f-e1393d8e277a | public ServerPI(Socket clientSocket, ServerDTP serverDTP)
{
try
{
MyLogger.setup();
} catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
try
{
this.sktControl = clientSocket;
out = new PrintWriter(clientSocket.getOutputStream(), true);
// Iniciar el Server DTP
this.serverDTP = serverDTP;
apuntador = null;
} catch (IOException e)
{
System.out.println("Error creando el flujo de transmisión");
}
} |
9265f7d8-d4ac-4c22-b86e-70d81ca7dc8f | public void run()
{
MyLogger.logger.log(Level.INFO, "Accede un cliente");
while (true)
{
if (sktControl.isClosed())
{
} else
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(sktControl.getInputStream()));
// Mientras el buffer está vacío
while (!in.ready())
{
}
String comando = in.readLine();
MyLogger.logger.log(Level.INFO, comando);
String[] separacion = comando.split(" ");
// Si el usuario se quiere loguear y ya está logueado
if (logueado == true && separacion[0].equalsIgnoreCase("USER"))
{
MyLogger.logger.log(Level.INFO, "El usuario se logueó");
out.println("already_logged");
} else
{
// Si el usuario no se ha logueado y quiere usar los
// comandos
if (logueado == false && !(separacion[0].equalsIgnoreCase("USER") || separacion[0].equalsIgnoreCase("PASS")))
{
MyLogger.logger.log(Level.WARNING, "Debe loguearse");
out.println("please_log");
} else
{
// 1. Comandos sin parametros
if (separacion.length == 1)
{
// Cerrar la conexión
if (comando.equalsIgnoreCase("END"))
{
out.close();
MyLogger.logger.log(Level.INFO, "Termina el cliente");
// Comando LIST
} else if (comando.equalsIgnoreCase("LIST") || comando.equalsIgnoreCase("LS"))
{
String respuestaList = getListOfDirectory(serverDTP.getCurrentPath());
out.println(respuestaList);
} else if (comando.equalsIgnoreCase("ASCII"))
{
isAscii = true;
out.println("ASCII_mode");
MyLogger.logger.log(Level.INFO, "Se elige el modo ASCII");
} else if (comando.equalsIgnoreCase("BINARY"))
{
isAscii = false;
out.println("binary_mode");
MyLogger.logger.log(Level.INFO, "Se elige el modo binario");
} else
{
out.println(ERROR);
MyLogger.logger.log(Level.INFO, "Comando desconocido");
}
}
// 2. Comandos con un parámetro
else if (separacion.length == 2)
{
// Comando CWD
if (separacion[0].equalsIgnoreCase("CWD") || separacion[0].equalsIgnoreCase("CD"))
{
commandCWD(separacion[1]);
}
// Comando LIST
else if (separacion[0].equalsIgnoreCase("LIST") || separacion[0].equalsIgnoreCase("LS"))
{
commandLIST(separacion[1]);
}
// Comando STOR
else if (separacion[0].equalsIgnoreCase("STOR") || separacion[0].equalsIgnoreCase("PUT"))
{
commandSTOR(separacion[1]);
}
// Comando RETR
else if (separacion[0].equalsIgnoreCase("RETR") || (separacion[0].equalsIgnoreCase("GET")))
{
commandRETR(separacion[1]);
}
// Comando DELE
else if (separacion[0].equalsIgnoreCase("DELE") || separacion[0].equalsIgnoreCase("DELETE"))
{
commandDELE(separacion[1]);
}
// Comando RNFR
else if (separacion[0].equalsIgnoreCase("RNFR") || separacion[0].equalsIgnoreCase("SELECT"))
{
commandRNFR(separacion[1]);
}
// Comando RNTO
else if (separacion[0].equalsIgnoreCase("RNTO") || separacion[0].equalsIgnoreCase("RENAME"))
{
commandRNTO(separacion[1]);
}
// Comando USER
else if (separacion[0].equalsIgnoreCase("USER"))
{
usuarioEsperandoAutenticacion = separacion[1];
contadorAutenticacion = 0;
commandUSER();
}
// Comando PASS
else if (separacion[0].equalsIgnoreCase("PASS"))
{
if (contadorAutenticacion == 1)
{
passwordUsuario = separacion[1];
if (commandPASS(usuarioEsperandoAutenticacion, passwordUsuario) == false)
{
passwordUsuario = null;
usuarioEsperandoAutenticacion = null;
MyLogger.logger.log(Level.WARNING, "Errores de autenticación");
} else
{
logueado = true;
MyLogger.logger.log(Level.INFO, "La autenticación fue existosa");
}
} else
{
out.println(ERROR);
MyLogger.logger.log(Level.WARNING, "El password no se ingresa inmediatamente después del usuario");
}
}
}
// 3. Comandos con más de un parámetro
else
{
out.println(ERROR);
MyLogger.logger.log(Level.WARNING, "El comando es incorrecto");
}
}
}
} catch (IOException e)
{
MyLogger.logger.log(Level.WARNING, "Error en el flujo de información");
System.out.println("Error en el flujo de información");
}
}
contadorAutenticacion++;
}
} |
44ef22a0-6475-4b3c-b6c2-7bbbea89e609 | public String getListOfDirectory(String path)
{
File f = new File(serverDTP.getCurrentPath());
if (f.isDirectory())
{
String[] listOfFiles = f.list();
StringBuilder sb = new StringBuilder();
for (String file : listOfFiles)
{
sb.append(file + ";");
}
MyLogger.logger.log(Level.INFO, sb.toString());
return sb.toString();
} else
{
MyLogger.logger.log(Level.WARNING, "El parámetro no es un directorio");
return ERROR;
}
} |
27a631fc-d770-40b1-92c3-843aa4076d94 | public void commandCWD(String rutaRelativa)
{
if (rutaRelativa.equals("/"))
{
serverDTP.setCurrentPath(System.getProperty("user.dir") + "/root");
out.println(SUCCESS);
MyLogger.logger.log(Level.INFO, "Se cambia de directorio");
} else
{
File f = new File(serverDTP.getCurrentPath() + "/" + rutaRelativa);
if (f.exists())
{
if (f.isDirectory())
{
serverDTP.setCurrentPath(serverDTP.getCurrentPath() + "/" + rutaRelativa);
out.println(SUCCESS);
MyLogger.logger.log(Level.INFO, "Se cambia de directorio");
} else
{
out.println(ERROR);
MyLogger.logger.log(Level.WARNING, "La carpeta no existe");
}
} else
{
out.println(ERROR);
MyLogger.logger.log(Level.WARNING, "El archivo no existe");
}
}
} |
b63fb6fd-8a57-419a-9c16-d6eb659d9663 | public void commandUSER()
{
out.println("waiting_pass");
MyLogger.logger.log(Level.INFO, "Se está esperando por el password");
} |
89d9cb6a-3150-4b49-8c83-f7b5675b1250 | public void commandLIST(String ruta)
{
File f = new File(serverDTP.getCurrentPath() + "/" + ruta);
if (f.exists())
{
if (f.isFile())
{
Date fechaModificacion = new Date(f.lastModified());
String resultado = "Tamaño: " + f.length() + " bytes;" + "Oculto: " + f.isHidden() + ";" + "Última modificación: " + fechaModificacion.toString();
out.println(resultado);
MyLogger.logger.log(Level.INFO, resultado);
} else
{
String respuestaList = getListOfDirectory(serverDTP.getCurrentPath());
out.println(respuestaList);
MyLogger.logger.log(Level.INFO, respuestaList);
}
} else
{
out.println(ERROR);
MyLogger.logger.log(Level.WARNING, "El archivo no existe");
}
} |
00927a80-a5c7-436b-a6ea-a52101c32e52 | public void commandSTOR(String rutaArchivo)
{
try
{
Socket sktDatos = serverDTP.socketDatos.accept();
InputStream is = sktDatos.getInputStream();
serverDTP.receiveFile(is, rutaArchivo);
System.out.println("Se recibieron los datos del cliente");
MyLogger.logger.log(Level.INFO, "Se recibieron los datos del cliente");
out.println(SUCCESS);
} catch (Exception e)
{
out.println("ERROR");
MyLogger.logger.log(Level.WARNING, "El archivo no se pudo almacenar");
}
} |
ca460191-3db6-482c-8a60-f4599e78c904 | public void commandRETR(String nombreArchivo)
{
try
{
File f = new File(serverDTP.getCurrentPath() + "/" + nombreArchivo);
if (f.exists() && f.isFile())
{
out.println("successful_retr");
serverDTP.sendFile(nombreArchivo);
MyLogger.logger.log(Level.INFO, "Se envían los datos al cliente");
} else
{
MyLogger.logger.log(Level.WARNING, "El archivo no existe");
out.println("error_retr");
}
} catch (Exception e)
{
MyLogger.logger.log(Level.WARNING, "No se pudo enviar el archivo");
out.println(ERROR);
}
} |
21f3fdc1-2bc6-4077-bd2e-636b84be4dc5 | public void commandDELE(String nombreArchivo)
{
try
{
File f = new File(serverDTP.getCurrentPath() + "/" + nombreArchivo);
if (f.exists() && f.isFile())
{
if (f.delete())
{
MyLogger.logger.log(Level.INFO, "Se elimina el archivo");
out.println("successful_dele");
} else
{
MyLogger.logger.log(Level.WARNING, "No se puede eliminar el archivo");
out.println("error_dele");
}
} else
{
MyLogger.logger.log(Level.WARNING, "El archivo no existe");
out.println("error_dele");
}
} catch (Exception e)
{
MyLogger.logger.log(Level.WARNING, "Hubo problemas en el flujo de la información");
out.println(ERROR);
}
} |
6d0fd2a6-c016-4357-9952-e955bbbf059b | public void commandRNTO(String nuevoNombre)
{
try
{
if (apuntador.exists() && apuntador.isFile() && (apuntador != null))
{
File nuevoArchivo = new File(serverDTP.getCurrentPath() + "/" + nuevoNombre);
if (apuntador.renameTo(nuevoArchivo))
{
MyLogger.logger.log(Level.INFO, "Se cambia el nombre del archivo");
out.println("successful_rename");
} else
{
MyLogger.logger.log(Level.WARNING, "No se pudo renombrar");
out.println("error_rename");
}
} else
{
MyLogger.logger.log(Level.WARNING, "El archivo no existe");
out.println("error_rename");
}
} catch (Exception e)
{
MyLogger.logger.log(Level.WARNING, "No se pudo cambiar el nombre");
out.println(ERROR);
}
} |
98fcdab0-527c-426e-aaad-705685fe43f1 | public boolean commandPASS(String nombreUsuario, String passwordUsuario)
{
if (nombreUsuario == null || passwordUsuario == null)
{
out.println("autentication_error");
return false;
} else
{
try
{
// Leer el listado de Usuarios y contrasenas
BufferedReader reader = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/root/" + "usersftp.txt"));
String line = reader.readLine();
boolean salir = false;
while (line != null && salir == false)
{
line = reader.readLine();
if (line != null)
{
String[] separacion = line.split(";");
if (separacion[0].equalsIgnoreCase(usuarioEsperandoAutenticacion) && separacion[1].equalsIgnoreCase(passwordUsuario))
{
out.println("autentication_success");
logueado = true;
reader.close();
return true;
}
}
}
out.println("autentication_error");
reader.close();
} catch (Exception e)
{
e.printStackTrace();
}
return false;
}
} |
83c246c7-6150-4715-8e16-15f6f06863e2 | public void commandRNFR(String nombreArchivo)
{
try
{
File f = new File(serverDTP.getCurrentPath() + "/" + nombreArchivo);
if (f.exists() && f.isFile())
{
apuntador = f;
MyLogger.logger.log(Level.INFO, "Se selecciona el archivo correctamente");
out.println("successful_rnfr");
} else
{
MyLogger.logger.log(Level.WARNING, "El archivo no existe");
out.println("error_rnfr");
apuntador = null;
}
} catch (Exception e)
{
MyLogger.logger.log(Level.WARNING, "No se pudo seleccionar el archivo");
out.println(ERROR);
apuntador = null;
}
} |
fc4b9162-9134-4135-8cb9-a825d4f6f84c | public ServerDTP(ServerSocket socketDatos)
{
currentPath = System.getProperty("user.dir") + "/root";
this.socketDatos = socketDatos;
} |
0d6d1d23-1e90-4ea8-922b-82cf2f761038 | public String getCurrentPath()
{
return currentPath;
} |
27ebe545-ab52-4f7e-8762-70b7b4c6394f | public void setCurrentPath(String rootPath)
{
this.currentPath = rootPath;
} |
185c13d8-da25-4561-80f7-90389e50a37f | public void receiveFile(InputStream is, String path) throws Exception
{
// Obtener nombre del archivo
String[] particion = path.split("/");
String nombreArchivo = particion[particion.length - 1];
int filesize = 6022386;
int bytesRead;
int current = 0;
byte[] mybytearray = new byte[filesize];
FileOutputStream fos = new FileOutputStream(getCurrentPath() + "/" + nombreArchivo);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do
{
bytesRead = is.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
bos.close();
} |
bd6815b8-9629-4687-b503-6ff92b34235b | public void sendFile(String path)
{
try
{
File myFile = new File(getCurrentPath() + "/" + path);
if (myFile.exists() && myFile.isFile())
{
Socket sktData = socketDatos.accept();
OutputStream out = sktData.getOutputStream();
byte[] mybytearray = new byte[(int) myFile.length() + 1];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
System.out.println("Sending...");
out.write(mybytearray, 0, mybytearray.length);
out.flush();
bis.close();
out.close();
sktData.close();
} else
{
System.out.println("El archivo no existe");
}
} catch (IOException e)
{
e.printStackTrace();
}
} |
d904925f-a510-4d4f-b098-f24cb212cd1c | public static void main(String[] args)
{
// Socket para conexión de cliente - TCP
ServerSocket controlSocketServidor = null;
ServerSocket dataSocketServidor = null;
try
{
controlSocketServidor = new ServerSocket(4000);
dataSocketServidor = new ServerSocket(4001);
System.out.println("Esperando por clientes...");
while (true)
{
// Crear y asignar la conexión de datos a cada cliente
ServerDTP hiloDTP = new ServerDTP(dataSocketServidor);
// Crear y asignar la conexión de control a cada cliente
Socket controlSocket = controlSocketServidor.accept();
ServerPI hiloPI = new ServerPI(controlSocket, hiloDTP);
hiloPI.start();
}
} catch (SocketException e)
{
System.out.println("Error creando el socket");
} catch (IOException e)
{
System.out.println("Error en el flujo de información");
}
} |
74e62561-83e3-494f-bb75-f79cdf13b04b | public static void setup() throws IOException
{
// get the global logger to configure it
logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
// suppress the logging output to the console
Logger rootLogger = Logger.getLogger("");
java.util.logging.Handler[] handlers = rootLogger.getHandlers();
if (handlers[0] instanceof ConsoleHandler)
{
rootLogger.removeHandler(handlers[0]);
}
logger.setLevel(Level.INFO);
fileTxt = new FileHandler("Logging.txt");
fileHTML = new FileHandler("Logging.html");
// create a TXT formatter
formatterTxt = new SimpleFormatter();
fileTxt.setFormatter(formatterTxt);
logger.addHandler(fileTxt);
// create an HTML formatter
formatterHTML = new MyHtmlFormatter();
fileHTML.setFormatter(formatterHTML);
logger.addHandler(fileHTML);
} |
e0f38879-47d9-4d67-969d-11e1809eec18 | public String format(LogRecord rec)
{
StringBuffer buf = new StringBuffer(1000);
buf.append("<tr>\n");
// colorize any levels >= WARNING in red
if (rec.getLevel().intValue() >= Level.WARNING.intValue())
{
buf.append("\t<td style=\"color:red\">");
buf.append("<b>");
buf.append(rec.getLevel());
buf.append("</b>");
} else
{
buf.append("\t<td>");
buf.append(rec.getLevel());
}
buf.append("</td>\n");
buf.append("\t<td>");
buf.append(calcDate(rec.getMillis()));
buf.append("</td>\n");
buf.append("\t<td>");
buf.append(formatMessage(rec));
buf.append("</td>\n");
buf.append("</tr>\n");
return buf.toString();
} |
30c31fa8-5639-4d1d-8a36-7c8e5004739f | private String calcDate(long millisecs)
{
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(millisecs);
return date_format.format(resultdate);
} |
2aecf2af-8d49-4cfc-be40-76bbb2a7f6fa | public String getHead(Handler h)
{
return "<!DOCTYPE html>\n<head>\n<style" + "type=\"text/css\">\n" + "table { width: 100% }\n" + "th { font:bold 10pt Tahoma; }\n" + "td { font:normal 10pt Tahoma; }\n" + "h1 {font:normal 11pt Tahoma;}\n" + "</style>\n" + "</head>\n" + "<body>\n" + "<h1>" + (new Date()) + "</h1>\n" + "<table border=\"0\" cellpadding=\"5\" cellspacing=\"3\">\n" + "<tr align=\"left\">\n" + "\t<th style=\"width:10%\">Loglevel</th>\n" + "\t<th style=\"width:15%\">Time</th>\n"
+ "\t<th style=\"width:75%\">Log Message</th>\n" + "</tr>\n";
} |
806a7944-5a70-4fe3-9ae7-e917ca851dfa | public String getTail(Handler h)
{
return "</table>\n</body>\n</html>";
} |
121db5a3-2987-4ba0-ac73-88ab9c483b03 | static public void main(String[] args) {
if(args.length == 0) {
showHelp();
return;
}
boolean result = false;
try {
if(args[0].compareToIgnoreCase("-version") == 0)
result = showVersion();
else if(args.length == 2 && args[0].compareToIgnoreCase("-createSchema") == 0)
result = exportSchema(args);
else if(args.length == 2 && args[0].compareToIgnoreCase("-export") == 0)
result = exportData(args);
} catch (Exception e) {
result = false;
System.err.println(e.getMessage());
}
if(!result)
showHelp();
} |
5886ea76-b59a-49a2-af97-c60a0627a970 | static private boolean exportSchema(String[] args) throws Exception {
String configFilePath = parseConfigFile(args);
if(configFilePath == null) {
System.err.println("no config file found");
return false;
}
ConfigFile file = new ConfigFile();
file.parse(configFilePath);
ExcelSchemaCreator creator = new ExcelSchemaCreator();
return creator.exportSchema(file);
} |
9659aff9-6588-4097-9d4f-5c21ab03e95f | static private boolean exportData(String[] args) {
return false;
} |
51512c8a-fdb1-47ed-8f8c-b86f9b0bccdf | static private void showHelp() {
String help =
"Usage: excel2db <verb>\r\n" +
"\r\n" +
"Verb: \r\n" +
"-help Show help information\r\n" +
"-version Show version information\r\n" +
"-createSchema -config<config file> Create schema file according to format of excel files, according to config file\r\n" +
"-export -config<config file> Export data of excel files to database, according to config file\r\n" +
"\r\n" ;
System.out.println(help);
} |
09e5f7b6-5c21-499d-9404-e7c41210f947 | static private boolean showVersion() {
String version = "excel2db "
+ InfoBundle.MajorVersion + "."
+ InfoBundle.MinorVersion + "."
+ InfoBundle.SubVersion;
System.out.println(version);
return true;
} |
4e4585a0-15b7-4611-8a29-92cdf97d2c63 | static private String parseConfigFile(String[] args) throws Exception {
String configFile = null;
for(String arg : args) {
if(arg.startsWith("-config")) {
configFile = arg.substring(7);
return configFile;
}
}
throw new Exception("no config file found");
} |
952192b2-127f-4829-905b-396bc91230cb | static public JSONObject loadFromPath(String filePath) {
File file = new File(filePath);
if(!file.exists())
return null;
try {
String source = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
for(String line = reader.readLine(); line != null; line = reader.readLine()) {
line = line.trim();
if(line.startsWith("//"))
continue;
source += line;
source += "\n";
}
JSONObject obj = new JSONObject(source);
return obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} |
f129481d-b9dd-43e9-b97f-f230a086db06 | public String getName() {
return name;
} |
37c656b3-203a-4875-aeae-650b7e4754f0 | public void setName(String name) {
this.name = name;
} |
9936b68a-5ac9-48bc-941d-bedcbefe5305 | public boolean isExport() {
return export;
} |
06e75ddc-39b8-4c8c-ae81-c9c0dcd4e517 | public void setExport(boolean export) {
this.export = export;
} |
b7056bd6-304f-4ed6-958b-2e839ae7b73f | public String getTable() {
return table;
} |
f1d445e9-eabb-4c09-b0cb-d494a784d0c1 | public void setTable(String table) {
this.table = table;
} |
a8684a25-6462-462a-a8fd-9dc24c2b4989 | public String getPrimaryKey() {
return primaryKey;
} |
ff63ae25-adc3-45f5-a212-af109c83cca1 | public void setPrimaryKey(String primaryKey) {
this.primaryKey = primaryKey;
} |
2d7e395e-1fc2-4e33-b594-21cb117d3bc4 | public boolean isDrop() {
return drop;
} |
61f3ac6f-bb99-46b2-9104-fb572a86b2a9 | public void setDrop(boolean drop) {
this.drop = drop;
} |
095144aa-2e85-4418-90f0-30403899bd18 | public Map<String, String> getFieldMap() {
return fieldMap;
} |
9f986540-6bde-45bb-a851-c027a6ee5425 | public void setFieldMap(Map<String, String> fieldMap) {
if(fieldMap == null || fieldMap.size() == 0)
this.fieldMap = null;
else
this.fieldMap = fieldMap;
} |
8b49b622-5370-45ab-9383-fc9000a49b51 | public List<String> getFieldNames() {
return fieldNames;
} |
44dcaa48-154b-46cd-81bd-d18960128a35 | public void setFieldNames(List<String> fieldNames) {
if(fieldNames == null || fieldNames.size() == 0)
this.fieldNames = null;
else
this.fieldNames = fieldNames;
} |
e65eb468-585c-42fe-abde-5ac2515e8379 | @Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof SheetConfig))
return false;
SheetConfig cfgRhs = (SheetConfig)obj;
if(!this.name.equals(cfgRhs.getName())
|| this.export != cfgRhs.isExport()
|| !this.table.equals(cfgRhs.getTable())
|| !this.primaryKey.equals(cfgRhs.getPrimaryKey())
|| this.drop != cfgRhs.isDrop()) {
return false;
}
if((this.fieldMap == null && cfgRhs.getFieldMap() != null)
|| (this.fieldMap != null && cfgRhs.getFieldMap() == null))
return false;
if(this.fieldMap != null && !this.fieldMap.equals(cfgRhs.getFieldMap()))
return false;
if((this.fieldNames == null && cfgRhs.getFieldNames() != null)
|| (this.fieldNames != null && cfgRhs.getFieldNames() == null))
return false;
if(this.fieldNames != null && !this.fieldNames.equals(cfgRhs.getFieldNames()))
return false;
return true;
} |
1254b4de-a1e7-47fc-9b5b-af0dffb37ea0 | public void parse(String configFilePath) throws Exception {
try {
JSONObject root = JsonLoader.loadFromPath(configFilePath);
if(root == null)
throw new Exception("wrong format of config");
// Common
String error = parseCommon(root);
if(error != null)
throw new Exception(error);
// Schema
error = parseSchema(root);
if(error != null)
throw new Exception(error);
// Export
error = parseExport(root);
if(error != null)
throw new Exception(error);
} catch (JSONException e) {
e.printStackTrace(System.err);
throw new Exception("format error in config file");
}
} |
583beb86-5e16-4f10-a682-ef41f7653896 | private String parseCommon(JSONObject root){
try {
sourceFile = root.getString("source");
return null;
} catch (JSONException e) {
return "no source file";
}
} |
5921673f-d134-4d2c-8776-ef63e177d19b | private String parseSchema(JSONObject root) {
if(!root.has("schema"))
return null;
JSONObject schema;
try {
schema = root.getJSONObject("schema");
if(!schema.has("dest"))
return "no dest file specified";
// destFile
destFile = schema.getString("dest");
if(schema.has("heuristics"))
heuristics = schema.getBoolean("heuristics");
if(schema.has("defaultType"))
defaultType = schema.getString("defaultType");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
} |
c3b535a3-0e04-4e01-a915-53c84293a60d | private String parseExport(JSONObject root) {
if(!root.has("export"))
return "no export config";
try {
JSONObject export = root.getJSONObject("export");
// Database
if(!export.has("database"))
return "no database config";
String error = parseDatabase(export);
if(error != null)
return error;
// Sheets
if(export.has("sheets")) {
JSONArray sheets = export.getJSONArray("sheets");
parseSheets(sheets);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
} |
2cb4eb64-670b-4dc3-86cf-3f84207acd7a | private void parseSheets(JSONArray sheets) {
sheetConfigs = new ArrayList<SheetConfig>();
try {
int count = sheets.length();
for(int i=0; i<count; ++ i) {
JSONObject sheet = sheets.getJSONObject(i);
SheetConfig cfgSheet = new SheetConfig();
if(!sheet.has("sheet"))
continue;
cfgSheet.setName(sheet.getString("sheet"));
if(sheet.has("table"))
cfgSheet.setTable(sheet.getString("table"));
if(sheet.has("export"))
cfgSheet.setExport(sheet.getBoolean("export"));
if(!cfgSheet.isExport()) {
sheetConfigs.add(cfgSheet);
continue;
}
if(sheet.has("primary"))
cfgSheet.setPrimaryKey(sheet.getString("primary"));
if(sheet.has("drop"))
cfgSheet.setDrop(sheet.getBoolean("drop"));
if(sheet.has("field_maps")) {
cfgSheet.setFieldNames(null);
Map<String, String> map = new HashMap<String, String>();
JSONObject field_maps = sheet.getJSONObject("field_maps");
Iterator iterator = field_maps.keys();
while(iterator.hasNext()) {
String name = (String) iterator.next();
if(field_maps.isNull(name)) {
map.put(name, null);
} else {
String value = field_maps.getString(name);
map.put(name, value);
}
}
cfgSheet.setFieldMap(map);
} else if(sheet.has("field_names")) {
cfgSheet.setFieldMap(null);
List<String> names = new ArrayList<String>();
JSONArray field_names = sheet.getJSONArray("field_names");
int nameCount = field_names.length();
for(int index=0; index<nameCount; ++ index) {
if(field_names.isNull(index))
names.add(null);
else
names.add(field_names.getString(index));
}
cfgSheet.setFieldNames(names);
}
sheetConfigs.add(cfgSheet);
}
} catch (JSONException e) {
e.printStackTrace();
}
} |
46318449-6d14-4715-9a9f-f6e57b6b5eff | private String parseDatabase(JSONObject export){
try
{
// database
JSONObject database = export.getJSONObject("database");
// database
if(!database.has("jdbc_database"))
return "no jdbc_database found";
jdbcDatabase = database.getString("jdbc_database");
// host
if(database.has("jdbc_host"))
jdbcHost = database.getString("jdbc_host");
else
jdbcHost = "localhost";
// user
if(database.has("jdbc_user"))
jdbcUser = database.getString("jdbc_user");
else
jdbcUser = "root";
// password
if(database.has("jdbc_password"))
jdbcPassword = database.getString("jdbc_password");
else
jdbcPassword = "";
}
catch(JSONException e) {
}
return null;
} |
6f5aae84-4286-4b80-87c0-a265b95778c1 | public String getSourceFile() {
return sourceFile;
} |
a9f2acc3-3d1e-4fb2-b1d0-9c484677582e | public boolean isHeuristics() {
return heuristics;
} |
af538401-7cc9-4f54-91f7-a87ecfd21ea4 | public String getDefaultType() {
return defaultType;
} |
71142b18-1e18-4d63-b7df-46ea2096d00d | public String getDestFile() {
return destFile;
} |
bf1a621c-e660-4828-ba8b-8d78cd5364ce | public List<SheetConfig> getSheetConfigs() {
return sheetConfigs;
} |
d8df1722-aae7-42ae-a983-a28f53767166 | public String getJdbcHost() {
return jdbcHost;
} |
e7069bc0-e690-4978-acae-5e5993f6fb57 | public String getJdbcUser() {
return jdbcUser;
} |
95015bf4-f40d-4803-a826-ca00b63de87f | public String getJdbcPassword() {
return jdbcPassword;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.