How to connect with Azure cloud (blob storage) using dasein API - java

Can anyone help me with example or sample? I need to get & put files on the blob storage
I have managed to code following,
try {
CloudProvider provider = (CloudProvider) Class.forName("org.dasein.cloud.azure.Azure").newInstance();
ProviderContext providerContext = new ProviderContext("DEV","West US");
//providerContext.setStorage("");
providerContext.setStorageAccountNumber("mypackages");
providerContext.setStoragePublic("XXX".getBytes());
providerContext.setEndpoint("http://XXX.blob.core.windows.net/");
providerContext.setStorageX509Key("YYY".getBytes());
provider.connect(providerContext, provider);
System.out.println("here "+provider.testContext());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
On executing above code I am getting NPE as below
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more

This Works for me:
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;"
+ "AccountName=<Your accountname>;"
+ "AccountKey=<Your key>";
public static synchronized String upLoadSelected(String containername, String path, String directory, String pathPartRemover) {
List<File> filListe = new ArrayList<>();
if (storageConnectionString.isEmpty() != true) {
String respons = "";
try {
CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient serviceClient = account.createCloudBlobClient();
CloudBlobContainer container = null;
String source = "" + path;
container = serviceClient.getContainerReference("" + containername);
container.createIfNotExists();
String temp = "" + directory;
filListe = listf(source);
for (File file : filListe) {
if (file.isDirectory() == true && file.getParentFile().getName().equalsIgnoreCase(temp) != true) {
temp = (temp + "\\" + file.getName());
}
if (file.isDirectory() != true) {
CloudBlockBlob blob = container.getBlockBlobReference("" + file.getCanonicalPath().replace("" + pathPartRemover, ""));
File sourceFile = new File("" + file.getAbsolutePath());
blob.upload(new FileInputStream(sourceFile), sourceFile.length());
}
}
} catch (FileNotFoundException fileNotFoundException) {
respons = respons + "FileNotFoundException encountered: " + fileNotFoundException.getMessage();
} catch (StorageException storageException) {
respons = respons + "StorageException encountered: " + storageException.getMessage();
} catch (IOException e) {
respons = respons + "IOexception encountered: " + e.getMessage();
} catch (URISyntaxException e) {
respons = respons + "URIexception encountered: " + e.getMessage();
} catch (InvalidKeyException ex) {
respons = respons + "InvalidKeyException encountered: " + ex.getMessage();
}
return respons;
}
return "No connection";
}
public static synchronized List<File> listf(String directoryName) {
File directory = new File(directoryName);
List<File> resultList = new ArrayList<>();
File[] fList = directory.listFiles();
resultList.addAll(Arrays.asList(fList));
for (File file : fList) {
if (file.isFile()) {
} else if (file.isDirectory()) {
resultList.addAll(listf(file.getAbsolutePath()));
}
}
return resultList;
}

Related

IOException on move file (FileUtils.moveFile)

I'm getting an IOException that is caught while trying to move a file.
public static void moveFile() {
String filePath = "C:/Users/newuser/inbound";
String archiveFolder = filePath.replaceAll("inbound", "archive");
File critLocation = new File(archiveFolder.concat("/crit"));
File sourceFolder = new File(filePath);
File[] listOfFiles = sourceFolder.listFiles();
for (File file : listOfFiles) {
if (file.getName().contains("crit")){
System.out.println("Moving crit file... " + file.getName());
try {
FileUtils.moveFile(file, critLocation);
} catch (FileAlreadyExistsException e) {
System.out.println("File " + file.getName() + " already exists.");
file.delete();
} catch (IOException exception) {
System.out.println("AN IO EXCEPTION HAS OCCURED");
}
}
}
}
I just want to use a filePath to move some files around. I also tried
FileUtils.moveFileToDirectory(file, sitLocation, false);
but to no avail.

Renaming the original file name of a Multipart file

I have this code where I wanted to rename the before saving it to the file system. I tried other questions here in stack overflow but it doesn't apply for me. Hoping you could help me this is my code.
#PostMapping("/api/file/upload")
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
try {
fileStorage.store(file);
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
return "Error -> message = " + e.getMessage();
}
}
This is my store function:
#Override
public void store(MultipartFile file){
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
}
I tried renaming the original file but it doesn't work.
Hoping you could help me. Thank you so much!!!
Below is working snippet with little modification here and there :
#PostMapping(value = "/api/file/upload", headers = {"content-type=multipart/*"})
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
Path TO = Paths.get("/Users/myusername/Desktop/newfileName");
try {
try {
Files.copy(file.getInputStream(), TO);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
return "Error -> message = " + e.getMessage();
}
}
OutputScreen:

