Начальный вариант проекта

This commit is contained in:
Victor 2013-05-30 21:19:13 +03:00
commit 6e5b0d66e6
21 changed files with 2158 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/build/
/dist/

74
build.xml Normal file
View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="SocketFileTransfer" default="default" basedir=".">
<description>Builds, tests, and runs the project SocketFileTransfer.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="SocketFileTransfer-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

3
manifest.mf Normal file
View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

1411
nbproject/build-impl.xml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
build.xml.data.CRC32=b5a554e2
build.xml.script.CRC32=5cee8796
build.xml.stylesheet.CRC32=28e38971@1.56.0.46
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=b5a554e2
nbproject/build-impl.xml.script.CRC32=1f769548
nbproject/build-impl.xml.stylesheet.CRC32=c6d2a60f@1.56.0.46

View File

@ -0,0 +1,73 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=SocketFileTransfer
application.vendor=aNNiMON
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/SocketFileTransfer.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
includes=**
jar.compress=false
javac.classpath=
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.7
javac.target=1.7
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=com.annimon.socketfiletransfer.Main
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project.
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
# To set system properties for unit tests define test-sys-prop.name=value:
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=windows-1251
src.dir=src
test.src.dir=test

15
nbproject/project.xml Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>SocketFileTransfer</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>

View File

@ -0,0 +1,40 @@
package com.annimon.socketfiletransfer;
import com.annimon.socketfiletransfer.util.Config;
import com.annimon.socketfiletransfer.util.ExceptionHandler;
import java.io.IOException;
import java.net.Socket;
/**
*
* @author aNNiMON
*/
public class Client {
private Socket clientSocket;
private OperationManager manager;
public Client(String host) throws IOException {
clientSocket = new Socket(host, Config.getPort());
manager = new OperationManager();
manager.setSocket(clientSocket);
}
public OperationManager getManager() {
return manager;
}
public void close() {
if (manager != null) {
manager.close();
}
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
}
}

View File

