I am trying to create TFTPClient using Apache Commons Net to put file on Server (AIX OS) and TFTP service is running on that Server, there isn't any exception raised while running the below code and it seems that everything is ok, but the file didn't put on the server.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.tftp.TFTP;
import org.apache.commons.net.tftp.TFTPClient;
public class Test {
/**
* #param args
* #throws IOException
* #throws SocketException
*/
public static void main(String[] args) throws SocketException, IOException {
int timeout=5000;
String host="192.168.1.20";
int port=22;
TFTPClient tftpClient=new TFTPClient();
tftpClient.setDefaultTimeout(60000);
tftpClient.open(69);
tftpClient.setSoTimeout(timeout);
System.out.println("DONE");
FileInputStream input = null;
File file;
file = new File("D:\\project.ear");
input = new FileInputStream(file);
try{
tftpClient.sendFile("/home/dev/project.ear", TFTP.BINARY_MODE, input, host);
}
catch (UnknownHostException e)
{
System.err.println("Error: could not resolve hostname.");
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("DONE2");
tftpClient.close();
}
}
the output of the above code was:
DONE
DONE2
which means that everything is OK but i didn't find the file in the directory specified in code.
please advice.
If you still need help, I think you should try call tftpClient.sendFile method this way:
tftpClient.sendFile("/home/dev/project.ear", TFTP.BINARY_MODE, input, InetAddress.getByName(host));
While using InetAddress.getByName(host) it should determine your host ip address either by ip string representation or hostname, as it says here. Hope it works this way.
Related
I'm trying to create a new excel file with just "hello" in it.
Here's my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author kamal
*/
public class JavaApplication4 {
private static String dir = "";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
JFileChooser jc = new JFileChooser();
jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int output = jc.showOpenDialog(null);
if(output == JFileChooser.APPROVE_OPTION){
File f = jc.getSelectedFile();
String directory = f.getAbsolutePath();
setDir(directory);
}
FileOutputStream out = new FileOutputStream(new File(getDir()+"\\Book2.xlsx"));
FileInputStream in = new FileInputStream(new File(getDir()+"\\Book2.xlsx"));
org.apache.poi.ss.usermodel.Workbook workbook = new XSSFWorkbook(in);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0).createCell(0).setCellValue("hello");
workbook.write(out);
workbook.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #return the dir
*/
public static String getDir() {
return dir;
}
/**
* #param dir the dir to set
*/
public static void setDir(String directory) {
dir = directory;
}
}
..And when I run it I get the following error:
Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at javaapplication4.JavaApplication4.main(JavaApplication4.java:46)
C:\Users\kamal\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 7 seconds)
I looked up this code in youtube and it's same but i'm not sure why am i getting the error? Can you help me with this?
I think the most likely explanations are that either the file is corrupt, or it is an older format spreadsheet file that XSSFWorkbook does not understand.
It is unlikely anyone can give you a definite diagnosis without looking at the file itself.
Okay. Today I encountered the same problem . The server was linux and the excel file is copied from windows to linux through winscp. Winscp has options like transferring the file in binary mode , text mode etc. When we copy the excel file through text mode , I got the same error you mentioned. The error got resolved when I copy the excel file using binary mode. To summarize , this issue came because we copied excel file from windows to linux. Just make sure you are copying in binary mode if using winscp. Make sure the file is copied correctly.
I was facing the same problem. I did create the Excel file by doing right click inside the folder and then ->New->Microsoft Excel Worksheet.
As a trial I removed this file and then created the new Excel through Start Menu->Microsoft Office->Excel
It worked for me, Hopefully same will work for you too.
I’m using java.net.URL.openStream() to access a HTTPS resource. The returned stream is incomplete for some URLs: for the example below, it yields a 1,105,724 byte-file whereas the same URL accessed from a browser yields a 5,755,858 byte-file (even when "disabling" Content-Encoding).
And it doesn’t even throw an exception.
What am I missing?
import static java.nio.file.Files.copy;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Paths;
public class Test {
public static void main(String... args) throws IOException {
try (final InputStream in = new URL(
"https://upload.wikimedia.org/wikipedia/commons/9/95/Germany_%28orthographic_projection%29.svg").openStream()) {
copy(in, Paths.get("germany.svg"));
}
}
}
Edit
I’ve tested this code a lot of times (on different networks, but always on JRE 1.8.0_60 / Mac OS X 10.11.4), and sometimes it’s suddenly "starting to work".
However, switching to another of my problematic URLs (e.g. "https://upload.wikimedia.org/wikipedia/commons/c/ce/Andorra_in_Europe_%28zoomed%29.svg") enables me to reproduce the issue.
Does this mean that it is a server issue? I’ve never seen it on a browser though.
It's working fine.
As others have suggested there may be a problem with your network, try connecting to another network.
package test;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class TestMain2 {
public static void main(String[] args) {
System.out.println("Started");
try (final InputStream in = new URL(
"https://upload.wikimedia.org/wikipedia/commons/9/95/Germany_%28orthographic_projection%29.svg")
.openStream()) {
Path outputFile = Paths.get("test.svg");
Files.copy(in, outputFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Output file size : " + outputFile.toFile().length());
System.out.println("Finished");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output
Started
Output file size : 5755858
Finished
I created a file helloworld.txt. Now I'm reading from the file and then I want to load the contents of the file into the cache, and whenever the cache is updated, it should write to the file as well.
This is my code so far:
Please tell me what to do to load the cache and then write from the cache to the file, as the instructions are not clear from Apache Ignite documentation.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteException;
import org.apache.ignite.Ignition;
import org.apache.ignite.examples.ExampleNodeStartup;
import org.apache.ignite.examples.ExamplesUtils;
public class FileRead {
/** Cache name. */
private static final String CACHE_NAME = "FileCache";
/** Heap size required to run this example. */
public static final int MIN_MEMORY = 512 * 1024 * 1024;
/**
* Executes example.
*
* #param args Command line arguments, none required.
* #throws IgniteException If example execution failed.
*/
public static void main(String[] args) throws IgniteException {
ExamplesUtils.checkMinMemory(MIN_MEMORY);
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
System.out.println();
try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(CACHE_NAME)) {
long start = System.currentTimeMillis();
try (IgniteDataStreamer<Integer, String> stmr = ignite.dataStreamer(CACHE_NAME)) {
// Configure loader.
stmr.perNodeBufferSize(1024);
stmr.perNodeParallelOperations(8);
///FileReads();
try {
BufferedReader in = new BufferedReader
(new FileReader("/Users/akritibahal/Desktop/helloworld.txt"));
String str;
int i=0;
while ((str = in.readLine()) != null) {
System.out.println(str);
stmr.addData(i,str);
i++;
}
System.out.println("Loaded " + i + " keys.");
}
catch (IOException e) {
}
}
}
}
}
}
For information on how to load the cache from a persistence store please refer to this page: https://apacheignite.readme.io/docs/data-loading
You have two options:
Start a client node, create IgniteDataStreamer and use it to load the data. Simply call addData() for each line in the file.
Implement CacheStore.loadCache() method, provide the implementation in the cache configuration and call IgniteCache.loadCache().
Second approach will require to have the file on all server nodes, by there will be no communication between nodes, so most likely it will be faster.
I searched google, this site and JavaRanch and I can not find an answer.
My program needs to obtain proxies from a selected file(I got that done using java gui FileChooser class and RandomAccessFile)
Then I need to verify the proxies starting with the one that is first in the txt file. It will try to connect to some site or port to verify if the connection was successful.If the connection was successful (I got a positive response) it will add the proxy to a list of proxies and then get and check next one in the list until it is done.
I know how to do this but I got a little problem. My Problem is that this process needs to be independent of connection speed because someone may set 15000(milliseconds) timeout for the connection to be dealt with and set 100 threads and then none of the proxies would come out working because connection is too slow.
I heard of a method called pinging to check proxies,but I do not know how to use it in java.
Could anyone give me solution or at least classes I could use.
Ok I found a solution and it is easy.
What I used it InetAddress.isReachable() method along with some HttpClient by Apache. For proxy checking I used blanksite.com because all I need is check connectability and not speed of proxies.
So here is the code(Including input from file, but it is not gui, YET):
/* compile with
java -cp .;httpclient-4.5.1.jar;httpcore-4.4.3.jar ProxyMat
run with
java -cp .;httpclient-4.5.1.jar;httpcore-4.4.3.jar;commons-logging-1.2.jar ProxyMat
put one proxy to check per line in the proxies.txt file in the form
some.host.com:8080
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
public class ProxyMat{
File file=null;
static RandomAccessFile read=null;
public ProxyMat(){
file=new File("proxies.txt");
try {
read=new RandomAccessFile(file,"rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void checkproxies(){
try{
String line;
for(int i=0;i<25;i++){
if((line=read.readLine())!=null){
System.out.println(line);
String[] hp=line.split(":");
InetAddress addr=InetAddress.getByName(hp[0]);
if(addr.isReachable(5000)){
System.out.println("reached");
ensocketize(hp[0],Integer.parseInt(hp[1]));
}
}
}
}catch(Exception ex){ex.printStackTrace();}
}
public void ensocketize(String host,int port){
try{
File pros=new File("working.txt");
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet("http://blanksite.com/");
HttpHost proxy=new HttpHost(host,port);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
HttpResponse response=client.execute(get);
HttpEntity enti=response.getEntity();
if(response!=null){
System.out.println(response.getStatusLine());
System.out.println(response.toString());
System.out.println(host+":"+port+" ## working");
}
}catch(Exception ex){System.out.println("Proxy failed");}
}
public static void main(String[] args){
ProxyMat mat=new ProxyMat();
mat.checkproxies();
}
}
I have written the code which downloads the file from FTP server. Since I have my FTP server locally and I want to access like "ftp://localhost/alfresco". It was alfresco's FTP.
I have the following Code
public class FtpTransfer {
public static final void main(String[] args)
{
FTPClient ftp = new FTPClient();
FileOutputStream br = null;
try
{
ftp.connect("ftp://localhost/alfresco");
ftp.login("admin", "admin");
String file = "KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";
br = new FileOutputStream("file");
ftp.retrieveFile("/"+file, br);
System.out.println("Downloaded...");
}
catch(IOException exception) {
System.out.println("Error : "+exception);
}
}
}
The following exception occurs.
Error : java.net.UnknownHostException: ftp://localhost/alfresco
Please let me know how should I give the FTP Host Address?
FTPClient f = new FTPClient();
f.connect("localhost");
f.login(username, password);
FTPFile[] files = listFiles(directory);
Also See
Article from JavaWorld
JavaDoc
Here is an example demonstrating connection to a server, changing present working directory, listing files in a directory and downloading a file to some specified directory.
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpTransfer {
public static final void main(String[] args) throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect("ftp.somedomain.com"); // or "localhost" in your case
System.out.println("login: "+ftp.login("username", "pass"));
ftp.changeWorkingDirectory("folder/subfolder/");
// list the files of the current directory
FTPFile[] files = ftp.listFiles();
System.out.println("Listed "+files.length+" files.");
for(FTPFile file : files) {
System.out.println(file.getName());
}
// lets pretend there is a JPEG image in the present folder that we want to copy to the desktop (on a windows machine)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // don't forget to change to binary mode! or you will have a scrambled image!
FileOutputStream br = new FileOutputStream("C:\\Documents and Settings\\casonkl\\Desktop\\my_downloaded_image_new_name.jpg");
ftp.retrieveFile("name_of_image_on_server.jpg", br);
ftp.disconnect();
}
}
Try remove protocol ("ftp://") from your url.
And please, look at the example.
The FTPClient.connect() method takes the name of a server, not a URL. Try:
ftp.connect("localhost");
Also, you may need to put alfresco somewhere else. If it's part of the file path,
String file = "alfresco/KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";