i want to give specific name to the uploaded file in my destination folder.. this is my action file code.. here i want to give name like CPIC_1.jpg,CPIC_2.jpg,CPIC_3.jpg,CPIC_4.jpg etc but every time it is assigning name : CPIC_1.jpg.. so how i declare variable ext so that through out it will be distinct..
CommercialFileBean b = (CommercialFileBean) form;
FormFile f = b.getF();
String s = request.getParameter("action");
HttpSession session = request.getSession(false);
String n = (String) session.getAttribute("str");
String email = session.getAttribute("uname").toString();
String status = (String) session.getAttribute("status");
String type = request.getParameter("type");
String pid;
long ext=0;
int id;
if (s.equalsIgnoreCase("finish")) {
return mapping.findForward(next);
} else { /// first else
String a = getServlet().getServletContext().getRealPath("/");
File file = new File(a + "uploaded/CPIC_"+ ++ext+".jpg");
if (!file.exists()) {
FileOutputStream out = new FileOutputStream(file);
out.write(f.getFileData());
out.close();
}
try {
if (n.equalsIgnoreCase("rent")) {
Session sess = UtilClass.createSession();
Transaction tx = sess.beginTransaction();
if (status.equalsIgnoreCase("new")) {
String sql1 = "select MAX(id) from Rentcommercialrecord where loginid=:email";
Query q1 = sess.createQuery(sql1);
q1.setParameter("email", email);
// JOptionPane.showMessageDialog(null, "max id is :");
List<Rentcommercialrecord> l = q1.list();
Rentcommercialrecord rc = l.get(l.size()-1);
id = rc.getId();
} else {
pid = (String) session.getAttribute("id");
id = Integer.parseInt(pid);
}
JOptionPane.showMessageDialog(null, " latest id is :" + id);
if (type.equalsIgnoreCase("frontpic")) {
try {
String file1 = f.getFileName();
JOptionPane.showMessageDialog(null, "file name is : "+file1);
Rentcommercialrecord rc1 = (Rentcommercialrecord) sess.get(Rentcommercialrecord.class, id);
rc1.setImg1("CPIC_" +ext+".jpg");
sess.update(rc1);
// JOptionPane.showMessageDialog(null, "img1");
} // img1 try ends
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Second error is : " + e.getMessage());
}
} // fontpic if ends
else {
try {
String file1 = f.getFileName();
JOptionPane.showMessageDialog(null, "file name is : "+file1);
Rentcommercialrecord rc1 = (Rentcommercialrecord) sess.get(Rentcommercialrecord.class, id);
rc1.setImg2("CPIC_" +ext+".jpg");
sess.update(rc1);
// JOptionPane.showMessageDialog(null, "img2");
} // img2 try ends
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Second error is : " + e.getMessage());
}
} // else img2 ends
// l.size if ends
tx.commit();
}
Make your variable ext as static.
static long ext = 0;
This will make the variable common to all instances.
Note : You need to store this value somewhere in db / file during restart and get it during application startup to make it consistent irrespective of restart of your application
You can make your ext variable static
Note: The scope of your static variable is for the current class Loader. ie, if it is a diff class loader is used , this will change.
other option is store the ext value in session and every time you upload a new image file, get this value from session and use it. And you need to put the new value back into session as well. This approach will work for per user. ie if your application is having diff users, for diff users it will have diff value based on session
You can use a static variable, but it won't be consistent through application restarts.
I would change approach and would read filenames, then extracting the numbers from their names, getting the highest, incrementing it and then writing a new file.
Use Apache Commons to avoid reinventing the wheel.
Kickoff example:
String path = getServlet().getServletContext().getRealPath("/") + "uploaded/";
String partialName = "CPIC_";
int markerLength = partialName.length();
int maxValue = 0;
// Find all files, if any, with name starting with "CPIC_" in the desired folder
List<File> files = FileUtils.listFiles(new File(path),
new PrefixFileFilter(partialName),
null);
if (!files.isEmpty()){
for (File file : files) {
// Strip marker and extension
int num = Integer.parseInt(
file.getName().substring(markerLength,
file.getName().indexOf("."))
);
// compare the number, if greater, set as new max value
if (num > maxValue) {
maxValue = num;
}
}
}
String newFile = partialName + ++maxValue + ".jpg";
System.out.println("Next file name would be : " + newFile);
Related
I have spring boot application where the user sends parameter and based on this parameter, there are configuration should be get.
I created file name configuration type “Configration_Types.properies” , now how can I read the configuration based on parameter pass I don't want to create database to lookup it?
Type1=Type1
Type1.width=60
Type1.heght=715
Type2=Type2
Type2.width=100
Type2.heght=720
Type3=Type3
Type3.width=100
Type3.heght=700
Type4=Type4
Type4.width=450
Type4.heght=680
Type5=Type5
Type5.width=270
Type5.heght=750
for example pass type4 should get configuration
Type4
450
680
The function could be like that :
public void readPropertyByType(String type)
{
InputStream input = null;
try
{
Properties prop = new Properties();
// if your type is Type4, the typeKey will be Type4. for compare data
String typeKey = type + ".";
String filename = "config.properties";
input = new FileInputStream(filename);
prop.load(input);
String typeInformation = "";
Enumeration< ? > e = prop.propertyNames();
while (e.hasMoreElements())
{
String key = (String)e.nextElement();
if (key.indexOf(typeKey) > 0)
{
typeInformation = typeInformation + prop.getProperty(key);
}
}
System.out.println("The data of type " + type + "is :" + typeInformation);
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
But you make a better design for your property file.
In case the order of property file never change, you can stop the
function when you get all expected data, don't need to loop whole
file.
Hope it help.
---UPDATE---
The property file could be like that :
Option 1
Type4.width=450
Type4.heght=680
Type5.width=450
Type5.heght=680
Option 2
Type4=450, 680
Type5=450, 680
Depend on each option, you can break the while loop when you got the expected data.
If you can modified your property file Configration_Types.properies like:-
type[0].width=60
type[0].heght=715
type[1].width=100
type[1].heght=720
type[2].width=100
type[2].heght=700
type[3].width=450
type[3].heght=680
type[4].width=270
type[4].heght=750
And your class for consume property values from property file would be:-
#Component
#ConfigurationProperties("type") // prefix type, find type.* values
public class GlobalProperties {
private List<Type> type = new ArrayList<Type>();
//getters and setters
public static class Type
{
private int width;
private int heght;
// getter setter
}
And As based on user params you can access the value from arraylist.
hope this help:
I developed a Java program to search particular file in particular folder on Google Drive. It uses DFS(Depth First Search) algorithm to search.
However, the searching efficiency is very bad. If the file is located in the "later" or deeper folder, the program will take several minutes to find it if found, or sometimes it will be time out and respond an HTTP 500 Internal Server Error.
The program is as follows:
public static void main(String[] args) throws IOException {
DriveSearch driveSearch = new DriveSearch();
String searchResult = driveSearch.fetchData("F1b1ZuRUpPLWh6",
"test.txt");
System.out.println(searchResult);
}
public String fetchData(String folderID, String searchFileName) {
String result = "";
~~~~~ Skip Codes for Authorization ~~~~
// try {
// try {
Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
long startTime = System.currentTimeMillis(); // Begin search time
// String pageToken = null;
// do {
System.out.println("=== Begin Search ===");
File searchResult = recursiveSearch(folderID, searchFileName);
System.out.println("=== End Search ===");
long endTime = System.currentTimeMillis(); // End search time
long totTime = (endTime - startTime) / 1000;
System.out.println("This search takes " + totTime + " seconds to find the file.");
if (searchResult != null) {
result = searchResult.getName();
}
// pageToken = fileList.getNextPageToken();
// } while (pageToken != null);
// } catch (IOException e) {
// result = "invalid_grant";
// System.err.println(e.getMessage());
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
return result;
}
public File recursiveSearch(String folderID, String searchFileName) throws IOException {
File searchResult = null;
FileList fileList = service.files().list().setQ("'" + folderID + "' in parents and trashed = false")
// .setSpaces("drive")
.setCorpora("user").setFields("nextPageToken, files(id, name, mimeType)").execute();
List<File> items = fileList.getFiles();
for (File file : items) {
if (file.getName().equals(searchFileName)) {
searchResult = file;
System.out.println(file.getName() + " is found!");
return searchResult;
} else if (file.getMimeType().equals("application/vnd.google-apps.folder")) {
System.out.println("Recursive Search");
System.out.println("file.getId() is " + file.getId());
searchResult = recursiveSearch(file.getId(), searchFileName);
} else {
System.out.println("file name is " + file.getName());
}
}
return searchResult;
}
Since specific file can be found immediately on Google Drive search bar, can it also be immediately found in specific folder? If yes, what should I do to improve the searching efficiency? Thank you for any suggestion.
The expensive part are the calls to Google Drive in each recursive call. They are not necessary. You can fetch the list of all files in one call:
/**
* Read file list from Google Drive.
* #param service an authenticated <code>Drive</code> object needed to send the request
* #return Answer the list of files.
* #throws IOException
*/
protected List<File> readFiles( final Drive service ) throws IOException {
final List<File> result = new ArrayList<File>();
final Files.List request = service.files().list();
do {
final FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
return result;
}
Afterwards search the list of files for your files. Of course you may add a filter o your request as you did in your code, e.g. to filter out trashed files.
I have to create a web application in java to upload all types of file.War file will be deployed on the linux server.The problem is path.Everything is working on localhost but when it deployed to linux server its not working,the page became empty.The below is my code:
try {
dbConnectionUtils db = new dbConnectionUtils();
Connection conn = null;
try {
conn = db.getConnection();
} catch (ClassNotFoundException ex) {
Logger.getLogger(upload_images.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(upload_images.class.getName()).log(Level.SEVERE, null, ex);
}
Map<String, String> paramMap = new LinkedHashMap<String, String>();
InputStream filecontent = null;
FileItem modelFile = null;
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(50 * 1024 * 1024);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
// List<FileItem> items = new ServletFileUpload(new
// DiskFileItemFactory()).parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
// System.out.println("TESTING " + fieldname + " : "
// + fieldvalue);
paramMap.put(fieldname, fieldvalue);
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
modelFile = item;
System.out.println("ModelFile"+modelFile);
filecontent = item.getInputStream();
// ... (do your job here)
// System.out.println("TESTING *****" + fieldname + " : "
// + filename + " : " + item.getName());
paramMap.put(fieldname, filename);
}
}
System.out.println("filemanager");
String filemanager = paramMap.get("filemanager");
if ((filemanager != null) && (filemanager.equalsIgnoreCase("Submit"))) {
try {
System.out.println("Inside");
String filename = paramMap.get("filename");
String file = paramMap.get("file");
System.out.println("........." + file);
String prj = paramMap.get("PjList");
if (null != filename && null != file) {
String relative = getRealpath() + "filemanager\\" + request.getSession(true).getAttribute("logged_user_id") + "\\";
File mkTime = new File(relative);
mkTime.mkdirs();
String ipath = uploadData(modelFile, relative);
FileInputStream fis = new FileInputStream(ipath);
Statement st = conn.createStatement();
conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection) conn).getLargeObjectAPI();
//create a new large object
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
//open the large object for write
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0) {
obj.write(buf, 0, s);
tl += s;
}
// Close the large object
obj.close();
int f=8;
String fileType = modelFile.getContentType();
}
does the user/owner on the hosting server have permissions to write to the folders/create a subfolder in the PWD you are running your WAR from? CHMOD 777 your WARs folder and see if it lets you create the relative subdir needed to run.
If that is not the case the reason you are not seeing an error is you only defined ClassNotFoundException and SQLException errors and not a more general error catch to report the access issues that I think you might be having.
Put a generic error catch around your try{} and print the error, I think you'll get some sort of access error.
You should always use "/" as path separators in Java.
"\" only works on Windows.
I have a "moreinfo" Directory which has some html file and other folder. I am searching the file in the moreinfo directory( and not sub directory in moreinfo) matches with toolId*.The names of the file is same as toolId],
Below is a code snippet how i writing it, In case my toolId = delegatedAccess the list returns 2 file (delegatedAccess.html & delegatedAccess.shopping.html) based on the wide card filter(toolId*)
Is their a better way of writing the regular expression that check until last occurring period and return the file that matches exactly with my toolId?
infoDir =/Users/moreinfo
private String getMoreInfoUrl(File infoDir, String toolId) {
String moreInfoUrl = null;
try {
Collection<File> files = FileUtils.listFiles(infoDir, new WildcardFileFilter(toolId+"*"), null);
if (files.isEmpty()==false) {
File mFile = files.iterator().next();
moreInfoUrl = libraryPath + mFile.getName(); // toolId;
}
} catch (Exception e) {
M_log.info("unable to read moreinfo" + e.getMessage());
}
return moreInfoUrl;
}
This is what i end up doing with all the great comments. I did string manipulation to solve my problem. As Regex was not right solution to it.
private String getMoreInfoUrl(File infoDir, String toolId) {
String moreInfoUrl = null;
try {
Collection<File> files = FileUtils.listFiles(infoDir, new WildcardFileFilter(toolId+"*"), null);
if (files.isEmpty()==false) {
for (File mFile : files) {
int lastIndexOfPeriod = mFile.getName().lastIndexOf('.');
String fNameWithOutExtension = mFile.getName().substring(0,lastIndexOfPeriod);
if(fNameWithOutExtension.equals(toolId)) {
moreInfoUrl = libraryPath + mFile.getName();
break;
}
}
}
} catch (Exception e) {
M_log.info("unable to read moreinfo" + e.getMessage());
}
return moreInfoUrl;
}
I have the following code which must add new values to the existing properties in the .properties file of, if the property doesn't exist - create it.
public String saveProperties(ArrayList<Property> properties, String customerId){
final String userPropFieldName = "users." + customerId + ".rules";
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
for (Property property: properties){
String fieldName = "rules." + property.getName() + "." + property.getType();
String[] values = (property.getValue()).split("\\,");
for (String word: values){
System.out.print(word + " ");
}
if (util.exist(fieldName, props)){
props.setProperty(fieldName, values);
} else {
props.addProperty(fieldName, values);
}
String[] userProperties = props.getStringArray(userPropFieldName);
if (property.getAccepted()){
userProperties = util.addNewValue(userProperties, fieldName);
} else {
userProperties = util.removeValue(userProperties, fieldName);
}
props.setProperty(userPropFieldName, userProperties);
}
}catch (ConfigurationException e){
e.printStackTrace();
}
return "Saved";
}
I run it with the debugger and all values right, I mean, there are the proper name of the property and the proper values in the array, so, seen that it came up to the adding or setting new value, but finally I didn't see any changes in the property file.
Save your modified properties to file
props.save();
Read more: http://commons.apache.org/proper/commons-configuration/userguide/howto_properties.html#Saving
BTW, Saving properties directly to source code (src/main/resources/rules.properties) is usually bad idea.