How to create a commons-net FTPClient from a URL - java

Is there a way to construct an FTPClient instance from a URL such as ftp://user:pass#foo.bar:2121/path, similar to FtpURLConnection in the JDK?

If your problem is the parsing then use the code below to parse and then just create a wrapper class ...
import java.net.; import java.io.;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " +
aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
} }
Here's the output displayed by the program:
protocol = http
authority = java.sun.com:80
host = java.sun.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

There is no direct constructor available for it,
You can use something
FTPClient f = new FTPClient();
f.connect(server);
f.login(username, password);

Related

How many parellel connection HTTPClient can make

Below is the code which we are using to call Microsoft Dynamics. I want to know how many parallel connection this code can create or how many parallel request it can send.
HttpClient client = new HttpClient();
client.getParams().setParameter(CredentialsProvider.PROVIDER, new ConsoleAuthPrompter(logger));
String strURL = getstringURL();
String strSoapAction = "";
strSoapAction = getSoapAction();
PostMethod httppost = new PostMethod(strURL);
String ContetType = getContentType();
RequestEntity entity = new StringRequestEntity(getSOAPxml(),"application/json", "utf-8");
httppost.setRequestEntity(entity);
httppost.setRequestHeader("SOAPAction", strSoapAction);
httppost.setDoAuthentication(true);
try {
// execute the GET
int status = client.executeMethod(httppost);
if (httppost.getStatusCode() == 200)
setReply_SOAPxml(httppost.getResponseBodyAsString());
else {
logger.error("Server Replied with Error :"
+ httppost.getStatusCode() + " "
+ httppost.getStatusText() + " "
+ httppost.getResponseBodyAsString());
throw new Exception("Server Replied with Error : ["
+ httppost.getStatusLine().toString() + "] "
+ httppost.getStatusCode() + " "
+ httppost.getStatusText() + " "
+ httppost.getResponseBodyAsString());
}
} finally {
// release any connection resources used by the method
httppost.releaseConnection();
}
}

Dispatch File from AS400 to Mainframe using FTPS

Currently, My system send file from AS400 to Mainframe by FTP. The downstream Mainframe system will not support FTP any more. FTPS will be the only way to send files to it.
Currently we use com.ibm.as400.access.FTP and this package to execute FTP command. I want to know What package can be used by FTPS from AS400 to Mainframe.
currently ftp code is as follows:
boolean FTPFile(String filepath, String filename, String country) {
String ftpresult = "";
String region = bundle.getString("region." + country);
FTP ftp = new FTP(ftpHost, ftpId, ftpPw);
try {
if (country.equals("766") || country.equals("858")
|| country.equals("761") || country.equals("836")) {
ftp.setDataTransferType(FTP.BINARY);
}
if (ftp.connect()) {
getLogMsg().append("FTPing SIF file. Region = " + region,
LogMsg.TEXT_MSG);
String sendname = "'" + ftpDataset + country + ".LSIFATB'";
getLogMsg().append(
"sending file: = " + filepath + filename + " as "
+ sendname, LogMsg.TEXT_MSG);
// Korea
if (country.equals("766") || country.equals("761")) {
ftp.issueCommand("ltype c 933");
// ftpresult = ftp.issueCommand("type b 6");
}
// Taiwan
if (country.equals("858") || country.equals("836")) {
ftp.issueCommand("ltype c 937");
// ftpresult = ftp.issueCommand("type b 8");
}
boolean ftp_res = ftp.put(filepath + filename, sendname);
// System.out.println("ftp result: " + ftp_res);
getLogMsg().append("ftp result (sending SIF): " + ftp_res,
LogMsg.TEXT_MSG);
ftpresult = ftp.issueCommand("site filetype=jes");
System.out.println("ftp command result = " + ftpresult);
String jobname = bundle.getString("app.sif.jobname." + country);
// String jobname = "CISBL30D";
ftp.setDataTransferType(FTP.ASCII);
ftp_res = ftp.put(bundle.getString("app.sif.directory") + "/"
+ region + country + "/jcl.txt", "jcl.txt '" + jobname
+ "'");
getLogMsg().append("ftp result (sending jcl): " + ftp_res,
LogMsg.TEXT_MSG);
return true;
}
} catch(...) {}
}
I've used the Apache COMMONS Net module to do normal FTP.
It does have a FTPSClient class that should do what you want.

I can login a webpage (aspx) with python but i can't with JSoup

