I want to try an FTP upload from Jenkins to my FTP server with a groovy script.
After the upload, the archive file is corrupt and can not be opened.
I downloaded my archive from the workspace of Jenkins. There is all correct.
import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPF
import java.io.InputStream
#Grab(group='commons-net', module='commons-net', version='3.6')
def upload(){
String ftpServer = "ftp.my-domain.com";
String folder = "/";
def ftpClient = new FTPClient()
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
InputStream is = classLoader.getResourceAsStream("deployment.tar.gz")
ftpClient.connect(ftpServer)
ftpClient.enterLocalPassiveMode()
ftpClient.login("jenkins#my-domain.com","JenkisPassword")
ftpClient.setFileType(FTP.BINARY_FILE_TYPE)
// Store file to server
ftpClient.storeFile("deployment.tar.gz", is);
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
upload();
Is there any solution for groovy ? or is it a bad way ?
You probably need to call setFileType(FTP.BINARY_FILE_TYPE) before sending the file
Related
I have been trying to implement an application to determine content type of any file. I use Apache Tika for determination.
Here is a basic code implementation for that:
InputStream fileStream = ContentTypeController.class.getClassLoader().getResourceAsStream(fileName);
Tika tika = new Tika();
String contentType = null;
try {
contentType = tika.detect(fileStream);
} catch (IOException e) {
e.printStackTrace();
}
Instead of code above I have to download files from Openstack to determine file content type. Some files are more than 100GB and downloading all file is heavy.
I can not figure out how to overcome this necessity of downloading all file, I hope you have any idea/solution without downloading all file
Tika has ability to determine content type of file without downloading all if you pass a URL parameter to detect() function.
Tika tika = new Tika();
String contentType = null;
try {
contentType = tika.detect(new URL("a url"));
} catch (IOException e) {
e.printStackTrace();
}
I am targeting Android API 30. My app was storing log file and taking database backup in location "/storage/emulated/0/SpecialDir/". Now I am facing access denied issue while my app was workinng fine previously.
I got an overview about scoped storage and came to know that we have some managed locaitons where we can store our data accordingly. i.e Audio, Video, Images, and Download
My question is What is the solution for existing apps that was previously saving files on "/storage/emulated/0/SpecialDir/".
Can anyone please guide me what should i do.
string dir = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "LogFolder");
if (Directory.Exists(dir))
{
return Path.Combine(dir, "MyLogFile.txt");
}
try
{
string newDirectory = Directory.CreateDirectory(dir).FullName;
path = Path.Combine(newDirectory, "MyLogFile.txt");
System.IO.File.WriteAllText(path, "This is some testing log.");
}
catch (Exception ex)
{
string msg = ex.Message;
}
The above code is used to make 'LogFolder' if not exist and 'MyLogFile' as well. What changes do i needed to make it compatiable to Android 10. Thankyou
In Android 10, Google has introduced a new feature for external Storage. Its name is Scoped Storage. Google officially translates it as partitioned Storage, or Scoped Storage.The intent is to limit what programs can do with public directories in external storage. Partitioned storage has no effect on either the internal storage private directory or the external storage private directory.In short, in Android 10, there is no change to private directory reads and writes, and you can still use the File set without any permissions. For reading and writing to public directories, you must use the API provided by MediaStore or the SAF (storage access framework), which means you can no longer use the File set to manipulate public directories at will.
If you set targetSdkVersion above 29,you could try to add below codes into your AndroidManifest.Then you could access the File as before.
<manifest ... >
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
Update (you could try this for public external storage ):
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("LogFolder").AbsolutePath;
Java.IO.File file = new Java.IO.File(path);
if (!file.Exists())
{
file.Mkdirs();
}
try
{
FileWriter fw = new FileWriter(path + Java.IO.File.Separator + "MyLogFile.txt");
fw.Write("This is some testing log.");
fw.Close();
}
catch (Exception ex)
{
string msg = ex.Message;
}
Update for Android 11:
add MANAGE_EXTERNAL_STORAGE permission in your AndroidManifest.
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
in your activity:
if (Environment.IsExternalStorageManager)
{
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("LogFolder").AbsolutePath;
Java.IO.File file = new Java.IO.File(path);
if (!file.Exists())
{
file.Mkdirs();
}
try
{
FileWriter fw = new FileWriter(path + Java.IO.File.Separator + "MyLogFile.txt");
fw.Write("This is some testing log.");
fw.Close();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
else
{
StartActivityForResult(new Intent(Settings.ActionManageAllFilesAccessPermission), 0);
}
I'm using Docker for a Spring Boot application and so far everything is working.
I have a resource file in src/main/resources/db/data/dummydata.csv
In a bootstrap class this file is used to import the dummy data into the database.
private fun getDummyData(): List {
var fileReader: BufferedReader? = null
val dummyData = ArrayList<DummyDataEntity>()
try {
var line: String?
val res = ResourceUtils.getFile("classpath:db/data/dummydata.csv")
fileReader = BufferedReader(FileReader(res.path))
// Read CSV header
fileReader.readLine()
... Processing the data ...
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
fileReader!!.close()
} catch (e: Exception) {
e.printStackTrace()
}
return dummyData
}
}
When I run the application in IntelliJ, everything works just fine, but when I'm running it in Docker it cannot be found.
The Jar and the Docker image are created using Kotlin DSL Gradle.
import com.palantir.gradle.docker.DockerExtension
import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension
import org.gradle.tooling.model.GradleTask
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.springframework.boot.gradle.tasks.bundling.BootJar
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath(Libs.springBootGradlePlugin)
classpath(Libs.kotlinGradlePlugin)
classpath(Libs.kotlinAllOpen)
classpath(Libs.gradleDocker)
}
}
plugins {
// Apply the java-library plugin to add support for Java Library
`java-library`
}
apply {
plugin("kotlin")
plugin("kotlin-spring")
plugin("org.springframework.boot")
plugin("io.spring.dependency-management")
plugin("com.palantir.docker")
}
repositories {
mavenCentral()
}
dependencies {
compile(Libs.kotlinReflect)
// Spring Boot
compile(Libs.springBootStarterDataJpa)
}
configure<DependencyManagementExtension> {
imports {
mavenBom(Libs.vaadinBom)
}
}
val bootJar: BootJar by tasks
bootJar.baseName = "reporting-app-site"
bootJar.version = "0.0.1"
configure<DockerExtension> {
name = "brabantia/${bootJar.baseName}"
files(bootJar.archivePath)
buildArgs(mapOf("JAR_FILE" to bootJar.archiveName))
dependsOn(tasks["build"])
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions.jvmTarget = "1.8"
The Jar does contain BOOT-INF/classes/db/data/dummyData.csv but when the application is run the error that is thrown is
java.io.FileNotFoundException: class path resource [db/data/dummydata.csv] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app.jar!/BOOT-INF/classes!/db/data/dummydata.csv
What am I missing here?
The below worked for me.., you need to use an InputStream and not a File.
...
#Autowired
private ResourceLoader resourceLoader;
...
Resource resource= resourceLoader.getResource("classpath:/account_info.html");
InputStream inputStream= resource.getInputStream();
Assert.notNull(inputStream,"Could not load template resource!");
String email = null;
try {
byte[] bdata = FileCopyUtils.copyToByteArray(inputStream);
email = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.warn("IOException", e);
}finally {
if ( inputStream != null) {
IOUtils.closeQuietly(inputStream);
}
}
Store store = Session.getDefaultInstance().getStore();
Folder[] folders = store.list(Folder.SENT);
Folder sentfolder = folders[0];
// Create message.
Message msg = new Message(sentfolder);
// Add TO Recipients.
Address toList[] = new Address[1];
try {
toList[0]= new Address("someemail#email.com", "Some Email");
} catch(AddressException e) {
System.out.println(e.toString());
}
try {
msg.addRecipients(Message.RecipientType.TO, toList);
} catch (MessagingException e) {
System.out.println(e.toString());
}
// Add CC Recipients.
Address ccList[] = new Address[1];
try {
ccList[0]= new Address("someemail#gmail.com", "some address");
} catch(AddressException e) {
System.out.println(e.toString());
}
try {
msg.addRecipients(Message.RecipientType.CC, ccList);
} catch (MessagingException e) {
System.out.println(e.toString());
}
// Add the subject.
msg.setSubject("A Test Email");
// Add the message body.
try {
msg.setContent("This is a test message.");
} catch(MessagingException e) {
// Handle messaging exceptions.
}
// Send the message.
try {
Transport.send(msg);
} catch(MessagingException e) {
System.out.println(e.getMessage());
}
System.out.println("Email sent successfully.");
Are you running this on a simulator? If so, which development environment (eclipse or JDE)? Have you started the MDS or are you using ESS? (With MDS 4, you don't need ESS.)
Personally, I use eclipse with the plug-in, then set the run-time configuration to launch MDS.
However, before doing that, you need to edit the rimpublic.property file to configure it to connect to your e-mail server (if you are using a remote e-mail server). If you are going to use a local mail client, configure MDS to use that as a pass-through.
Let me know what your setup / configuration is and I'll try to help more.
I have the included grails script that I found in some random place on the internet and it works pretty well for firing up scripts in a bootstrapped grails env. The only thing it doesn't seem to do is kick off my conf/*Bootstrap.groovy scripts like when I do run-app.
Is there another function like loadApp() and configureApp() that will do that for me?
import org.codehaus.groovy.grails.support.PersistenceContextInterceptor
Ant.property(environment: "env")
grailsHome = Ant.antProject.properties."env.GRAILS_HOME"
includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")
target('default': "Runs scripts in the test/local directory") {
if (!args) { throw new RuntimeException("[fail] This script requires an argument - the script to run.") }
depends(configureProxy, packageApp, classpath)
classLoader = new URLClassLoader([classesDir.toURI().toURL()] as URL[], rootLoader)
Thread.currentThread().setContextClassLoader(classLoader)
loadApp()
configureApp()
def interceptor = null
def beanNames = appCtx.getBeanNamesForType(PersistenceContextInterceptor)
if (beanNames && beanNames.size() == 1) {
interceptor = appCtx.getBean(beanNames[0])
}
try {
interceptor?.init()
new GroovyScriptEngine(Ant.antProject.properties."base.dir", classLoader).run("scripts/${args}.groovy", new Binding(['appCtx':appCtx]))
interceptor?.flush()
} catch (Exception e) {
e.printStackTrace()
interceptor?.clear()
} finally {
interceptor?.destroy()
}
}
Yes, try
new BootStrap().init()