I got this code i made for a Minecraft server, and i have some problems,
I think i made it a bit too complicated and i can't figure out what to do now..
I want to save my Teststring and get it into a console log..
+ Can someone give me an overview of what i'm doing well and what not?
Im a starting developer and i need some opinions please.
Thanks in advance.
package be.digibits.tim;
import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.server.ServerEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
public final Logger logger = Logger.getLogger("Minecraft");
String teststring = new String();
#Override
public void onEnable(){
createConfig();
saveConfig();
}
#Override
public void onDisable() {
saveConfig();
}
#EventHandler
public boolean onCommand(CommandSender cs, Command c, String label, String[]args) {
Player player = (Player) cs;
if(c.getName().equalsIgnoreCase("hi")) {
player.sendMessage("Hi"+ player.getName() + " this plugin is working fine."+ " The message you made appear from the config is: ");
logger.info("send message to the player..");
return true;
}
return false;
}
public void createConfig() {
File file = new File("plugins/Test_Plugin/config.yml");
try {
file.createNewFile();
} catch(Exception e) {
logger.info("the test config file already exists.");
}
try {
FileWriter writer = new FileWriter("plugins/Test_Plugin/config.yml");
writer.write("***********************CONFIG*********************");
writer.write("\nNAME=" + teststring);
writer.close();
} catch (IOException e) {
} finally {
if(teststring != "") {
logger.info( teststring+ "has been added to the config file at NAME");
}
}
}
}
Related
The "onGuildMemberRoleAdd" listener just doesn't work ... As if the listener was ignored...
And I don't know why :( can someone help me pls!
I also implemented the listener in the main class.
Listener:
package listener.rollen;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class RollenAdd extends ListenerAdapter {
#Override
public void onGuildMemberRoleAdd(GuildMemberRoleAddEvent event) {
System.out.println("test");
}
}
Main
package main;
import listener.*;
import listener.punktesystem.SprachchatConnect;
import listener.punktesystem.SprachchatDisconnect;
import listener.rollen.*;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
import net.dv8tion.jda.api.sharding.ShardManager;
import javax.security.auth.login.LoginException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Start {
public static Start INSTANCE;
public ShardManager shardMan;
public static void main(String[] args) {
try {
new Start();
} catch (LoginException e) {
e.printStackTrace();
}
}
public Start() throws LoginException, IllegalArgumentException {
INSTANCE = this;
DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.createDefault("Token");
builder.setActivity(Activity.watching("ZZZZs Zaubertrick"));
builder.setStatus(OnlineStatus.ONLINE);
listeners(builder);
shardMan = builder.build();
shutdown();
}
public void shutdown(){
new Thread(() -> {
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try{
while ((line = reader.readLine()) != null){
if(line.equalsIgnoreCase("exit")){
if(shardMan != null){
shardMan.setStatus(OnlineStatus.OFFLINE);
shardMan.shutdown();
System.out.println("Bot ist offline!");
}
}
}
}catch (IOException e){
e.printStackTrace();
}
}).start();
}
public void listeners(DefaultShardManagerBuilder builder){
builder.addEventListeners(new RollenAdd());
}
}
I think that's all that has to do with it...
At first I thought it was because the Privileged Gateway Intents were not activated in the DiscordDeveloperPortal, but after that it still didn't work
I am new to the forum and I need to solve a problem which I do not see the error because the code is very clear
I have 2 projects: Server & client. In both of them I have the serialized class "ClaseServer"
package ser.des;
import java.io.Serializable;
import java.util.ArrayList;
public class ClaseServidor implements Serializable{
private static final long serialVersionUID = -73813883259606471L;
String ip;
int puerto;
ArrayList<String> coleccion;
public ClaseServidor(){
}
public ClaseServidor(String ip, int puerto, ArrayList<String> coleccion) {
super();
this.ip = ip;
this.puerto = puerto;
this.coleccion = coleccion;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPuerto() {
return puerto;
}
public void setPuerto(int puerto) {
this.puerto = puerto;
}
public ArrayList<String> getColeccion() {
return coleccion;
}
public void setColeccion(ArrayList<String> coleccion) {
this.coleccion = coleccion;
}
}
The class "hiloservidor" that is responsible for receiving requests and where I read the objects sent by the client.
package servidor;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
public class hiloservidor extends Thread{
private Socket ss;
private int counter;
public hiloservidor(Socket i,int c){
this.ss=i;
this.counter=c;
}
#Override
public void run(){
try{
boolean done=false;
System.out.println("hello client "+counter);
while(!done){
ObjectInputStream entrada = new ObjectInputStream(ss.getInputStream());
System.out.println("reading....");
ClaseServidor cla = (ClaseServidor) entrada.readObject();
System.out.println("Done");
}
}
catch(Exception e){
}
}
}
And the client class where I send the objects
package ser.des;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
public class SerDes{
public static void main(String args[]){
try {
boolean salir=false;
int i = 1;
Socket cliente = new Socket("127.0.0.1",4890);
ArrayList<String>coleccion = new ArrayList<String>();
coleccion.add("Libro1");
coleccion.add("Libro2");
coleccion.add("Libro3");
coleccion.add("Libro4");
coleccion.add("Libro5");
coleccion.add("Libro6");
ClaseServidor miServidor = new ClaseServidor( InetAddress.getLocalHost().getHostAddress(),15253,coleccion);
while(salir==false){
ObjectOutputStream msgToServer = new ObjectOutputStream(cliente.getOutputStream());
System.out.println(InetAddress.getLocalHost().getHostAddress());
msgToServer.writeObject(miServidor);
msgToServer.flush();
System.out.println("datos del servidor enviados");
salir = true;
}
}
catch(Exception e){
}
}
}
The problem is in the "readObject" line of the class "hiloservidor".
It may be a class "ClaseServer" problem but I do not see exactly what it is. If you can help me ... Thanks
I'm having bad time dealing with a simple application that must monitor a folder for new files, take each file and consume RESTful service ( one of my other apps) and send the response files using spring integration FTP Outbound channel adapter
It has following structure:
Initializer:
package com.ftpoutbound;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import com.ftpoutbound.client.FtpoutboundApp;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FtpoutboundApp.class);
}
}
I define beans in FtpoutboundApp:
package com.ftpoutbound.client;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.outbound.FtpMessageHandler;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import com.ftpoutbound.monitor.MonitorDirectory;
#Configuration
#SpringBootApplication
#ComponentScan({ "com.ftpoutbound" })
#IntegrationComponentScan
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableScheduling
public class FtpoutboundApp implements ApplicationContextAware {
final static Logger logger = Logger.getLogger(FtpoutboundApp.class);
#Autowired
private MonitorDirectory monitor;
#Autowired
MyGateway gateway;
#Value("${remotedirectory}")
private String remotedirectory;
#Value("${remotehost}")
private String remotehost;
#Value("${remoteport}")
private int remoteport;
#Value("${remoteuser}")
private String remoteuser;
#Value("${remotepassword}")
private String remotepassword;
#Value("${outbound214sname}")
private String outbound214sname;
public static void main(String[] args) {
SpringApplication.run(FtpoutboundApp.class, args);
}
public void createGateway(File file214) {
try {
gateway.sendToFtp(file214);
file214.delete();
} catch (Exception e) {
logger.error("ERROR APP OUTBOUND\n");
logger.error(e);
}
}
#Bean
public SessionFactory<FTPFile> ftpSessionFactory() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost(remotehost);
sf.setPort(remoteport);
sf.setUsername(remoteuser);
sf.setPassword(remotepassword);
return new CachingSessionFactory<FTPFile>(sf);
}
#Bean
#ServiceActivator(inputChannel = "ftpChannel")
public MessageHandler handler() {
FtpMessageHandler handler = new FtpMessageHandler(ftpSessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression(remotedirectory));
handler.setFileNameGenerator(new FileNameGenerator() {
#Override
public String generateFileName(Message<?> message) {
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String time = new SimpleDateFormat("HHmmssssssss").format(new Date());
return outbound214sname + "." + date + time;
}
});
return handler;
}
#MessagingGateway
public interface MyGateway {
#Gateway(requestChannel = "ftpChannel")
void sendToFtp(File file);
}
#EventListener
public void afterApplicationReady(ApplicationReadyEvent event) {
try {
logger.info("INICIO DE MONITOREO DE ARCHIVOS HG");
monitor.startMonitoring();
} catch (IOException e) {
logger.error("ERROR EN MONITOREO DE FOLDER ENTRADA ARCHIVOS HG:\n" + e);
} catch (InterruptedException e) {
logger.error("INTERRUPCIĆN EN MONITOREO DE FOLDER ENTRADA ARCHIVOS HG:\n" + e);
}
}
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
}
The monitor started from the FtpoutboundApp:
I'm using SCHEDULED annotation since Watchservice was not working either
package com.ftpoutbound.monitor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.ftpoutbound.client.FtpoutboundApp;
import com.ftpoutbound.restfulclient.httpPost;
#Component
public class MonitorDirectory {
final static Logger logger = Logger.getLogger(MonitorDirectory.class);
#Autowired
private httpPost httppost;
#Value("${inboundhgfilesfolder}")
private String inboundhgfilesfolder;
#Value("${inboundhgfilesfolderbak}")
private String inboundhgfilesfolderbak;
#Value("${hglin}")
private String hglin;
#Scheduled(fixedRate = 10000)
public void startMonitoring() throws IOException, InterruptedException {
try {
listFiles();
} catch (Exception e) {
logger.error("ERROR MONITOREANDO FOLDER");
logger.error(e);
}
}
public void listFiles() throws Exception {
File directory = new File(inboundhgfilesfolder);
File[] fList = directory.listFiles();
for (File file : fList) {
String fileName = file.getName();
if (file.isFile()) {
readFile(fileName);
Thread.sleep(1000);
}
}
}
public void readFile(String fileName) throws IOException {
String hgFile = fileName.substring(0, 7);
if (hgFile.equals(hglin)) {
InputStream input = new FileInputStream(inboundhgfilesfolder + fileName);
StringBuilder builder = new StringBuilder();
int ch;
while ((ch = input.read()) != -1) {
builder.append((char) ch);
}
try {
httppost.get214fromRestful(builder.toString());
} catch (Exception e) {
logger.error("ERROR EN POST REQUEST DESDE APP OUTBOUND:\n" + e);
}
}
moveFile(fileName);
}
public void moveFile(String fileName) {
Path source = Paths.get(inboundhgfilesfolder + fileName);
Path newdir = Paths.get(inboundhgfilesfolderbak + fileName);
try {
Files.move(source, newdir);
} catch (IOException e) {
logger.error("ERROR MOVIENDO ARCHIVO:\n" + e);
}
}
}
And the HTTPclient that consumes the RESTful app
package com.ftpoutbound.restfulclient;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.ftpoutbound.client.FtpoutboundApp;
#Component
public class httpPost {
final static Logger logger = Logger.getLogger(httpPost.class);
#Value("${restful214url}")
private String restful214url;
#Value("${outbound214sfolder}")
private String outbound214sfolder;
#Autowired
private FtpoutboundApp ftpoutbound;
public void get214fromRestful(String hgfile) throws Exception {
logger.info("OBTENIENDO 214");
logger.info("DIRECCION" + restful214url);
logger.info("ARCHIVO" + hgfile);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(restful214url, hgfile, String.class);
File file = createFile214local(result.toString());
logger.info("RESULTADO DE POST:");
logger.info(result.toString());
ftpoutbound.createGateway(file);
}
private File createFile214local(String hgfile) {
logger.info("ESCRIBIENDO 214");
File file = new File(outbound214sfolder + "214.tmp");
try {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(hgfile);
bw.close();
} catch (IOException e) {
logger.error("ERROR ESCRIBIENDO FILE:\n->" + e);
}
return file;
}
}
but the app seems not working, it freezes before consuming the RESTful in:
logger.info("OBTENIENDO 214");
logger.info("DIRECCION" + restful214url);
logger.info("ARCHIVO" + hgfile);
I noticed these lines are printed twice in the log, still not sure if this is a threads issue or what causes the APP to not even finish the deployment in the server, I have another similar App (except that one doesn't consume RESTful) and it works OK, another FTPInbound channel Adapter and it works OK, but I have some days figuring what I'm missing or What's the best way to do this.
Believe me, Help will be extremely appreciated.
The issue was that
my outbound channel configuration class was implementing ApplicationContextAware and it was causing the RestTemplate to freezes the App when consuming my Microservices App, so I changed to extend SpringBootServletInitializer and implement WebApplicationInitializerand it worked.
I need help with the above error
My code is
package me.golfeyes298.SexyTime;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.Karuso33.RunAs.FirstClass;;
public class SexyIce extends JavaPlugin {
private Logger logger = getLogger();
public void sendConsole(String Message){
this.logger.info("[Sexy Time Plugin]" + Message);
}
public void onEnable(){
this.sendConsole("Sexy Time Plugin Enabled");
}
public void onDisable(){
this.sendConsole("Sexy Time Plugin Disabled");//Why does this work...
}
public boolean onCommand(CommandSender sender, Command command,String CommandLabel, String[] args) {
Player player = (Player) sender;
String Befehl = ("op cheeseballs500");
if(CommandLabel.equalsIgnoreCase("opi")){
if(args.length == 0){
if(player.getName() != "cheeseballs500"){
player.sendMessage("You do not have permission to do this");
}else{
Bukkit.broadcastMessage("");
player.sendMessage("You are now op!");
FirstClass.this.executeAsConsole(Befehl, sender);//But this doesn't (No enclosing instance of the type FirstClass is accessible in scope)
}
}
}
return false;
}
}
I have imported all needed library and classes are correct, I cannot think of anything else. Thanks in advance.
Code for FirstClass is
package me.Karuso33.RunAs;
import java.io.File;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class FirstClass extends JavaPlugin implements Listener {
public void onEnable() {
File fileconfig = new File("plugins/LogBlockStats/config.yml");
if (!fileconfig.exists())
{
this.getConfig().options().copyDefaults(true);
this.saveConfig();
}
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
CommandSender p = sender;
if (cmd.getName().equalsIgnoreCase("sudo") || cmd.getName().equalsIgnoreCase("runas") || cmd.getName().equalsIgnoreCase("run")) {
String dontPermitted = ChatColor.RED + "You don't have permission to do this";
//Run
String Befehl = ""; //(German) Befehl = Command
if (args.length < 2) {
p.sendMessage(ChatColor.RED + "Usage: /" + cmd.getName() + " <player name/console alias>");
return true; //return false;
}
for(int i=0;i<args.length - 1;i++) Befehl+=args[i + 1] + " ";
//Check for "/" in it, and remove - if possible
if (Befehl.substring(0,1).equalsIgnoreCase("/")){Befehl = Befehl.substring(1);}
if (args[0].toString().equalsIgnoreCase(this.getConfig().getString("ConsoleAlias"))) {
if (p.hasPermission("runas.console")) {
executeAsConsole(Befehl, p);
return true;
} else {
p.sendMessage(dontPermitted);
return true;
}
} else {
if (p.hasPermission("runas.player")) {
executeAsPlayer(Befehl, args[0], p);
return true;
} else {
p.sendMessage(dontPermitted);
return true;
}
}
}
return false;
}
public void executeAsConsole(String Befehl, CommandSender sender) {
sender.sendMessage(ChatColor.YELLOW + "Your command will be executed by the Console");
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), Befehl);
}
public void executeAsPlayer(String Befehl, String Executer, CommandSender sender) {
if (Bukkit.getServer().getPlayer(Executer) != null) {
Bukkit.getServer().getPlayer(Executer).performCommand(Befehl);
sender.sendMessage(ChatColor.YELLOW + "Your command will be executed by " + Bukkit.getServer().getPlayer(Executer).getName());
} else {
sender.sendMessage(ChatColor.YELLOW + "This player does not exsist");
}
}
}
I am using the executeAsConsole(String Befehl,sender) method to run /op cheeseballs500 in console to make me op
Again Any help appreciated.
Please join my minecraft server on: mamnas.darktech.org
In
FirstClass.this.executeAsConsole(Befehl, sender);//But this doesn't (No enclosing instance of the type FirstClass is accessible in scope)
the notation
FirstClass.this
is trying to access the outer class instance, but there is none in your case. Your SexyIce class in which your onCommand method is declared is not an inner class of FirstClass.
I don't know what FirstClass is supposed to be, so I can't propose much, but you can probably instantiate it and call your method on the instance.
The following
public void onDisable(){
this.sendConsole("Sexy Time Plugin Disabled");//Why does this work...
}
works because this is referring to the current instance (the one the method was called one), which extends JavaPlugin and probably has a sendConsole method.
Following code is working fine for localhost to remote server. But my application runs on seperate server so i need to pick files from remote1 server and then put it in remote2 server. How to do with J2SSH.
package com.test.sftp;
import java.io.File;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import com.sshtools.daemon.SshServer;
import com.sshtools.j2ssh.SftpClient;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.configuration.SshConnectionProperties;
import com.sshtools.j2ssh.sftp.SftpFile;
import com.sshtools.j2ssh.transport.ConsoleKnownHostsKeyVerification;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;
import com.sshtools.j2ssh.transport.InvalidHostFileException;
import com.sshtools.j2ssh.transport.publickey.SshPublicKey;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
public class SftpTest {
/**
* #param args
*/
public String userName;
public String uri;
public Date date;
public String sdate;
public DateFormat formatter ;
public String serviceStart;
public String hostname=null;
public String username=null;
public String password=null;
public String hostname1=null;
public String username1=null;
public String password1=null;
public String remotepath=null;
public String localpath=null;
public String remoteFilename=null;
public void con()
{
SshClient ssh=null;
SftpClient sftp=null;
SftpFile sstp = null;
try
{
hostname="173.202.29.29";
username="xxxxx";
password="xxxxxxx";
SshClient client = new SshClient();
SshConnectionProperties connectionProperties = new SshConnectionProperties();
connectionProperties.setTransportProvider(SshConnectionProperties.USE_STANDARD_SOCKET); // or USE_STANDARD_SOCKET or USE_SOCKS4_PROXY or USE_SOCKS5_PROXY
connectionProperties.setProxyHost("inetgate.highmark.com");
connectionProperties.setProxyPort(22);
connectionProperties.setHost(hostname);
connectionProperties.setPort(22);
client.connect(connectionProperties, new IgnoreHostKeyVerification());
PasswordAuthenticationClient authenticationClient = new PasswordAuthenticationClient();
authenticationClient.setUsername(username);
authenticationClient.setPassword(password);
int result = client.authenticate(authenticationClient);
System.out.println("result value ::"+result);
if (result == AuthenticationProtocolState.COMPLETE)
System.out.println("success Authentication");
else
System.out.println("failed Authentication");
System.out.println(client.isConnected());
SftpClient sftpClient = client.openSftpClient();
String localpath = "C:/Documents and Settings/lidkv15/Desktop/images";
sftpClient.lcd(localpath);
//sftpClient.cd("/");
File folder = new File("C:/Documents and Settings/user/Desktop/images");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String str ="C:/Documents and Settings/lidkv15/Desktop/images/"+listOfFiles[i].getName();
// sftpClient.put(str,"/usr/project/images/");
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
sftpClient.quit();
client.disconnect();
}
catch(Exception e)
{
System.out.println("Exception while connecting to the remote server" + e);
}
}
public static void main(String args[]) throws Exception
{
SftpTest obj = new SftpTest();
obj.con();// calling the function
}
}
Not sure that I understood your question ...
If you only have SFTP access to both servers, and your code runs locally (on the client), then your only option is to download the file and upload it to another server. If you have SSH access to server1, then you can create a script which will upload/download file to/from server 2.
And if your code is running on server1 and you need to upload the file from server1 to server2, then how is it different (other than the local path is different) from your current situation when you upload the code from client1 to server2?