import requests as rq
url = "https://ogrotomasyon.uludag.edu.tr/login.aspx?un="
data = { "__EVENTTARGET" : "", "__EVENTARGUMENT" : "",
"__VIEWSTATE" : "",
"__VIEWSTATEGENERATOR" : "C2EE9ABB",
"__EVENTVALIDATION" : "",
"un":"USERNAME", "pw":"PASSWORD", "ok22": "Giriş"}
s = rq.Session()
a = s.get(url, verify=0)
print(a.text)
d1 = input()
d2 = input()
data["__VIEWSTATE"] = d1
data["__EVENTVALIDATION"] = d2
a = s.post(url, data=data, verify=0)
s.get(a.url)
print(a.url)
I can login the system with this code when i copy __VIEWSTATE and __EVENTVALIDATION truely.
CAREFULL : I'm using one session. If i use just 'rq.get("URL")' i cannot log in. I have to use one and always same session
public static void main(String[] args) {
try {
Connection.Response first = Jsoup.connect("https://ogrotomasyon.uludag.edu.tr/login.aspx")
.validateTLSCertificates(false)
.method(Connection.Method.GET)
.execute();
Elements form = first.parse().select("form");
Elements inputs = form.select("input");
System.out.println(inputs.get(0).id() + " " + inputs.get(0).val());
System.out.println(inputs.get(1).id() + " " + inputs.get(1).val());
System.out.println(inputs.get(2).id() + " " + inputs.get(2).val());
System.out.println(inputs.get(3).id() + " " + inputs.get(3).val());
System.out.println(inputs.get(4).id() + " " + inputs.get(4).val());
System.out.println(inputs.get(7).id() + " " + inputs.get(7).val());
Document second = Jsoup.connect("https://ogrotomasyon.uludag.edu.tr/login.aspx")
.validateTLSCertificates(false)
.data(inputs.get(0).id(), inputs.get(0).val())
.data(inputs.get(1).id(), inputs.get(1).val())
.data(inputs.get(2).id(), inputs.get(2).val())
.data(inputs.get(3).id(), inputs.get(3).val())
.data(inputs.get(4).id(), inputs.get(4).val())
.data("un", "USERNAME")
.data("pw", "PASSWORD")
.data(inputs.get(7).id(), inputs.get(7).val())
.post();
System.out.println(second.text());
} catch (IOException e) {
e.printStackTrace();
}
}
}
But i can't log in with this code. Actually sometimes i can but few times it "throws java.net.UnknownHostException"
How can i connect via 2nd code?

Java BufferedWriter file content is empty [duplicate]