@ -0,0 +1,78 @@
/*
* aNNiMON 2013
*/
package com.annimon.socketfiletransfer;
import com.annimon.socketfiletransfer.util.Config;
import com.annimon.socketfiletransfer.util.ExceptionHandler;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
*
* @author aNNiMON
*/
public class FileOperation implements Operation {
private static final int BUFFER_SIZE = 1024;
private DataInputStream dis;
private DataOutputStream dos;
public FileOperation(DataInputStream dis) {
this.dis = dis;
}
public FileOperation(DataOutputStream dos) {
this.dos = dos;
}
@Override
public void startServerSide() {
FileOutputStream fout = null;
try {
String name = dis.readUTF();
System.out.println("Filename: " + name);
fout = new FileOutputStream(Config.getTransferDir() + name);
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while ((count = dis.read(buffer, 0, BUFFER_SIZE)) != -1) {
fout.write(buffer, 0, count);
}
fout.flush();
fout.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
} finally {
try {
fout.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
}
@Override
public void startClientSide(Object... params) throws Exception {
File file = (File) params[0];
dos.writeInt(OperationManager.MODE_FILE_TRANSFER);
String name = file.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while ((count = fis.read(buffer, 0, BUFFER_SIZE)) != -1) {
dos.write(buffer, 0, count);
}
dos.flush();
fis.close();
}
}

View File

@ -0,0 +1,47 @@
/*
* aNNiMON 2013
*/
package com.annimon.socketfiletransfer;
import com.annimon.socketfiletransfer.util.ExceptionHandler;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
*
* @author aNNiMON
*/
public class Main {
public static void main(String[] args) throws Exception {
if (args[0].equalsIgnoreCase("server")) {
try {
Server server = new Server();
server.listenClients();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
return;
}
String host = "127.0.0.1";
try {
Client client = new Client(getHostIp(host));
if (args[1].equalsIgnoreCase("file")) {
String filePath = args[2];
client.getManager().sendFile( new File(filePath) );
} else if (args[1].equalsIgnoreCase("message")) {
String message = args[2];
client.getManager().sendMessage(message);
}
client.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
private static String getHostIp(String defaultIp) {
return JOptionPane.showInputDialog(null, "Enter server host IP:", defaultIp);
}
}

View File

@ -0,0 +1,28 @@
/*
* aNNiMON 2013
*/
package com.annimon.socketfiletransfer;
/**
*
* @author aNNiMON
*/
public class MessageHistory {
private static String lastMessage = "";
private static StringBuilder allText = new StringBuilder();
public static void addMessage(String message) {
lastMessage = message;
allText.append(message).append("\r\n\r\n");
}
public static String getLastMessage() {
return lastMessage;
}
public static String getAllText() {
return allText.toString();
}
}

View File

@ -0,0 +1,41 @@
/*
* aNNiMON 2013
*/
package com.annimon.socketfiletransfer;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
*
* @author aNNiMON
*/
public class MessageOperation implements Operation {
private DataInputStream dis;
private DataOutputStream dos;
public MessageOperation(DataInputStream dis) {
this.dis = dis;
}
public MessageOperation(DataOutputStream dos) {
this.dos = dos;
}
@Override
public void startServerSide() throws IOException {
String text = dis.readUTF();
MessageHistory.addMessage(text);
}
@Override
public void startClientSide(Object... params) throws Exception {
String message = (String) params[0];
dos.writeInt(OperationManager.MODE_MESSAGE_TRANSFER);
dos.writeUTF(message);
}
}

View File

@ -0,0 +1,13 @@
package com.annimon.socketfiletransfer;
/**
*
* @author aNNiMON
*/
public interface Operation {
void startServerSide() throws Exception;
void startClientSide(Object... params) throws Exception;
}

View File

@ -0,0 +1,67 @@
package com.annimon.socketfiletransfer;
import com.annimon.socketfiletransfer.util.ExceptionHandler;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
* Ïðîñëóøèâàíèå îïåðàöèé ñ äàííûìè.
* @author aNNiMON
*/
public class OperationListener {
protected static final int
MODE_FILE_TRANSFER = 1,
MODE_MESSAGE_TRANSFER = 2;
protected DataInputStream dis;
protected DataOutputStream dos;
public void setSocket(Socket socket) {
try {
dis = new DataInputStream( socket.getInputStream() );
dos = new DataOutputStream( socket.getOutputStream() );
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
public void listenOperation() throws Exception {
int mode = dis.readInt();
System.out.println("Read mode: " + mode);
Operation operation;
switch(mode) {
case MODE_FILE_TRANSFER:
System.out.println("MODE_FILE_TRANSFER");
operation = new FileOperation(dis);
break;
case MODE_MESSAGE_TRANSFER:
operation = new MessageOperation(dis);
break;
default:
return;
}
if (operation != null) {
operation.startServerSide();
}
}
public void close() {
if (dis != null) {
try {
dis.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
if (dos != null) {
try {
dos.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
}
}

View File

@ -0,0 +1,21 @@
package com.annimon.socketfiletransfer;
import java.io.File;
/**
* Ìåíåäæåð îïåðàöèé ñ äàííûìè.
* @author aNNiMON
*/
public class OperationManager extends OperationListener {
public void sendFile(File file) throws Exception {
Operation operation = new FileOperation(dos);
operation.startClientSide(file);
}
public void sendMessage(String message) throws Exception {
Operation operation = new MessageOperation(dos);
operation.startClientSide(message);
}
}

View File

@ -0,0 +1,44 @@
package com.annimon.socketfiletransfer;
import com.annimon.socketfiletransfer.util.Config;
import com.annimon.socketfiletransfer.util.ExceptionHandler;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author aNNiMON
*/
public class Server {
private ServerSocket serverSocket;
public Server() throws IOException {
serverSocket = new ServerSocket(Config.getPort());
}
public void listenClients() {
while (true) {
try {
Socket client = serverSocket.accept();
new Thread(new TransferServer(client)).start();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
break;
}
}
close();
}
private void close() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex);
}
}
}
}

View File

@ -0,0 +1,39 @@
package com.annimon.socketfiletransfer;
import com.annimon.socketfiletransfer.util.ExceptionHandler;
import java.net.Socket;
/**
*
* @author aNNiMON
*/
public class TransferServer implements Runnable {
private OperationListener listener;
public TransferServer(Socket client) {
listener = new OperationListener();
listener.setSocket(client);
printClientInfo(client);
}
@Override
public void run() {
Thread thr = Thread.currentThread();
while(Thread.currentThread() == thr) {
try {
listener.listenOperation();
//Thread.sleep(1);
} catch (Exception ex) {
ExceptionHandler.handle(ex);
break;
}
}
listener.close();
}
private void printClientInfo(Socket client) {
System.out.println( client.getRemoteSocketAddress().toString() );
}
}

View File

@ -0,0 +1,39 @@
package com.annimon.socketfiletransfer.util;
import java.io.File;
/**
*
* @author aNNiMON
*/
public class Config {
private static final String
TYPE = "TYPE",
PORT = "PORT",
TRANSFER_DIR = "TRANSFER_DIR";
public static boolean isServer() {
String type = Configuration.getInstance().getProperty(TYPE);
return (type.equalsIgnoreCase("server"));
}
public static int getPort() {
String value = Configuration.getInstance().getProperty(PORT);
try {
return Integer.parseInt(value);
} catch (NumberFormatException ex) {
ExceptionHandler.handle(ex);
return 7119;
}
}
public static String getTransferDir() {
String path = Configuration.getInstance().getProperty(TRANSFER_DIR);
path = path.trim();
if (!path.endsWith(File.pathSeparator)) {
path = path + File.pathSeparator;
}
return path;
}
}

View File

@ -0,0 +1,63 @@
package com.annimon.socketfiletransfer.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Êëàññ êîíôèãóðàöèè.
* @author aNNiMON
*/
class Configuration {
private static final String PROPERTY_RESOURCE = "config.ini";
private static Configuration instance;
static synchronized Configuration getInstance() {
if (instance == null) {
instance = new Configuration();
}
return instance;
}
private Properties properties;
private Configuration() {
properties = new Properties();
readProperties();
}
public String getProperty(String key) {
return properties.getProperty(key);
}
private void readProperties() {
// Åñëè ðÿäîì ñ ïðèëîæåíèåì íåò ôàéëà config.ini, òî ÷èòàåì èç ðåñóðñîâ.
InputStream stream = getInputStreamFromFile();
if (stream == null) {
stream = getClass().getResourceAsStream("/" + PROPERTY_RESOURCE);
}
try {
properties.load(stream);
stream.close();
} catch (IOException ex) {
ExceptionHandler.handle(ex, "read property");
}
}
private InputStream getInputStreamFromFile() {
File file = new File(PROPERTY_RESOURCE);
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException ex) {
return null;
}
}
return null;
}
}

View File

@ -0,0 +1,49 @@
package com.annimon.socketfiletransfer.util;
/**
* Êëàññ îáðàáîòêè èñêëþ÷èòåëüíûõ ñèòóàöèé.
* @author aNNiMON
*/
public class ExceptionHandler {
private static enum HANDLE_MODE {
NO_LOG, LOG_STACK_TRACE
};
private static HANDLE_MODE mode = HANDLE_MODE.LOG_STACK_TRACE;
/**
* Óñòàíîâêà ðåæèìà, êîãäà âñå ñîîáùåíèÿ èãíîðèðóþòñÿ.
*/
public static void setNoLogMode() {
ExceptionHandler.mode = HANDLE_MODE.NO_LOG;
}
/**
* Óñòàíîâêà ðåæèìà âûâîäà ëîãîâ íà êîíñîëü.
* Èñïîëüçóåòñÿ òðàññèðîâêà ñòåêà.
*/
public static void setStackTraceMode() {
ExceptionHandler.mode = HANDLE_MODE.LOG_STACK_TRACE;
}
public static void handle(Throwable throwable) {
if (mode == HANDLE_MODE.LOG_STACK_TRACE) {
throwable.printStackTrace();
}
}
public static void handle(Throwable throwable, String comment) {
if (mode == HANDLE_MODE.LOG_STACK_TRACE) {
System.out.println(comment);
handle(throwable);
}
}
public static void handle(String comment) {
if (mode == HANDLE_MODE.LOG_STACK_TRACE) {
System.out.println(comment);
handle(new Throwable(comment));
}
}
}

3
src/config.ini Normal file
View File

@ -0,0 +1,3 @@
TYPE=server
PORT=7119
TRANSFER_DIR=E: