How to create sub folder with username in java - java-io

I am making a small project there is a one module, which is KYC update and In this module i am save AadharCard,PAN Card and Other documents in Folder.So I am using java IO and try to create directory which name is Document and i want to create a sub-directory with user name and for create unique a also append username,id concat.I write a code but the sub-directory didn't crate.
My code is
String uploadPath = context.getRealPath("") + "assets" + File.separator + "Document" + File.separator
+ userPojo.getFirstName();
File file = new File(uploadPath);
try {
if (!file.exists()) {
file.mkdirs();
logger.debug("Make Dir");
}
and I also try this
File file = new File(dir, userPojo.getUserName());
if (!file.exists()) {
file.mkdirs();
logger.debug("Make Dir");
}

I search and i solve my problem.So i want to give solution if anyone face this type of problem
File file = new File(uploadPath);
File file2 = new File(uploadPath, dataPojo.getFirstName()));
if (!file.exists()) {
file.mkdirs();
logger.debug(file.getAbsolutePath());
}
if (!file2.exists()) {
file2.mkdirs();
logger.debug(file.getAbsolutePath());
}

Related

How to create a string for #Html.ActionLink that concatenates an integer from the Model and a string

I'm using VS2015, MVC 5 design model. Creating a link that says "View" to open a PDF file in a new browser tab. It works fine, but the document sub-directory is hard-coded in the controller. I need to pass the document sub-directory + filename to the controller. The document sub-directory is the same as the Model.id . I'm having a difficult time converting the Model.id to a string and concatenating with the filename.
The following code in the view works fine with the hard-coded sub-directory in the controller
<td>#Html.ActionLink("View", "ViewAttachedDoc", "Documents", new { filename = item.filename}, new { target = "_blank" })</td>
But this code does not work
<td>#Html.ActionLink("View", "ViewAttachedDoc", "Documents", new { filename = Convert.ToString(Model.id) + "\" + item.filename }, new { target = "_blank" })</td>
The controller action is:
public FileResult ViewAttachedDoc(string filename)
{
string DocPath = ConfigurationManager.AppSettings["DocPath"];
string path = Path.Combine(DocPath, filename);
return File(path, "application/pdf");
}
TIA,
Tracy
The issue is likely from trying to pass a backslash through the URL. This link of a similar question has that same problem and their solution was to use HttpUtility.UrlEncode(value); and HttpUtility.UrlDecode(value);. Otherwise if that still doesn't work, what error are you getting?
P.S. C# automatically converts / -> \ for retrieving files.

Spring boot SFTP, dynamic directory in SFTP

I tried to upload files to dynamic directory to SFTP. When I uploaded some files, the first file always uploaded to the last directory. Then after that rest file will be uploaded to the correct directory. When I did debug mode, I saw that every first file would be uploaded to temporaryDirectory which is the code already set up by spring. I don't know how to set the value of this temporaryDirectory to the right value. Please, help me to solve the problem.
Or maybe you guys have other way to upload and create proper dynamic directory. Please let me know.
Here is the code:
private String sftpRemoteDirectory = "documents/"
#MessagingGateway
public interface UploadGateway {
#Gateway(requestChannel = "toSftpChannel")
void upload(File file, #Header("dirName") String dirName);
}
#Bean
#ServiceActivator(inputChannel = "toSftpChannel")
public MessageHandler handler() {
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
String newDynamicDirectory = "E" + formatter.format(new Date())+String.format("%04d",Integer.parseInt("0001") + 1);
handler.setRemoteDirectoryExpression(new LiteralExpression(sftpRemoteDirectory + newDynamicDirectory));
handler.setFileNameGenerator(message -> {
String dirName = (String) message.getHeaders().get("dirName");
handler.setRemoteDirectoryExpression(new LiteralExpression(sftpRemoteDirectory + dirName));
handler.setAutoCreateDirectory(true);
if (message.getPayload() instanceof File) {
return (((File) message.getPayload()).getName());
} else {
throw new IllegalArgumentException("File expected as payload!");
}
});
return handler;
}
You are using a LiteralExpression, evaluated just once, you need an expression that's evaluated at runtime.
handler.setRemoteDirectoryExpressionString("'" + sftpRemoteDirectory/ + "'" + headers['dirName']);

How to copy google doc to another folder in google drive service

I have a class that makes a copy of a google doc template file to then merge placeholders with data. The problem is that it's creating the copy in the same folder as the original template file and I can't find a way to copy it to another folder.
Say I have a structure like so in google drive.
Main
TemplateFiles
MainTemplateDoc
Contracts
CopyOfMainTemplateDocAfterBeingMerged
As you can see, the CopyOfMainTemplateDocAfterBeingMerged doc wouldn't be located in the TemplateFiles folder where the original template was, but copied to the Contracts folder.
Is it possible to use the google drive v2 service to move the file after creating the copy? I'm using the .net Google.Apis.Drive.v2 nuget package. Here's the code that I have so far to create the copy.
private string CopyDocument(string documentId, string title)
{
var newFile = new File { Title = title };
var documentCopyFile = driveService.Files.Copy(newFile, documentId).Execute();
return documentCopyFile.Id;
}
You are using Drive API v2.
You want to copy a file to the folder of Contracts.
You have already been able to use Drive API.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
In this answer, I would like to propose the following modification.
From:
var newFile = new File { Title = title };
To:
var newFile = new File {
Title = title,
Parents = new List<ParentReference> {new ParentReference {Id = parentId}}
};
or
var newFile = new File() {
Title = title
};
newFile.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}};
or
var newFile = new File();
newFile.Title = title;
newFile.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}};
parentId is the folder ID of the folder Contracts.
Note:
If you want to use Drive API v3, please use new List<string> {folderId} instead of new List<ParentReference> {new ParentReference {Id = folderId}}.
References:
Files: copy
Files: insert
If I misunderstood your question and this was not the direction you want, I apologize.

Upload a image in a porltet Liferay

I am doing a portlet to create banners. I preferences I made the form with: input type="file" and the form nctype='multipart/form-data'
In the processAction I get the image, but I don't know how save it in the server, because I only get save in temporal instance portlet, but if I restart the server I lose the image.
This is my code to save the image:
private boolean uploadFile( ActionRequest request, ActionResponse response) throws ValidatorException, IOException, ReadOnlyException {
try {
// Si la request es del tipo multipart ...
if (PortletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
PortletFileUpload servletFileUpload = new PortletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(81920); // bytes
List fileItemsList = servletFileUpload.parseRequest(request);
Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (fileItem.isFormField()){
}
else{
String nombreCampo = fileItem.getFieldName();
String nombreArchivo = fileItem.getName();
String extension = nombreArchivo.substring(nombreArchivo.indexOf("."));
PortletContext context = request.getPortletSession().getPortletContext();
String path = context.getRealPath("/images");
File archivo = new File(path + "/" + nombreArchivo);
PortletContext pc = request.getPortletSession().getPortletContext();
fileItem.write(archivo);
}
}
}
} catch (Exception e) {}
return true;
}
I don't know if I am doing something wrong or this isn't the correct way.
Any idea?
Thanks in advance
EDIT:
Finally I tried do it with DLFolderLocalServiceUtil and DLFileEntryLocalServiceUtil, but it doesn't work correctly. When I load the page you can see the image, but after, when the page is load completely, the image disappears.
I don't know if it is because I don't create fine the fileEntry or the url is wrong.
This is my code:
long folderId = CounterLocalServiceUtil.increment(DLFolder.class.getName());
DLFolder folder = DLFolderLocalServiceUtil.createDLFolder(folderId);
long userId = themeDisplay.getUserId();
long groupId = themeDisplay.getScopeGroupId();
folder.setUserId(userId);
folder.setGroupId(groupId);
folder.setName("Banner image " + nombreArchivo+String.valueOf(folderId));
DLFolderLocalServiceUtil.updateDLFolder(folder);
ServiceContext serviceContext= ServiceContextFactory.getInstance(DLFileEntry.class.getName(), request);
File myfile = new File(nombreArchivo);
fileItem.write(myfile);
List<DLFileEntryType> tip = DLFileEntryTypeLocalServiceUtil.getFileEntryTypes(DLUtil.getGroupIds(themeDisplay));
DLFileEntry DLfileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, 0, folderId, null, MimeTypesUtil.getContentType(myfile), nombreArchivo, "Image banner_"+nombreArchivo, "", tip.get(0).getFileEntryTypeId(), null, myfile, fileItem.getInputStream(), myfile.getTotalSpace(), serviceContext);
FileVersion fileVersion = null;
//FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, nombreArchivo);
//String path = DLUtil.getPreviewURL(fileEntry, fileVersion, themeDisplay, "&imagePreview=1");
String path1 = themeDisplay.getPortalURL()+"/c/document_library/get_file?uuid="+DLfileEntry.getUuid()+"&groupId="+themeDisplay.getScopeGroupId();
String path = "/documents/" + DLfileEntry.getGroupId() + "/" + DLfileEntry.getFolderId() + "/" + DLfileEntry.getTitle()+"/"+DLfileEntry.getUuid();
System.out.println("path " + path);
System.out.println("path " + path1);
prefs.setValue(nombreCampo, path);
And this is the output:
path /documents/10180/0/cinesa888.png/f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f
path http://localhost:8080/c/document_library/get_file?uuid=f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f&groupId=10180
I tried to get the url like lpratlong said (DLUtil) but when I tried to get the FileEntry with DLAppServiceUtil.getFileEntry(..) I have an error that says no exist FileEntry.
I don't know what I am doing wrong.. Any idea?
Thanks.
You can use Liferay API to store the file in the Document Library : take a look in DLFolder and DLFileEntry API (for exemple, DLFileEntryLocalServiceUtil will show you allowed local operations).
These API will allowed you to store your file in your file system (in the "data" folder of your Liferay installation) and to store reference of your file in Liferay database.

How to get sub-folder names from a given path Server.MapPath

I want get the folder names from server.MapPath in ASP.NET MVC 3 application.
In this action, I have to check (if there exist more folders in a given folder name) if a .jpg file is in that folder and if so, return that folder.
string path = Server.MapPath("Content/");
DirectoryInfo dInfo = new DirectoryInfo(path);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
if (Directory.Exists(path))
{
ArrayList ar = new ArrayList();
// This path is a directory
ar.Add(path);
//ProcessDirectory(path);
}
I'm not sure I've understand the qestion correctly, but I think you want something like
string path = Server.MapPath(YOURPATH);
List<string> files = Directory.GetFiles(path, "*.jpg", SearchOption.AllDirectories);
or something like
string path = Server.MapPath(YOURPATH);
List<string> picFolders = new List<string>();
if(Directory.GetFiles(path, "*.jpg").Length > 0)
picFolders.Add(path)
foreach(string dir in Directory.GetDirectories(path, "*", SearchOption.AllDirectories))
{
if(Directory.GetFiles(dir, "*.jpg").Length > 0)
picFolders.Add(dir)
}

Resources