This question already has answers here:
Bufferedwriter works, but file empty?
(4 answers)
Closed 6 years ago.
I want to create One file with .cfg extension and content of this file must be in below format
define host {
host_name test.testing.local
alias Server 1
address 192.168.1.111
check_command check-host-alive
max_check_attempts 10
check_interval 5
retry_interval 5
active_checks_enabled 1
passive_checks_enabled 1
check_period 24x7
register 1
}
For this I am using below code
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/addNewHost")
public Response AddNewHost(String json) {
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
HostObj hostObj = new HostObj();
hostObj.hostname = innerJsonObj.getString("hostname");
hostObj.ipaddress = innerJsonObj.getString("ipaddress");
hostObj.alias = innerJsonObj.getString("alias");
hostObj.check_command = innerJsonObj.getString("check_command");
hostObj.notification_period = innerJsonObj.getString("notification_period");
hostObj.max_check_attempts = innerJsonObj.getInt("max_check_attempts");
hostObj.active_checks_enabled = innerJsonObj.getInt("active_checks_enabled");
hostObj.passive_checks_enabled = innerJsonObj.getInt("passive_checks_enabled");
hostObj.register = innerJsonObj.getBoolean("register");
hostObj.chIntervalInMinutes = innerJsonObj.getInt("chIntervalInMinutes");
hostObj.retryIntervalInMinutes = innerJsonObj.getInt("retryIntervalInMinutes");
hostObj.contact_groups = innerJsonObj.getString("contact_groups");
hostObj.check_period = innerJsonObj.getString("check_period");
String filename = hostObj.ipaddress.replace(".", "");
Properties propFile = LoadProp.getProperties();
BufferedWriter writer = Files.newBufferedWriter(Paths.get(propFile.getProperty(Constants.filepath) + filename + ".cfg"));
writer.write("define host {\n");
writer.write("\thost_name\t" + hostObj.hostname + "\n");
writer.write("\talias\t" + hostObj.alias + "\n");
writer.write("\taddress\t" + hostObj.ipaddress + "\n");
writer.write("\tcheck_command\t" + hostObj.check_command + "\n");
writer.write("\tmax_check_attempts\t" + hostObj.max_check_attempts + "\n");
writer.write("\tcheck_interval\t" + hostObj.chIntervalInMinutes + "\n");
writer.write("\tretry_interval\t" + hostObj.retryIntervalInMinutes + "\n");
writer.write("\tactive_checks_enabled\t" + hostObj.active_checks_enabled + "\n");
writer.write("\tpassive_checks_enabled\t" + hostObj.passive_checks_enabled + "\n");
writer.write("\tcheck_period\t" + hostObj.check_period + "\n");
writer.write("\tregister\t" + hostObj.register + "\n}");
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
errorJson.put("error", errorMsg);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But problem is that when I run this, my file is created with empty data.
So please help me to fix this issue.
I am using Java with Eclipse Mars 1.
You need to flush and close the writer by
writer.flush();
writer.close();

URLConnection doesn't work with public FTP servers in Android

My issue: my android device is unable to connect to a public FTP server using URLConnection. However, when the device tried to connect to a public FTP server (anonymous for username and no password), it cannot retrieve the InputStream from urlConnection.getInputStream();.
I do not use FTPClient from Apache Commons library because the speed is quite limited... A related question regarding that limited speed with FTPClient is here
FTPClient's download is slower than URLConnection's download.
Whatever I tried with the urlString:
urlString = protocol+"://" + username+"#" +address+":"+port + filepath + file;
// ftp://anonymous#speedtest.tele2.net:21/100GB.zip
urlString = protocol+"://" + username+":" + password + "#" +address+":"+port + filepath + file;
// ftp://anonymous:#speedtest.tele2.net:21/100GB.zip
urlString = protocol+"://" + username+":" + "password" + "#" +address+":"+port + filepath + file;
// ftp://anonymous:password#speedtest.tele2.net:21/100GB.zip
urlString = protocol+"://" + address+":"+port + filepath + file;
// ftp://speedtest.tele2.net:21/100GB.zip
downloadAndBroadcastURL:after getinputStream is never got logged with open FTP servers. I also tried with these two public FTP servers:
ftp://speedtest.tele2.net/100GB.zip
ftp://ftp.funet.fi/dev/1GBnull
But it doesn't connect as well.
My code:
private void downloadAndBroadcastURL() {
beginTime = System.currentTimeMillis();
try {
String urlString;
if (username.equals("anonymous")){
urlString = protocol+"://" + username+"#" +address+":"+port + filepath + file;
} else {
urlString = protocol+"://" + username+":" + password + "#" +address+":"+port + filepath + file;
}
Log.d(TAG, "downloadAndBroadcastURL: "+ urlString);
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
Log.d(TAG, "downloadAndBroadcastURL:after connect ");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.d(TAG, "downloadAndBroadcastURL:after getinputStream");
/*******************************
The rest is about handling the input stream, the download...
*****************************/
long difference;
byte data[] = new byte[4094];
int count;
while ((count = inputStream.read(data)) != -1 && download) {
downloadCount += count;
long stopTime = System.currentTimeMillis();
difference = stopTime - beginTime;
if (difference > 1000 && download) {
currentSpeed = downloadCount / (difference / 1000L); //for precision, because difference can be more than 1000 sometimes
averageSpeed = (averageSpeed + currentSpeed) / 2;
Log.d(TAG, "Speed: " + downloadCount + " bytes/s. " + (downloadCount / 1024) + "kB/s " + (downloadCount / 128) + "kbit/s " + (downloadCount / 1048576) + "Mb/s " + ((downloadCount) / (1024 * 128)) + "Mpbs" + (downloadCount / 131072) + "Mbit/s difference:" + difference + "ms");
if (download) {
broadcastSpeed();
}
downloadCount = 0; //Resetoidaan määrä
beginTime = stopTime;
}
if (!download) {
Log.d(TAG, "downloadAndBroadcast: download stops");
clearInputStream();
}
}
clearInputStream();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "FAIL " + e.toString());
} finally {
Log.d(TAG, "downloadAndBroadcastURL: ");
clearInputStream();
Log.d(TAG, "downloadAndBroadcast: finally");
}
}
Does anyone have any idea? Thanks in advance!

Categories

Resources