I want to use ttorent java lib in my project. I am tried to figure out how it works. When I want to use it as a standalone program and call
./client -o ~ ~/file.torrent -i eth3
there is always 0%. When I tried to use it as a library with simple code like this:
import java.io.File;
import java.net.InetAddress;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.BasicConfigurator;
import com.turn.ttorrent.client.Client;
import com.turn.ttorrent.client.Client.ClientState;
import com.turn.ttorrent.client.SharedTorrent;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
BasicConfigurator.configure();
// Get options
File output = new File("/home/user");
// Get the .torrent file path
File torrentPath = new File("/home/user/file.torrent");
// Start downloading file
try {
SharedTorrent torrent = SharedTorrent.fromFile(torrentPath, output);
System.out.println("Starting client for torrent: "
+ torrent.getName());
Client client = new Client(InetAddress.getLocalHost(),
torrent);
try {
System.out.println("Start to download: " + torrent.getName());
client.download(); // DONE for completion signal
while (!ClientState.SEEDING.equals(client.getState())) {
// Check if there's an error
if (ClientState.ERROR.equals(client.getState())) {
throw new Exception("ttorrent client Error State");
}
// Display statistics
System.out
.printf("%f %% - %d bytes downloaded - %d bytes uploaded\n",
torrent.getCompletion(),
torrent.getDownloaded(),
torrent.getUploaded());
// Wait one second
TimeUnit.SECONDS.sleep(1);
}
System.out.println("download completed.");
} catch (Exception e) {
System.err.println("An error occurs...");
e.printStackTrace(System.err);
} finally {
System.out.println("stop client.");
client.stop();
}
} catch (Exception e) {
System.err.println("An error occurs...");
e.printStackTrace(System.err);
}
}
}
It is always 0% too. I tried to download with this torrent file using some other client and it was ok, so I assume this is no lack of seeds.
Related
Let me summarize my problem I am trying to download a file using java nio in that I have also written code for resuming the file download when you run the program again but my problem is this when there is no internet connection the download process is not stoping( what I meant is when there is no internet the code is not going to the next line no exception nothing it simply waits for the internet to resume .)
package com.jcg.java.nio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DownloadFileFromUrl {
// File Location
private static String filePath ="D:\\path\\app.zip";
// Sample Url Location
private static String sampleUrl = "server_url";
// private static int downloaded;
// This Method Is Used To Download A Sample File From The Url
private static void downloadFileFromUrlUsingNio() {
URL urlObj = null;
ReadableByteChannel rbcObj = null;
FileOutputStream fOutStream = null;
long downloaded=0l;
try {
long startTime = System.currentTimeMillis();
urlObj = new URL(sampleUrl);
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObj.openConnection();
File file=new File("D:\\path\\app.zip");
if(file.exists()){
System.out.println("if condition");
downloaded = file.length();
System.out.println(downloaded);
httpUrlConnection.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else{
httpUrlConnection.setRequestProperty("Range", "bytes=" + downloaded + "-");
}
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
rbcObj = Channels.newChannel(urlObj.openStream());
fOutStream = new FileOutputStream(filePath,true);
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
System.out.println("! File Successfully Downloaded From The Url !");
long endTime = System.currentTimeMillis();
System.out.println(endTime);
System.out.println(endTime-startTime);
// System.out.println(System);
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
} finally {
try {
if(fOutStream != null){
fOutStream.close();
}
if(rbcObj != null) {
rbcObj.close();
}
} catch (IOException ioExObj) {
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
}
}
// } else {
// System.out.println("File Not Present! Please Check!");
// }
}
public static void main(String[] args) {
downloadFileFromUrlUsingNio();
// usingJavaNIO();
}
}
In the above code if you can see the below code of line
fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
this is for downloading the file , when I disable the internet connection(no internet) than the control is not comming to the next line
System.out.println("! File Successfully Downloaded From The Url !");
and not in catch block either
System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
And what I am trying to accomplish is that when there is no internet the process(download) or the channel should close and the rest of the code executes normally but what actually happens is until I reconnect my internet it will not stop(and after connecting internet still it takes time).
So in simple terms my application will even wait for hours to stop the download when there is no internet and there will be no errors.
Please someone help me to overcome this scenario I just want it to stop when there is no internet.
Using Java program I am opening an external application( for example: notepad). How can i get coordinates/location of external application for screen capture/screen-shots.
I can take screen-shots of the whole window, but not for a particular application.
I have already tried "Robot" for screen capturing but not able to capture a particular area as I am not able to find the location and size of the application window.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
public class AppCheck {
public static void main(String[] args) {
System.out.println("***********************");
try {
System.out.println("Opening notepad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("notepad");
try {
int count=0;
while(process.isAlive())
{
System.out.println("process name : " + process.getClass().getName());
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
System.out.println("Process ID : " + handl);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing notepad");
process.destroy();
} catch (Exception ex) {
System.out.println(ex);
}
System.out.println("************************************");
}
}
I am trying to batch some apps installations and I want to do it app by app.
I am trying to get the adb command response into my java program but I don't manage to understand why I don't get anything from an InputStream!
Here is my test code:
import java.io.IOException;
import java.io.InputStream;
public class main_adbStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Process pro = Runtime.getRuntime().exec("platform-tools\\adb.exe -s " + args[0] + ":5555 install -r " + args[1]); // + " >> " + SBCWLogger.getFileHandlerName()
//add installation verification
InputStream is = pro.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
//verification done
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found this answer which is not working, and I do not manage to use pro.getInputStream() properly either.
I also tried most of the answers from here but none of those I tested worked. I successfully read the errors when I don't connect or when the install fails, but not the informational messages as Success at the end of an install. And that is what I want.
EDIT: the code below is working thanks to Onix' answer.
import java.io.IOException;
import java.io.InputStream;
public class main_adbStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Process pro = new ProcessBuilder("platform-tools\\adb.exe", "-s",args[0], "install", "-r", args[1]).start();
//add installation verification
InputStream is = pro.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
//verification done
} catch (IOException e) {
e.printStackTrace();
}
}
}
And to get the famous Success, just write the stream to a file and read the last row.
Try this
Process process = new ProcessBuilder("Full path to adb", "-s", args[0], "install", "-r", args[1]).start();
InputStream is = process.getInputStream();
I'm trying to make use of Tika from a C# project that needs to extract text from a large volume of files.
I started with a simple proof of concept that made use of TikaJAXRS, reading the content of the files and making a HTTP PUT request with the file content to the TikaJAXRS server at http://localhost:9998/tika. This works reasonably well, but it struck me that the overhead of streaming content through HTTP must be slowing things down.
So I decided to write a Java implementation to see how the performance would compare once HTTP is removed from the equation. What I've found is unexpected. It performs much slower, taking roughly twice as long to parse 65 files of various types totaling 16MB. 1200ms for the TikaJAXRS HTTP scenario, 2400ms for the Java app.
Both the TikaJAXRS server and the Tika libraries I'm using are version 1.7. My Java code listing is below. What am I missing, why is my Java app so much slower?
import org.apache.log4j.varia.NullAppender;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.time.StopWatch;
public class TikaTest {
public static void main(String[] args) {
// I'm not interested in what log4j has to say...
org.apache.log4j.BasicConfigurator.configure(new NullAppender());
File folder = new File("C:\\LMDevelopment");
StopWatch timer = new StopWatch();
timer.start();
Collection<File> files = FileUtils.listFiles(folder, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
Tika tikaClient = new Tika();
try {
tikaClient.parseToString(files.iterator().next());
} catch (IOException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
System.out.println("Time to warm up: " + timer.getTime() + "ms");
timer.reset();
timer.start();
for (File f : files)
{
try {
tikaClient.parseToString(f);
} catch (IOException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
timer.stop();
System.out.println("Time to parse all files: " + timer.getTime() + "ms");
}
}
I'm trying to create a simple Flash chat application for educational purposes, but I'm stuck trying to send a policy file from my Java server to the Flash app (after several hours of googling with little luck).
The policy file request reaches the server that sends a harcoded policy xml back to the app, but the Flash app doesn't seem to react to it at all until it gives me a security sandbox error.
I'm loading the policy file using the following code in the client:
Security.loadPolicyFile("xmlsocket://myhostname:" + PORT);
The server recognizes the request as "<policy-file-request/>" and responds by sending the following xml string to the client:
public static final String POLICY_XML =
"<?xml version=\"1.0\"?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=\"*\" to-ports=\"*\" />"
+ "</cross-domain-policy>";
The code used to send it looks like this:
try {
_dataOut.write(PolicyServer.POLICY_XML + (char)0x00);
_dataOut.flush();
System.out.println("Policy sent to client: " + PolicyServer.POLICY_XML);
} catch (Exception e) {
trace(e);
}
Did I mess something up with the xml or is there something else I might have overlooked?
I've seen your approach and after some time trying i wrote a working class, listening on any port you want:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class PolicyServer {
public static final String POLICY_XML =
"<?xml version=\"1.0\"?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=\"*\" to-ports=\"*\" />"
+ "</cross-domain-policy>";
public PolicyServer(){
ServerSocket ss = null;
try {
ss = new ServerSocket(843);
} catch (IOException e) {e.printStackTrace();}
while(true){
try {
final Socket client = ss.accept();
new Thread(new Runnable() {
#Override
public void run() {
try {
client.setSoTimeout(10000); //clean failed connections
client.getOutputStream().write(PolicyServer.POLICY_XML.getBytes());
client.getOutputStream().write(0x00); //write required endbit
client.getOutputStream().flush();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//reading two lines emties flashs buffer and magically it works!
in.readLine();
in.readLine();
} catch (IOException e) {
}
}
}).start();
} catch (Exception e) {}
}
}
}
Try add \n at the end of policy xml.