I am getting 500 as reply code when I try to delete a file from remote server using java FTPClient

When I try to delete a file using ftpclient I am getting reply code as 500. Can someone help me with the issue. As you can see in the commented section of the code I tried to move the file to other folder and I got the reply code as 500 as well.
public boolean sendFile(HttpResponse httpresponse, String accessionNumber)
throws Exception {
FTPClient ftpClient = null;
boolean fileUploadStatus = false;
InputStream inputStream = null;
try {
FTPSClient ftpClient = new FTPSClient(true);
String fileName = "SampletesterFileNine.pdf";
String remotePath = "/";
String tempFile = remotePath + fileName;
try {
ftpClient.connect(server, this.port);
} catch (Exception e) {
e.printstackTrace();
}
int reply = ftpClient.getReplyCode();
logger.info("Reply code connect :" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
boolean login = ftpClient.login(userName, password);
if (login) {
if (ftps) {
((FTPSClient) ftpClient).execPROT("P");
}
logger.info("Logged in to ftp server with host " + server);
} else {
logger.info("login failed");
}
} else {
logger.info("login failed with exception");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
logger.info("Checking whether file exists or not!!");
inputStream = ftpClient.retrieveFileStream(tempFile);
if(inputStream != null) {
logger.info("File already exists");
isFileExist = true;
String toPath = "/failed/SampletesterFileNine.pdf";
/*boolean renamed = ftpClient.rename(tempFile, toPath);
logger.info("replycode is : " + ftpClient.getReplyCode());
if(renamed) {
logger.info("file moved to failed folder successfully");
} else {
logger.info("failed while moving file to failed folder");
} */
boolean renamed = ftpClient.deleteFile(tempFile);
logger.info("replycode is : " + ftpClient.getReplyCode());
if(renamed) {
logger.info("file moved to failed folder successfully");
} else {
logger.info("failed while moving file to failed folder");
}
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
} catch(Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printstackTrace();
}
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
e.printstackTrace();
}
}
return fileUploadStatus;
}

How to expose soap webservices as REST API

I wrote the below code for making soap webservice call. How do I expose it as REST api? The below code makes a soap call and sends username and password as headers. The output will be from a webservice callled SR_spcWeb_spcServiceStub. Thanks in advance
SR_spcWeb_spcService srv;
try {
srv = new UNINServiceRequestWSLocator().getSR_spcWeb_spcService(new java.net.URL("http://crmuat.un.org//eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&WSSOAP=1"));
((SR_spcWeb_spcServiceStub)srv).setUsername("username");
((SR_spcWeb_spcServiceStub)srv).setPassword("password");
((SR_spcWeb_spcServiceStub)srv).setHeader("http://siebel.com/webservices", "UsernameToken","username");
((SR_spcWeb_spcServiceStub)srv).setHeader("http://siebel.com/webservices", "PasswordText","password");
((SR_spcWeb_spcServiceStub)srv).setHeader("http://siebel.com/webservices", "SessionType","Stateless");
String timeStamp = new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime());
String fullName = firstName+" "+lastName;
System.out.println(timeStamp);
if (filename == null)
{
uploadFileName = "";
extension = "";
encodedString = "";
}
FileAttachment[] fileattachments = { new FileAttachment( uploadFileName, extension, encodedString ) } ;
CreateSR_Input sr=new CreateSR_Input("3-Medium", "",emailAddr,"","Reported By","","","",fullName,"",indexNum, indexNum,
"CRM Tier 3 Support","Incident",emailAddr,"","","Medium","",help_area, timeStamp,"","","","Low", indexNum,
subarea, area,emailAddr,"","", fileattachments,indexNum,requesteditem, "","", "Web",subarea1,
emailAddr, justification,"", "", "3-Medium", location_name, "");
System.out.println("srgroupe + "+ srgroup);
System.out.println("subarea + "+ subarea);
System.out.println("area + "+ area);
System.out.println("requesteditem + "+ requesteditem);
System.out.println("subarea1 + "+ subarea1);
CreateSR_Output srvo;
try {
srvo = srv.createSR(sr);
System.out.println("Got from webservice + "+ srvo.getSRNum());
System.out.println("Got from webservice + "+ srvo.getStatusMsg());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

apache ftpclient retrievefile() downloading corrupted file

I am using org.apache.commons.net.ftp.FTPClient for downloading files from ftp server.
It downloads all the files from my ftp server except those files with names like test.xml test.txt west.xml etc., The files with these names are getting downloaded with no data inside the file. retrieveFile() method is returning boolean false for these files.
I tried to download the same file by renaming its name manually on ftp server. It worked well with other names.
Please let me know how to solve this problem.
EDIT- Adding sample code
public static boolean downloadFTPDir(String localDir, FTPClient ftpClient) {
OutputStream output = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
/*
* Use passive mode as default because most of us are behind
* firewalls these days.
*/
ftpClient.enterLocalPassiveMode();
FTPFile[] fileList = ftpClient.listFiles();
for (FTPFile ftpFile : fileList) {
if(ftpFile.isDirectory()){
String tempDir = localDir + File.separatorChar+ftpFile.getName();
try {
File temp = new File(tempDir);
temp.mkdirs();
} catch (Exception e) {
System.out.println("Could not create local directory "+tempDir);
return false;
}
if(ftpClient.changeWorkingDirectory(ftpFile.getName())) {
downloadFTPDir(tempDir, ftpClient);
} else {
System.out.println("Could change directory to "+ftpFile.getName()+" on FTP server");
return false;
}
} else {
output = new FileOutputStream(localDir + File.separatorChar + ftpFile.getName());
if (!ftpClient.retrieveFile(ftpFile.getName(), output)) {
System.out.println("Unable to download file from FTP server : " + ftpFile.getName());
File tmp = null;
try {
output.close();
/*tmp = new File(localDir + File.separatorChar + ftpFile.getName());
tmp.delete();
logger.info("Deleted corrupt downloaded file : " + tmp.getAbsolutePath());*/
} catch (FTPConnectionClosedException e) {
System.out.println("Connection to FTP server is closed ");
return false;
} catch (Exception e1) {
System.out.println("Unable to delete corrupt file from local directory : " + tmp.getAbsolutePath());
return false;
}
}
output.close();
System.out.println("FTP file download successful : " + ftpFile.getName());
}
}
} catch (FTPConnectionClosedException e) {
e.printStackTrace();
return false;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return false;
} catch (IOException e2) {
e2.printStackTrace();
return false;
} catch (Exception e3) {
try {
output.close();
} catch (Exception e4) {
e3.printStackTrace();
}
return false;
} finally{
try {
if(output!=null)
output.close();
} catch (Exception e5) {
e5.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("FTP IP", 21);
System.out.println("connecting");
if(FTPReply.isPositiveCompletion(ftpClient.getReply())) {
System.out.println("connected");
if(!ftpClient.login("FTP username", "FTP Password")) {
System.out.println("could not login");
ftpClient.disconnect();
return;
}
System.out.println("logged in");
String remotePath = "FTP directory Path";
StringTokenizer st = new StringTokenizer(remotePath, "/");
String dir = null;
boolean status = false;
while (st.hasMoreTokens()) {
dir = st.nextToken();
status = ftpClient.changeWorkingDirectory(dir);
if (!status) {
System.out.println("FTP client is not able to change the current directory to " + dir);
return ;
}
}
System.out.println("connected");
downloadFTPDir("local path", ftpClient);
} else {
ftpClient.disconnect();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories