Updating Tomcat WAR file on Windows - windows

I have inherited a Maven/Tomcat(8.5) web application that is locally hosted on different machines. I am trying to get the application to update from a war file that is either stored locally (on a USB drive) or downloaded from AWS on Windows more reliably. On the Linux version, the software is able to upload the new war file via curl using the manager-script by doing the following:
String url = "http://admin:secret#localhost:8080/manager/text/deploy?path=/foo&update=true";
CommandRunner.executeCommand(new String[] { "curl", "--upload-file", war, url });
For Windows, the current current method tries to copy over the war file in the /webapps directory and has tomcat auto deploy the new war file after restarting either tomcat or the host machine. The problem is that the copied war file ends up being 0kb and there is nothing to deploy. This appears to happen outside of my install function because the file size after FileUtils.copyFile() for the /webapps/foo.war is the correct size.
I have tried to implement a PUT request for the manager-script roll from reading the Tomcat manager docs and another post:
File warfile = new File(request.getWar());
String warpath = warfile.getAbsolutePath().replace("\\", "/");
//closes other threads
App.terminate();
String url = "http://admin:secret#localhost:8080/manager/text/deploy?path=/foo&war=file:" + warpath + "&update=true";
HttpClient client = HttpClientBuilder.create().build();
HttpPut request;
try {
request = new HttpPut(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.err.println(result.toString());
} catch (Exception e){
LOGGER.info("war install failed");
throw new ServiceException("Unable to upload war file.", e);
}
However, the process still ends up with a 0kb war file to /webapps. The only error in my log is when tomcat tries to deploy the empty war. I have tried relaxing file read/write permissions in my tomcat installation and it doesn't seem to help. I also don't know if I can guarantee that all Windows installations will have access to curl if I try that implementation. Has anyone ran into similar issues?Thank you for the help!

Will, you are openning the file for sure but you are not writing anything to it, the result string is wrote to the stdout, so you got to replace System.err.println(result.toString()); with fr = new FileWriter(file); br = new BufferedWriter(fr); br.write(result);
and don't forget to close your resources at the end (br.close(); fr.close(); ) :)
PS: check if there are some informations to be filtered (headers or staff like that)

Related

How to Read File from PersistentVolumeClaims in SpringBoot

I have "file.txt" in my OpenShift PersistentVolumeClaims.
My StorageClasses is NFS.
Is it possible to access and read "file.txt" from my spring-boot code?
(This spring-boot code will be deployed on OpenShift and I'll mount the PVC to the DeploymentConfigs)
If yes, how can I do that? (I'm confused in how to retrieve the file from persistent volume from inside the code)
Any help will be appreciated. Thanks.
What #larsks said in the comment is correct:
your application doesn't know or care about the fact that you're using
a persistent volume
However, I used:
Resource resource = new ClassPathResource("/pvc/mount/path/file.txt");
InputStream inputStream = resource.getInputStream();
and:
Resource resource = resourceLoader.getResource("/pvc/mount/path/file.txt");
InputStream inputStream = resource.getInputStream();
Both doesn't work.
Below is what I use in the end:
Path file = Paths.get("/pvc/mount/path/file.txt");
InputStream stream = Files.newInputStream(file);

Files not found in JAR FIle

I am trying to find a folder containning PDF's . Everything works when the backend and frontent is not a Jar file.
My question is how do you locate files ,if it is in a JAR, all I am recieving is a file not found exception
Tried adding the file to my resources folder but still nothing.
What am I missing?
This can be accomplished in a number of ways, here are a couple:
// get the resources as a URL
URL resource = getClass().getClassLoader().getResource(
"static/test/TrainingDocuments/SuperUser/2/PartnerInformation/PartnerInformation.pdf");
// get the resource as a classPathResource
ClassPathResource classPathResource = new ClassPathResource(
"static/test/TrainingDocuments/SuperUser/2/PartnerInformation/PartnerInformation.pdf");
// get the resource directly as a stream
InputStream resourceAsStream = getClass().getClassLoader()
.getResourceAsStream("static/test/TrainingDocuments/SuperUser/2/PartnerInformation/PartnerInformation.pdf");

How do I rename file in Heroku running on Spring batch?

I have a Java codebase which is being executed on a heroku dyno. The command has executed and the log after that confirms the file is changed but actually it doesn't seem to work.
Here is my code:
File file =null;
String fileName = System.getProperty("user.dir") + env.getProperty("filePath");
try
{
if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
//Get the file and rename the same.
file = new File(fileName);
if (file!=null && file.exists())
{
String renameFile = System.getProperty("user.dir") + "/wardIssue_"+ new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(new Date().getTime()).toString() +"_completed";
logger.info("File being renamed to {}", renameFile);
file.renameTo(new File(renameFile));
}
logger.info("Batch job completed successfully");;
}
}
If you see the logger.info section actually prints the renamed file but in the server the file name is not changed.
The same code in my local is working fine i.e. file name is changed.
Should I be running the Java command for this spring batch with sudo? Are there any other things that might cause this problem?
I am using a Procfile with following command:
worker: java -Dserver.port=9002 $JAVA_OPTS -jar target/com.cognitive.bbmp.anukula.batch-0.0.1-SNAPSHOT.jar
Heroku's filesystem is ephemeral. Any changes you make to it will be lost the next time your dyno restarts, which happens frequently (at least once per day).
Furthermore, each dyno has its own ephemeral filesytem. Operations you perform on one dyno have no effect on other dynos, so you can't even make temporary filesystem changes with a worker and expect it to affect web (or any other) dynos.
You'll have to approach your problem in a way that doesn't require files to be renamed if you want to run your code on Heroku.

SFTP upload file Permission denied

I'm trying to upload excel file using SFTP to linux machine from my local windows PC.
Here is my code:
private void uploadToSftp() {
try
{
ChannelSftp sftpClient = null;
Channel channel = null;
JSch jsch = new JSch();
Session session = jsch.getSession("username", "host", 22);
session.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpClient = (ChannelSftp) channel;
sftpClient.cd("/var/www/folder");
File localFile = new File("C:\\Workspace\\upload-file\\test.xlsx");
sftpClient.put(localFile.getAbsolutePath(),localFile.getName());
sftpClient.disconnect();
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
but every time i run this application i get error:
3: Permission denied
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2873)
at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:594)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:475)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:365)
Doesn anyone know what could be problem and how can i solve this?
You seemed to upload your local file "C:\Workspace\upload-file\test.xlsx" to remote directory, "/var/www/folder" on SFTP.
I guess you have all permissions for reading,writing,executing etc on your local file("C:\Workspace\upload-file\test.xlsx"), but your remote folder, "/var/www/folder", might not accept your application's access including "upload" action.
SOLUTION:
The most simplest way to solve this issue is just granting all permission for all users to do anything in your upload target directory("/var/www/folder"). Please try this linux commands for checking permission on your upload folder.
ls -ld /var/www/folder
If you see your /var/www/folder/ directory is not allowed writing or reading(ex:drwxr-xr-x) for normal users, please grant permissions for this folder with the follwing command.
chmod 777 /var/www/folder
//check permission again.
ls -ld /var/www/folder
If you can check the target folder's permission is enough(drwxrwxrwx), please run your application again.
NOTE:
Giving all permissions for other users is not considered a good practice.
Please just do this solution for test, and change the permission setting fit to your specification later. For more detail, Please check this link(Click).

Create a folder via IBM sbt and share it to specific user: what is the correct Userid format?

I'm trying to create a folder and share it to a specific user, using SBT in a standalone Java console application (JDK 7).
I started with FileServiceApp sample in sbt/samples, and modified it with the following code:
...
fsa = new FileServiceApp(url, user, password);
FileService fileService = fsa.getFileService();
File newFolder = fileService.createFolder(newFolderName, "description", shareWith);
shareWith is a String that must contain 3 comma separated values: id,(person/community/group),(reader/Contributor/owner) as described in:
http://infolib.lotus.com/resources/social_business_toolkit/javadoc/com/ibm/sbt/services/client/connections/files/FileService.html#createFolder%28java.lang.String,%20java.lang.String,%20java.lang.String%29
update: I just downloaded SBT 1.1.0 and createFolder no longer accepts the shareWith parameter.
But I keep getting a "Not found" error (if shareWith does not contains those 3 elements the error turns to "Bad request").
edited: Calling createFolder without the third parameter just works, but the folder is not shared of course.
I get the same behaviour if I try with the following (with sbt 1.1.0 too):
File newFolder = fileService.createFolder(newFolderName, "description");
Map<String, String> folderParameters = new HashMap<String, String>();
folderParameters.put("shareWith", userID);
folderParameters.put("sharePermission", "View");
fileService.updateFileMetadata(newFolder, folderParameters);
Userid should be correct at least for Smartcloud (the format is: 1f......-b...-4...-b...-f............2 for Greenhouse, 2......1 for Smartcloud). I verified it using ProfileService.getProfile(id), for Smartcloud.
Code has been executed over a greenhouse account, and a collabserv account, using BasicEndpoint in both cases (SmartCloudEndpoint for Smartcloud).
My questions are:
is "share folder" not available in SmartCloud / Greenhouse, and in that case, is it available for a standalone Connections instance?
am I missing anything? (I only put the jars in lib/ext)
Found that the correct format for FileService.createFolder third parameter was
GUID + ",user,reader"
and not GUID,person,reader. Where GUID is the user GUID as suggested by Paul (not tried with user email yet).

Resources