Skip to content
Closed
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
11 changes: 11 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.test.redirectTestOutputToFile>true</maven.test.redirectTestOutputToFile>
</properties>

<repositories>
Expand Down Expand Up @@ -173,6 +174,16 @@
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<argLine>-Xmx512m</argLine>
<redirectTestOutputToFile>${maven.test.redirectTestOutputToFile}</redirectTestOutputToFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
2 changes: 1 addition & 1 deletion src/main/java/com/turn/ttorrent/cli/TorrentMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public static void main(String[] args) {
torrent = Torrent.create(source, announceURI, creator);
}

torrent.save(fos);
fos.write(torrent.getEncoded());
} else {
Torrent.load(new File(filenameValue), true);
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/com/turn/ttorrent/common/Torrent.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
Expand All @@ -49,6 +48,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -396,11 +396,11 @@ public boolean isSeeder() {
/**
* Save this torrent meta-info structure into a .torrent file.
*
* @param output The stream to write to.
* @param file The file to write to.
* @throws IOException If an I/O error occurs while writing the file.
*/
public void save(OutputStream output) throws IOException {
output.write(this.getEncoded());
public void save(File file) throws IOException {
FileUtils.writeByteArrayToFile(file, this.getEncoded());
}

public static byte[] hash(byte[] data) throws NoSuchAlgorithmException {
Expand Down
16 changes: 12 additions & 4 deletions src/main/java/com/turn/ttorrent/tracker/Tracker.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
Expand All @@ -39,7 +40,7 @@
* <p>
* The tracker usually listens on port 6969 (the standard BitTorrent tracker
* port). Torrents must be registered directly to this tracker with the
* {@link #announce(TrackedTorrent torrent)}</code> method.
* {@link #announce(Torrent torrent)}</code> method.
* </p>
*
* @author mpetazzoni
Expand Down Expand Up @@ -193,7 +194,8 @@ public Collection<TrackedTorrent> getTrackedTorrents() {
* different from the supplied Torrent object if the tracker already
* contained a torrent with the same hash.
*/
public synchronized TrackedTorrent announce(TrackedTorrent torrent) {
public synchronized TrackedTorrent announce(Torrent torrent)
throws IOException, NoSuchAlgorithmException {
TrackedTorrent existing = this.torrents.get(torrent.getHexInfoHash());

if (existing != null) {
Expand All @@ -202,10 +204,16 @@ public synchronized TrackedTorrent announce(TrackedTorrent torrent) {
return existing;
}

this.torrents.put(torrent.getHexInfoHash(), torrent);
final TrackedTorrent result;
if (torrent instanceof TrackedTorrent) {
result = (TrackedTorrent)torrent;
} else {
result = new TrackedTorrent(torrent);
}
this.torrents.put(torrent.getHexInfoHash(), result);
logger.info("Registered new torrent for '{}' with hash {}.",
torrent.getName(), torrent.getHexInfoHash());
return torrent;
return result;
}

/**
Expand Down
137 changes: 137 additions & 0 deletions src/test/java/com/turn/ttorrent/TempFiles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package com.turn.ttorrent;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.FileUtils;

public class TempFiles {

private static final File ourCurrentTempDir = new File(FileUtils.getTempDirectory(), "ttorrent-test");

private static final Random ourRandom = new Random();

private final File myCurrentTempDir;
private final List<File> myFilesToDelete = new ArrayList<File>();
private final Thread myShutdownHook;
private volatile boolean myInsideShutdownHook;

public TempFiles() {
myCurrentTempDir = ourCurrentTempDir;
if (!myCurrentTempDir.isDirectory() && !myCurrentTempDir.mkdirs()) {

throw new IllegalStateException(
"Temp directory is not a directory, was deleted by some process: "
+ myCurrentTempDir.getAbsolutePath());
}

myShutdownHook = new Thread(new Runnable() {
public void run() {
myInsideShutdownHook = true;
cleanup();
}
});
Runtime.getRuntime().addShutdownHook(myShutdownHook);
}

private File doCreateTempDir(String prefix, String suffix)
throws IOException {
prefix = prefix == null ? "" : prefix;
suffix = suffix == null ? ".tmp" : suffix;

do {
int count = ourRandom.nextInt();
final File f = new File(myCurrentTempDir, prefix + count + suffix);
if (!f.exists() && f.mkdirs()) {
return f.getCanonicalFile();
}
} while (true);

}

private File doCreateTempFile(String prefix, String suffix)
throws IOException {
final File file = doCreateTempDir(prefix, suffix);
file.delete();
file.createNewFile();
return file;
}

public final File createTempFile() throws IOException {
File tempFile = doCreateTempFile("test", null);
registerAsTempFile(tempFile);
return tempFile;
}

public void registerAsTempFile(final File tempFile) {
myFilesToDelete.add(tempFile);
}

public final File createTempFile(int size) throws IOException {
File tempFile = createTempFile();
int bufLen = Math.min(8 * 1024, size);
if (bufLen == 0) return tempFile;
final OutputStream fos = new BufferedOutputStream(new FileOutputStream(tempFile));
try {
byte[] buf = new byte[bufLen];
ourRandom.nextBytes(buf);

int numWritten = 0;
for (int i = 0; i < size / buf.length; i++) {
fos.write(buf);
numWritten += buf.length;
}

if (size > numWritten) {
fos.write(buf, 0, size - numWritten);
}
} finally {
fos.close();
}

return tempFile;
}

/**
* Returns a File object for created temp directory.
* Also stores the value into this object accessed with {@link #getCurrentTempDir()}
*
* @return a File object for created temp directory
* @throws IOException if directory creation fails.
*/
public final File createTempDir() throws IOException {
File f = doCreateTempDir("test", "");
registerAsTempFile(f);
return f;
}

/**
* Returns the current directory used by the test or null if no test is running or no directory is created yet.
*
* @return see above
*/
public File getCurrentTempDir() {
return myCurrentTempDir;
}

public void cleanup() {
try {
for (File file : myFilesToDelete) {
FileUtils.deleteQuietly(file);
}

myFilesToDelete.clear();
FileUtils.deleteQuietly(ourCurrentTempDir);
} finally {
if (!myInsideShutdownHook) {
Runtime.getRuntime().removeShutdownHook(myShutdownHook);
}
}
}
}
28 changes: 28 additions & 0 deletions src/test/java/com/turn/ttorrent/WaitFor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.turn.ttorrent;

public abstract class WaitFor {

private static final long DEFAULT_WAIT_TIMEOUT = 40 * 1000;

private static final long DEFAULT_POLL_INTERVAL = 100;

protected WaitFor() {
this(DEFAULT_WAIT_TIMEOUT);
}

protected WaitFor(long timeout) {
this(timeout, DEFAULT_POLL_INTERVAL);
}

protected WaitFor(long timeout, long interval) {
long started = System.currentTimeMillis();
try {
while (!condition() && System.currentTimeMillis() - started < timeout) {
Thread.sleep(interval);
}
} catch (InterruptedException ignored) {
}
}

protected abstract boolean condition();
}
47 changes: 47 additions & 0 deletions src/test/java/com/turn/ttorrent/common/TorrentTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.turn.ttorrent.common;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

@Test
public class TorrentTest {

private static final Logger logger =
LoggerFactory.getLogger(TorrentTest.class);

@BeforeMethod(alwaysRun = true)
protected void setUp(Method testMethod) throws Exception {
String testName = testMethod.getDeclaringClass().getSimpleName() + "." + testMethod.getName();
logger.trace("Test starting: " + testName);
}

@AfterMethod(alwaysRun = true)
protected void tearDown(Method testMethod) throws Exception {
String testName = testMethod.getDeclaringClass().getSimpleName() + "." + testMethod.getName();
logger.trace("Test finished: " + testName);
}

public void test_create_torrent() throws Exception {
URI announceURI = new URI("http://localhost:6969/announce");
String createdBy = "Test";
Torrent t = Torrent.create(new File("src/test/resources/parentFiles/file1.jar"), announceURI, createdBy);
assertEquals(createdBy, t.getCreatedBy());
assertEquals(announceURI, t.getAnnounceList().get(0).get(0));
}

public void load_torrent_created_by_utorrent() throws Exception {
Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent"));
assertEquals(new URI("http://localhost:6969/announce"), t.getAnnounceList().get(0).get(0));
assertEquals("B92D38046C76D73948E14C42DF992CAF25489D08", t.getHexInfoHash());
assertEquals("uTorrent/3130", t.getCreatedBy());
}
}
Loading