How to generate unique filenames??

i need to be able to generate unique files from a servlet..
my initial instinct was to use the seesion id as part of the filename, however as this file will be embedded in the responding html, this is not safe, as the user will only have to look at the html source to view a session id value.
i am now considering to use the date/time of the creation of a session as the unique identifier for the file, however this will not work if two sessions can be created at the same time.
my question thefore is if no two sessions can have the same date and time?
if not.. can anyone give me an idea as how to produce unique filenames?

If you are actually creating a file, why not usethe
java.io.File.createTempFile() method?how does that help with prducing a unique value to use
as the name of a file?
with that method i still need to supply the filename
as one of its arguments!
No you don't. You provide a prefix and suffix and it fills in the middle with something guaranteed to be unique, in the directory you specify. Here is the javadoc:
createTempFile
public static File createTempFile(String prefix,
String suffix,
File directory)
throws IOException
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
1. The file denoted by the returned abstract pathname did not exist before this method was invoked, and
2. Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as "hjb" or "mail". The suffix argument may be null, in which case the suffix ".tmp" will be used.
To create the new file, the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform. If the prefix is too long then it will be truncated, but its first three characters will always be preserved. If the suffix is too long then it too will be truncated, but if it begins with a period character ('.') then the period and the first three characters following it will always be preserved. Once these adjustments have been made the name of the new file will be generated by concatenating the prefix, five or more internally-generated characters, and the suffix.
If the directory argument is null then the system-dependent default temporary-file directory will be used. The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.
Parameters:
prefix - The prefix string to be used in generating the file's name; must be at least three characters long
suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used
directory - The directory in which the file is to be created, or null if the default temporary-file directory is to be used
Returns:
An abstract pathname denoting a newly-created empty file
Throws:
IllegalArgumentException - If the prefix argument contains fewer than three characters
IOException - If a file could not be created
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created
Since:
1.2

Similar Messages

  • How to generate unique numbers

    hi all,
    I want to generate unique numbers always starting from 1 using a single sql query and I dont want to use a sequence and i dont think rownum will be helpful for generating unique numbers in all cases . how to do this ?
    thanks & regards,
    kumar.

    If two users get the MAX from temp, they would be updating with the same value for two different rows.If TEMP is a genuine temporary table, this is not an issue, because the data in a temporary table is only visible within a session.
    The big problem with this approach is the mutating table one: we cannot issue the requisite select statement from a BEFORE INSERT trigger. So this solution is only going to work with a view and an INSTEAD OF INSERT trigger.
    Another, more workable, solution is to use a code control table. This can be (should be) another temporary table, with one row holding one column - next value for TEMP.ID. Normally we would rule out such a solution because it serializes access to the inserted table, but as this is only on a per session basis, it doesn't matter.
    CREATE OR REPLACE TRIGGER tmp_bir BEFORE INSERT ON temp1 FOR EACH ROW
    DECLARE
      ln NUMBER;
    BEGIN
      SELECT nvl(code1.next_id,1) INTO ln
      FROM code1;
      :NEW.id := ln;
      UPDATE code1
      SET    next_id := ln+1;
    END;Beware: coded freehand, so may need debugging.
    Cheers, APC

  • How to Generate Unique Cache Keys?

    I'm trying to improve the performance of my ColdFusion 10 application by making better use of caching.  I have a particular DAO/Gateway CFC that queries a particular database.  I added query caching to the query in this CFC and it made a huge difference.
    Since this database is outside my control for edits/updates, I need to be able to initiate flushing of the cached queries for this database only.  I don't believe the built-in ColdFusion ehcache query cache allows for granular control of flushing - in CF Administrator you pretty much can only flush the entire cache.
    So I figured the only solution was to create my own cache region that would be associated with just this database, and manually cache the queries into that region.  Then I can flush just that region without impacting any other cached queries.
    So here's my difficulty:  I believe that Internally, ColdFusion caches queries using a hash of the generated SQL.  I'm thinking I'll store my queries in cache with a key that hashes the input parameters.  Would the built-in Hash() function be the appropriate mechanism to create cache keys that are unique for each parameter combination?  Does it matter what algorithm I use with Hash()?
    Thanks,
    -Carl V.

    Sorry, didn't see your original question! You might be better asking this on StackOverflow, as there's more people who have more experience with CF keeping an eye on the questions there.
    What I can offer is that MD5 hashes are not guaranteed unique for different input strings. It's unlikely to happen, but it can happen. I think - but am not sure - more "thorough" hashing algorithms might be more likely to have a higher degree of uniqueness.
    That said, the general approach is how these things are generally done.  And it's very very unlikely that you'll ever come to use a combination of elements contributing to the key that will generate a hash that you've already used for something else.
    Adam

  • How to generate unique PKIDs to add a new translation

    We need to add a new translation to the table commonXLAExtensionCache. However in the documentation it states:
    -Verify that the pkid that is being inserted is unique per insert. It must start with 1058.
    How can we generate a unique pkid, is there a database command.
    For this example, we are adding a new translation for a custom FlexSync report are using.

    MSSQL DB
    select '1058' + upper(newid());
    Oracle DB
    select ('1058' || newid) from dual;

  • How to generate unique IDs for a metadata field

    Hi,
    We have a requirement to generate a unique ID for a metadata field. Does anybody know how this can be achieved? Ideally I would want to have a database sequence and specify the metadata field to get value from this database sequence, similar to how Content ID is generated.
    Any help is appreciated. Thank you in advance.
    Regards,
    Tim

    Look into the Counters table. You should be able to create a component install filter to add in your field to the Counters table.
    You could then create some Java code to fetch the next value from the Counters database for your field (and increment the value).
    Jonathan
    http://redstonecontentsolutions.com
    http://corecontentonly.com

  • How to Generate   Unique Serial No in Oracle 6i report

    Hi
    I want to generate a unique serial no for every row ,
    how can i achieve this result.
    thanx in advance

    You can also use the analytical function ROW_NUMBER in your query
    SELECT ...
               ROW_NUMBER() OVER (ORDER BY YOURORDERBY) RN
      FROM TABLE
    ORDER BY RN;

  • How to generate Unique Seq Id in BPEL

    Hi All,
    How can we generate a unique seq Id in BPEL.
    One way is to use "*orcl:generate-guid()*" .
    Are there any other ways by which we can generate the unique seq id. please send me some sample piece of code if any for example.
    Regards
    Narendra
    Mail to: [email protected]

    Probably not best practice, but I created a sequence in one of my Oracle DBs to call and get a unique ID. You could do something similar with a call to a SQL DB. If you don't care if it is a number or not you could use the Generate GUID function within BPEL.
    --S                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to generate unique values while initializing values

    I am initializing values in my pl/sql program and want to use a sequence to set my unique ids but it errors out. Below is what I use.
    ie. table_id := table_seq.nextval;
    How can I use my sequence to initialize values or is this possible?

    The method suggested by user605919 will work. However, you don't need to initialize a variable like this. It is better and more performant to do it like the third example below:
    SQL> create table mytable
      2  ( id number(6)
      3  , description varchar2(30)
      4  )
      5  /
    Tabel is aangemaakt.
    SQL> create sequence table_seq start with 1 increment by 1
      2  /
    Reeks is aangemaakt.
    SQL> declare
      2    table_id mytable.id%type := table_seq.nextval;
      3  begin
      4    insert into mytable
      5    ( id
      6    , description
      7    )
      8    values
      9    ( table_id
    10    , 'Some description'
    11    );
    12  end;
    13  /
      table_id mytable.id%type := table_seq.nextval;
    FOUT in regel 2:
    .ORA-06550: line 2, column 41:
    PLS-00357: Table,View Or Sequence reference 'TABLE_SEQ.NEXTVAL' not allowed in this context
    ORA-06550: line 2, column 12:
    PL/SQL: Item ignored
    ORA-06550: line 9, column 5:
    PLS-00320: the declaration of the type of this expression is incomplete or malformed
    ORA-06550: line 9, column 5:
    PL/SQL: ORA-00904: "TABLE_ID": invalid identifier
    ORA-06550: line 4, column 3:
    PL/SQL: SQL Statement ignored
    SQL> declare
      2    table_id mytable.id%type;
      3  begin
      4    select table_seq.nextval
      5      into table_id
      6      from dual
      7    ;
      8    insert into mytable
      9    ( id
    10    , description
    11    )
    12    values
    13    ( table_id
    14    , 'Some description'
    15    );
    16  end;
    17  /
    PL/SQL-procedure is geslaagd.
    SQL> begin
      2    insert into mytable
      3    ( id
      4    , description
      5    )
      6    values
      7    ( table_seq.nextval
      8    , 'Some description'
      9    );
    10  end;
    11  /
    PL/SQL-procedure is geslaagd.And if you need the id value for some code after the insert, you use the RETURNING clause.
    Regards,
    Rob.

  • How to generate unique random numbers

    Hi All,
    I am wondering whether there is already a random library or built-in function available in Java to produce some random numbers between certain ranges that are not repetitive. Let's look at a common examples as follows:
    Random diceRoller = new Random();
    for (int i = 0; i < 10; i++) {
      int roll = diceRoller.nextInt(6) + 1;
      System.out.println(roll);
    }My understanding from this approach is that it allows the same number to be repeated over and over again. However, I would like to find out how to continue generating random numbers from remaining ones that haven't been generated earlier.
    Using the above example to illustrate my intention:
    1st random number generated - possibility of 1 - 6 showed up. Say 5 is picked.
    2nd random number generated - possibility of 1, 2, 3, 4, 6 only. Say 2 is picked.
    3rd random number generated - possibility of 1, 3, 4, 6 available. Say 1 is picked.
    4th random number generated - possibility of 3, 4, 6 left. Say 6 is picked.
    5th random number generated - possibility of 3, 4 remains. Say 4 is picked.
    Any assistance would be much appreciated.
    Many thanks,
    Jack

    htran_888 wrote:
    Hi All,
    I am wondering whether there is already a random library or built-in function available in Java to produce some random numbers between certain ranges that are not repetitive. Let's look at a common examples as follows:
    Random diceRoller = new Random();
    for (int i = 0; i < 10; i++) {
    int roll = diceRoller.nextInt(6) + 1;
    System.out.println(roll);
    }My understanding from this approach is that it allows the same number to be repeated over and over again. However, I would like to find out how to continue generating random numbers from remaining ones that haven't been generated earlier.
    Using the above example to illustrate my intention:
    1st random number generated - possibility of 1 - 6 showed up. Say 5 is picked.
    2nd random number generated - possibility of 1, 2, 3, 4, 6 only. Say 2 is picked.
    3rd random number generated - possibility of 1, 3, 4, 6 available. Say 1 is picked.
    4th random number generated - possibility of 3, 4, 6 left. Say 6 is picked.
    5th random number generated - possibility of 3, 4 remains. Say 4 is picked.
    Any assistance would be much appreciated.If it is your school assignment then you have the answer above (List & the lists length).
    (You might want to look at Collections)

  • How to generate unique document number ?

    Hi All,
    We need to generate Document Number where there should be any gap, so that we cannot use sequence. For example : Invoice Number.
    one possible approach like : Select MAX(InvoiceNumber)+1 from invoice, what if that table has millions of rows, is this reliable enough ?
    How to avoid two user do the same query at same time that lead to dupplicate number ?
    Anybody has done it this way in production? or any other approach ?
    Thank you for your info,
    xtanto

    I strongly second Justin's strong suggestion about re-considering the requirement.
    Be aware that for any of the schemes suggested to have a chance of working, all access to the table must be through stored procedures that use a SELECT FOR UPDATE on the counter table. No user in the database can have insert privileges on the document table except the owner. The owner's password should be kept in a locked safe and be unknown to anyone. If for some reason the owner needs access to the database, then remove the password from the safe, do what needs to be done, then get some guy off the street to set a new password, write it down and lock it in the safe again.
    If you really need a gap-free number, it needsto be another column, separate from the PK. Use a sequence to generate the pk gaps and all, then create a procedure that runs periodically to update the gap free column. Soemthing like:
    SQL> CREATE PROCEDURE fix_gap_free AS
      2     l_v NUMBER;
      3     TYPE id_tbl IS TABLE OF number INDEX BY BINARY_INTEGER;
      4     l_ids  id_tbl;
      5     l_id2s id_tbl;
      6  BEGIN
      7     SELECT MAX(NVL(id2,0)) INTO l_v FROM t;
      8     SELECT id, ROW_NUMBER() OVER (ORDER BY id)
      9     BULK COLLECT INTO l_ids, l_id2s
    10     FROM t
    11     WHERE id2 IS NULL;
    12
    13     FORALL i IN 1 .. l_ids.COUNT
    14        UPDATE t
    15        SET id2 = l_id2s(i) + l_v
    16        WHERE id = l_ids(i);
    17     COMMIT;
    18  END;
    19  /
    Procedure created.
    SQL> SELECT * FROM t;
            ID        ID2
             1
             2
             5
             7So, id2 is going to be the gap-free column.
    SQL> exec fix_gap_free;
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t;
            ID        ID2
             1          1
             2          2
             5          3
             7          4So first pass is fine. Now lets add a few rows, so the table now looks like:
    SQL> SELECT * FROM t;
            ID        ID2
             1          1
             2          2
             5          3
             7          4
             8
             9
            25and generate more gap free number:
    SQL> exec fix_gap_free;
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t;
            ID        ID2
             1          1
             2          2
             5          3
             7          4
             8          5
             9          6
            25          7If there may be deletions in the table, and you need to maintain the gap free nature, then just skip the WHERE id2 IS NULL predicate.
    John

  • How to generate random filename?

    Hello! I have a programm that should create random tmp files in a directory also accessed by other clients. What is the best way to create a file with a unique name. I used System.currentTimeMilliseconds(), but I was told that it could make conflicts if other clients' time was not synchronized/wrong.

    Well, I guess I found the answer on forum. Question closed.

  • How to generate unique table row id's in a cfoutput query?

    I am trying to implement a jQuery drag and drop table row function to my CF pages but in order to save my "drop" positioning to the database I need to serialize all the table row id's.What coding would I need to add so that after the cfoutput query is run, each table row would have a unique id (ie. tr id="1", tr id="2", etc.)? Thanks.

    Utilize the CurrentRow variable that's automatically available within your query output:
    <cfoutput query="myQry">
              <tr id="row#currentRow#">
                        <td>...</td>
              </tr>
    </cfoutput>
    that will give you:
    <tr id="row1">
              <td>...</td>
    </tr>
    <tr id="row2">
              <td>...</td>
    </tr>
    <tr id="row3">
              <td>...</td>
    </tr>
    etc...

  • How to generate sepecific serial numbers?

    We want to generate specific serial number for item from paraemters, don't want to use the prefix or start number of item attribute.
    Serial Number should generated not associated with transactions. And Item attribute defined as "PRE-DEFINDED"
    And we do not want to insert basis table MTL_SERIAL_NUMBERS.
    We need API or Interface to do this.
    Is there anyone can help me?

    randy_ortan wrote:
    How to generate unique random numbers with out repetitions.The simplest way is to load the numbers 1 to 9 into an ArrayList. Then you use the Collections.shuffle method to shuffle the ArrayList numbers into random order. Finally you pick the 5 first numbers in the ArrayList. They will be unique and randomly picked from the 1 to 9 interval.
    If you want another 5 numbers you just reshuffle the ArrayList and pick the 5 first numbers again.

  • How to generate Serial(Unique) Number for finished goods?

    Guru's,
    How do i generate Serial(Unique) Numbers for finished goods.Suppose,if we get an order for a finished good A of 10 qty.We want to generate unique number to identify each and every A item separately for quality purpose.Any help is much appreciated.
    thanks Guru's

    Depending on serial control of item, you will need to generate serial numbers at the time of WIP Completion transaction using Serial Entry window (i.e. if serial control is At Receipt) or at the time of job creation (i.e. if you are using serial control as predefined)
    In latter case, you will have to use MES or MSCA screens to perform serialized WIP completion.
    Thanks,
    Hrishi

  • How to generate jasper report in pdf format using swing

    hi all,
    im new to swing and jasper.. can anybody provide me some example on how to generate the jasper report in pdf format? i will call the reportManager from sessionBean.. below is my code:
    1)delegate:
    public GenerateReportDto generateIntoPdfReport(String fileName, String outputFileName, Map parameters){
    GenerateReportDto generateReportDto = getAuditTrailServiceRemote().generateIntoPdfReport(fileName, outputFileName, parameters);
    return generateReportDto;
    2)sessionBean:
    public GenerateReportDto generateIntoPdfReport(String fileName, String outputFileName, Map parameters){
    //Map parameters = new HashMap();
    ReportManager reportManager = new ReportManager();
    3)ReportManager()
    public void generateIntoPdfReport(String fileName, String outputFileName, Map parameters) {
              Connection conn = null;
              try {
                   conn = dataSource.getConnection();
                   //Generate the report to bytes
                   File reportFile = new File(fileName);               
                   byte[] bytes =
                        JasperRunManager.runReportToPdf(
                             reportFile.getPath(),
                             parameters,
                             conn
              //conn.close();
              //Write the bytes to a file
              ByteBuffer buf = ByteBuffer.wrap(bytes);
              File file = new File(outputFileName);
              // (if the file exists)
              boolean append = false;
              // Create a writable file channel
              FileChannel wChannel = new FileOutputStream(file, append).getChannel();
              // Write the ByteBuffer contents; the bytes between the ByteBuffer's
              // position and the limit is written to the file
              wChannel.write(buf);
              // Close the file
              wChannel.close();
              } finally {
                   if (conn != null) {
    conn.close();
    Any help would be highly appreciated. Thanks in advance

    Hi ,
    One 'simple' way is by using the DBMS_SCHEDULER db package and the procedure CREATE_JOB(....) using as job_type the value 'EXECUTABLE'...
    Read for further info in 'PL/SQL Packages and Types Reference'.
    If you have access to OEM ... you can configure this there using wizard.....
    Other way is to use the External Procedure call capabiblity of Oracle DB Server...:
    http://www.oracle.com/pls/db102/ranked?word=external+procedure+call&remark=federated_search
    My greetings,
    Sim

Maybe you are looking for