Example usage for org.hibernate Session persist

List of usage examples for org.hibernate Session persist

Introduction

In this page you can find the example usage for org.hibernate Session persist.

Prototype

void persist(Object object);

Source Link

Document

Make a transient instance persistent.

Usage

From source file:ctd.services.getCleanData2.java

License:Apache License

public String cleanData() {
    String message = "";
    String timestamp = new java.util.Date().getTime() + "";

    try {//from  w ww .  j av a  2  s .  c om
        CleanDataResult result = new CleanDataResult();
        String error_message = "";
        //get parameters.
        ResourceBundle res = ResourceBundle.getBundle("settings");
        ResourceBundle cdf_list = ResourceBundle.getBundle("cdf");
        //Base directory ftp folder: Here the temporary subfolders are found for each set of CEL-files, and the final assaytoken-based folder.
        String ftp_folder = res.getString("ws.upload_folder");
        String rscript_cleandata = res.getString("ws.rscript_cleandata");
        String rscript = res.getString("ws.rscript");
        //db
        String db_username = res.getString("db.username");
        String db_password = res.getString("db.password");
        String db_database = res.getString("db.database");

        //retrieve the information on the assignment from the database
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tr = session.beginTransaction();
        Query q = session.createQuery(
                "from Ticket where password='" + getPassword() + "' AND ctd_REF='" + getCTD_REF() + "'");
        Ticket ticket = null;
        String closed = "";
        if (q.list().size() != 0) {
            ticket = (Ticket) q.list().get(0);
            closed = ticket.getClosed();
        }
        if (ticket == null) {
            error_message = "Ticket password and CTD_REF don't match.";
        }
        if (closed.equals("yes")) {
            error_message = "Ticket is already used for normalization of these CEL-files.";
            ticket = null;
        }

        if (ticket != null) {
            //get the folder
            String folder = ticket.getFolder();
            String zip_folder = ftp_folder + folder;
            //get contents
            File dir = new File(zip_folder);

            //find the zip file.
            File[] files = dir.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return pathname.isFile();
                }
            });
            String cel_zip_file = "";
            String zip_file = "";
            String gct_file = "";
            for (int i = 0; i < files.length; i++) {
                String file = files[i].getName();
                if (file.contains("zip")) {
                    // Add the timestamp to the zip
                    files[i].renameTo(new File(zip_folder + "/" + timestamp + "_zip.zip"));
                    file = timestamp + "_zip.zip";

                    cel_zip_file = file;
                    zip_file = zip_folder + "/" + cel_zip_file;
                    gct_file = zip_folder + "/" + timestamp + "_gctfile";
                }
            }
            Process p3 = Runtime.getRuntime().exec("chmod 777 " + zip_file);

            //////////////////////////////////////////////////////////////////
            //Do a system call to normalize. R. (zip_folder zip_file gct_file rscript)
            String args = rscript + " --verbose --vanilla " + rscript_cleandata + " -i" + zip_file + " -o"
                    + gct_file + " -w" + zip_folder;
            Logger.getLogger(getTicket.class.getName()).log(Level.INFO, timestamp + ": Running: " + args);
            Process p = Runtime.getRuntime().exec(args);
            // Check if CEL files are unzipped allready
            // This is done by checking every 5 seconds for the existence of a .chip file
            // This is a bad way of doing this, in future versions of CTD
            // the output of the R scripts should be parsed
            boolean do_loop = true;
            while (do_loop) {
                File dir2 = new File(zip_folder);
                String[] files2 = dir2.list();
                //Check if CEL files are allready there
                for (int i = 0; i < files2.length; i++) {
                    String file = files2[i];
                    if (file.endsWith("chip")) {
                        do_loop = false;
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(getCleanData.class.getName()).log(Level.SEVERE, null,
                                    timestamp + ": " + ex);
                        }
                    }
                }
            }
            Logger.getLogger(getTicket.class.getName()).log(Level.INFO, timestamp + ": rscript has finished.");
            File dir2 = new File(zip_folder);
            String[] files2 = dir2.list();
            String chip_file = "";
            String chip_file_db = "";
            ArrayList<String> unziped_files = new ArrayList<String>();
            for (int i = 0; i < files2.length; i++) {
                String file = files2[i];
                if (file.endsWith("CEL")) {
                    unziped_files.add(file);
                }
                if (file.endsWith("chip")) {
                    chip_file = file;
                    chip_file_db = chip_file.split("_CDF_")[1];
                    File fileFile = new File(chip_file);
                    fileFile.renameTo(new File(zip_folder + "/" + chip_file_db)); //Making the file correspond to the database entry. Duplicates can be safely overwritten, and will be.
                }
            }

            //Check if all CEL files are derived from the same chip.
            //This is essential for normalization.
            //initiate check hashmap. This map contains all the unique chip definition file names. There should be only one per analysis.
            ArrayList<StudySampleAssay> map = new ArrayList<StudySampleAssay>();
            for (int i = 0; i < unziped_files.size(); i++) {
                String cel_file = unziped_files.get(i);

                StudySampleAssay ssa = new StudySampleAssay();
                // Open the file that is the first
                // command line parameter
                //String cel_file_path = zip_folder + "/" + cel_file;
                String name = cel_file;
                ssa.setNameRawfile(name);
                ssa.setXREF(getCTD_REF());
                map.add(ssa);
            }
            ticket.getStudySampleAssaies().addAll(map);
            session.saveOrUpdate(ticket);
            session.persist(ticket);
            tr.commit();
            session.close();

            //Storage chip definition file (CDF), creation gct file and database storage.
            SessionFactory sessionFactory1 = new Configuration().configure().buildSessionFactory();
            Session session1 = sessionFactory1.openSession();

            //check if cdf (chip definition file) is allready stored, if not, store it.
            List<ChipAnnotation> chip_annotation = null;
            Query q2 = session1.createQuery("from Chip Where Name='" + chip_file_db + "'");
            if (q2.uniqueResult() != null) {
                Chip chip = (Chip) q2.list().get(0);
                chip_annotation = chip.getChipAnnotation();
            }
            if (q2.uniqueResult() == null) {
                //Add this chip and its annotation
                Chip chip_new = new Chip();
                chip_new.setName(chip_file_db);

                //read chip file
                String chip_file_path = zip_folder + "/" + chip_file;
                chip_annotation = readChip(chip_file_path);

                //Store the whole
                chip_new.getChipAnnotation().addAll(chip_annotation);

                Transaction tr1 = session1.beginTransaction();
                session1.save(chip_new);
                session1.persist(chip_new);
                tr1.commit();
                session1.close();
            }

            //create the temp file for storage of the data_insert file.
            String data_file = zip_folder + "/expression.txt";
            FileOutputStream out = null;
            PrintStream pr = null;
            out = new FileOutputStream(data_file);
            pr = new PrintStream(out);

            //create array data input file for the database table, find correct foreign keys.
            //get the study_sample_assay id and the probeset ids.
            SessionFactory sessionFactory2 = new Configuration().configure().buildSessionFactory();
            Session session2 = sessionFactory2.openSession();

            //Get the cip_annotation_id
            Query q3 = session2.createQuery("from Chip Where Name='" + chip_file_db + "'");
            Chip chip = (Chip) q3.list().get(0);
            chip_annotation = chip.getChipAnnotation();
            Iterator it2 = chip_annotation.iterator();
            //for speed, put the chip annotation id in a hashmap
            HashMap<String, String> chip_annotation_ids = new HashMap<String, String>();
            while (it2.hasNext()) {
                ChipAnnotation ca = (ChipAnnotation) it2.next();
                String id = ca.getId().toString();
                String ps = ca.getProbeset();
                chip_annotation_ids.put(ps, id);
            }

            //Create the .gct-files
            try {

                Query qt = session2.createQuery("from Ticket where password='" + getPassword()
                        + "' AND ctd_REF='" + getCTD_REF() + "'");

                ticket = null;

                if (qt.list().size() != 0) {
                    ticket = (Ticket) qt.list().get(0);
                }

                Iterator it3 = ticket.getStudySampleAssaies().iterator();
                while (it3.hasNext()) {
                    StudySampleAssay ssa = (StudySampleAssay) it3.next();
                    String name_raw_file = ssa.getNameRawfile();
                    String sampleToken = getSampletokens().get(name_raw_file);
                    String ssa_id = ssa.getId().toString();
                    error_message = error_message + name_raw_file;

                    String gct_file_generated = gct_file + ".gct";
                    ArrayList<Double> values = writeFile(pr, chip_annotation_ids, ssa_id, gct_file_generated,
                            name_raw_file.replaceAll(".CEL", ""));

                    Statistics stat = new Statistics();
                    stat.setData(values);
                    Double average = stat.getAverage();
                    Double std = stat.getSTD();

                    ssa.setXREF(getCTD_REF());
                    ssa.setAverage(average);
                    ssa.setStudyToken(getStudytoken());
                    ssa.setSampleToken(sampleToken);
                    ssa.setStd(std);
                }

            } catch (IOException e) {
                Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, timestamp
                        + ": ERROR IN getCleanData2: " + e.getMessage() + "  " + e.getLocalizedMessage());
            }
            pr.close();
            out.close();

            //update ticket
            Transaction tr2 = session2.beginTransaction();
            session2.update(ticket);
            session2.persist(ticket);
            tr2.commit();
            session2.close();

            //import the data into the database
            String u = "--user=" + db_username;
            String passw = "--password=" + db_password;
            String[] commands = new String[] { "mysqlimport", u, passw, "--local", db_database, data_file };
            Process p4 = Runtime.getRuntime().exec(commands);
            message = message + " RMA and GRSN on the CEL-files is done, data is stored.";

            //close the ticket when finished, normalization can only be performed once by the client.
            CloseTicket();

            //Remove zip and data file (expression.txt)
            File fileFolderOld = new File(zip_folder);
            File fileFolderDest = new File(res.getString("ws.upload_folder") + getCTD_REF());
            File[] listOfFiles = fileFolderOld.listFiles();
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].getPath().toLowerCase().endsWith(".zip")
                        || listOfFiles[i].getPath().toLowerCase().endsWith("expression.txt")) {
                    try {
                        listOfFiles[i].delete();
                    } catch (Exception e) {
                        Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE,
                                timestamp + ": ERROR IN getCleanData2 (try to delete): " + e.toString());
                    }
                } else {
                    try {
                        FileUtils.copyFileToDirectory(listOfFiles[i], fileFolderDest, false);
                        listOfFiles[i].delete();
                    } catch (Exception e) {
                        Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE,
                                timestamp + ": ERROR IN getCleanData2 (try to copy): " + e.toString());
                    }
                }
            }

            // Remove temporary folder
            try {
                fileFolderOld.delete();
            } catch (Exception e) {
                Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE,
                        timestamp + ": ERROR IN getCleanData2: " + e.toString());
            }

            // --------------------------------------------
            // This piece of code is added in order to cleanup all the files
            // of aborted upload procedures. It checks for these old folders
            // (more than a day old and a temporaty name (which is just a number
            // from 1 upwards. It is assumed that a temporary folder has a
            // name shorter than 10 chars) and removes these files and folders
            File folderData = new File(res.getString("ws.upload_folder"));
            long lngTimestamp = new java.util.Date().getTime();
            listOfFiles = folderData.listFiles();
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].lastModified() < (lngTimestamp - 10000)
                        && listOfFiles[i].getName().length() < 10) {
                    // This folder is more than a day old
                    // We know it is a temporary folder because the name is less than 10 chars long
                    File[] lstDelete = listOfFiles[i].listFiles();
                    for (int j = 0; j < lstDelete.length; j++) {
                        // Delete all content of the old folder
                        lstDelete[j].delete();
                    }
                    // Delete the old folder
                    if (!listOfFiles[i].delete()) {
                        Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE,
                                "delSample(): Folder deletion failed: " + listOfFiles[i].getName());
                    }
                }
            }
            // --------------------------------------------
        }

        // set the messages of the response
        result.setErrorMessage(error_message);
        result.setMessage(message);

        // Use SKARINGA in order to create the JSON response
        ObjectTransformer trans = null;
        try {
            trans = ObjectTransformerFactory.getInstance().getImplementation();
            message = trans.serializeToString(result);
        } catch (NoImplementationException ex) {
            Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE,
                    "SKARINGA ERROR IN getCleanData2: " + ex.getLocalizedMessage());
        }

    } catch (Exception e) {
        Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE,
                timestamp + ": ERROR IN getCleanData2: " + e.toString());
    }
    return message;
}

From source file:ctd.services.getJsonCleanData.java

License:Apache License

public String cleanData() throws IOException, NoImplementationException, SerializerException {

    CleanDataResult result = new CleanDataResult();

    String message = "";
    String error_message = "";
    //get parameters.
    ResourceBundle res = ResourceBundle.getBundle("settings");
    ResourceBundle cdf_list = ResourceBundle.getBundle("cdf");

    //Base directory ftp folder: Here the subfolders are found for each set of CEL-files.
    String ftp_folder = res.getString("ws.ftp_folder");
    String owner = res.getString("ws.owner");
    String group = res.getString("ws.group");
    String rscript_cleandata = res.getString("ws.rscript_cleandata");
    String rscript = res.getString("ws.rscript");
    //db//  w  ww.j a  v a  2 s . c o m
    String db_username = res.getString("db.username");
    String db_password = res.getString("db.password");
    String db_database = res.getString("db.database");

    //open hibernate connection
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    Transaction tr = session.beginTransaction();

    Query q = session.createQuery("from Ticket where password='" + getTicketPassword() + "'");

    Ticket ticket = null;
    String closed = "";
    if (q.list().size() != 0) {
        ticket = (Ticket) q.list().get(0);
        closed = ticket.getClosed();
    }
    if (ticket == null) {
        error_message = "Ticket password and CTD_REF don't match.";
    }
    if (closed.equals("yes")) {
        error_message = "Ticket is allready used for normalization of these CEL-files.";
        ticket = null;
    }
    if (ticket != null) {
        //get the folder
        String folder = ticket.getFolder();
        //create subfolder containing the derived zip file
        String zip_folder = ftp_folder + folder;
        //get content
        File dir = new File(zip_folder);
        String[] files = dir.list();
        //find the zip file.
        String cel_zip_file = "";
        String zip_file = "";
        String gct_file = "";

        for (int i = 0; i < files.length; i++) {
            String file = files[i];
            if (file.contains("zip")) {
                cel_zip_file = file;
                zip_file = zip_folder + "/" + cel_zip_file;
                gct_file = zip_folder + "/gctfile_" + folder;
            }
        }
        Process p3_0 = Runtime.getRuntime().exec("chmod 040 " + zip_file);
        Process p3_1 = Runtime.getRuntime().exec("chown robertk.ctd " + zip_file);

        //////////////////////////////////////////////////////////////////
        //Do a system call to normalize. R. (zip_folder zip_file gct_file rscript)
        String args = rscript + " --vanilla " + rscript_cleandata + " -i" + zip_file + " -o" + gct_file + " -w"
                + zip_folder;
        Process p = Runtime.getRuntime().exec(args);

        //Check if CEL files are unzipped allready
        boolean do_loop = true;
        while (do_loop) {
            File dir2 = new File(zip_folder);
            String[] files2 = dir2.list();
            //Check if Job is allready done, if gct-file is there.
            for (int i = 0; i < files2.length; i++) {
                String file = files2[i];
                if (file.endsWith("gct")) {
                    do_loop = false;
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(getCleanData.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }

        File dir2 = new File(zip_folder);
        String[] files2 = dir2.list();
        String chip_file = "";
        String chip_file_db = "";
        ArrayList<String> unziped_files = new ArrayList<String>();
        for (int i = 0; i < files2.length; i++) {
            String file = files2[i];
            if (file.endsWith("CEL")) {
                unziped_files.add(file);
            }
            if (file.endsWith("chip")) {
                chip_file = file;

                chip_file_db = chip_file.split("_CDF_")[1];
            }
        }

        //Check if all CEL files are derived from the same chip.
        //This is essential for normalization.
        //initiate check hashmap. This map contains all the unique chip definition file names. There should be only one per analysis.

        ArrayList<StudySampleAssay> map = new ArrayList<StudySampleAssay>();

        for (int i = 0; i < unziped_files.size(); i++) {
            String cel_file = unziped_files.get(i);

            StudySampleAssay ssa = new StudySampleAssay();
            // Open the file that is the first
            // command line parameter
            String cel_file_path = zip_folder + "/" + cel_file;
            String name = cel_file.replaceAll(".CEL", "");
            ssa.setNameRawfile(name);
            ssa.setXREF(name);
            map.add(ssa);

            String command = "rm " + cel_file_path;
            Process pr = Runtime.getRuntime().exec(command);

        }

        ticket.getStudySampleAssaies().addAll(map);
        session.saveOrUpdate(ticket);
        session.persist(ticket);
        tr.commit();
        session.close();

        //Storage chip definition file (CDF), creation gct file and database storage.
        SessionFactory sessionFactory1 = new Configuration().configure().buildSessionFactory();
        Session session1 = sessionFactory1.openSession();

        List<ChipAnnotation> chip_annotation = null;

        //check if cdf (chip definition file) is allready stored, if not, store it.

        Query q2 = session1.createQuery("from Chip Where Name='" + chip_file_db + "'");
        if (q2.uniqueResult() != null) {
            Chip chip = (Chip) q2.list().get(0);
            chip_annotation = chip.getChipAnnotation();
        }

        if (q2.uniqueResult() == null) {
            //Add this chip and its annotation
            Chip chip_new = new Chip();
            chip_new.setName(chip_file_db);

            //read chip file
            String chip_file_path = zip_folder + "/" + chip_file;
            chip_annotation = readChip(chip_file_path);

            //Store the whole
            chip_new.getChipAnnotation().addAll(chip_annotation);

            Transaction tr1 = session1.beginTransaction();
            session1.save(chip_new);
            session1.persist(chip_new);
            tr1.commit();
            session1.close();
        }

        //create the temp file for storage of the data_insert file.
        String data_file = zip_folder + "/expression.txt";
        FileOutputStream out = null;
        PrintStream pr = null;
        out = new FileOutputStream(data_file);
        pr = new PrintStream(out);

        //create array data input file for the database table, find correct foreign keys.
        //get the study_sample_assay id and the probeset ids.
        SessionFactory sessionFactory2 = new Configuration().configure().buildSessionFactory();
        Session session2 = sessionFactory2.openSession();

        //Get the cip_annotation_id
        Query q3 = session2.createQuery("from Chip Where Name='" + chip_file_db + "'");
        Chip chip = (Chip) q3.list().get(0);
        chip_annotation = chip.getChipAnnotation();
        Iterator it2 = chip_annotation.iterator();
        //for speed, put the chip annotation id in a hashmap
        HashMap<String, String> chip_annotation_ids = new HashMap<String, String>();
        while (it2.hasNext()) {
            ChipAnnotation ca = (ChipAnnotation) it2.next();
            String id = ca.getId().toString();
            String ps = ca.getProbeset();
            chip_annotation_ids.put(ps, id);
        }

        try {

            Query qt = session2.createQuery("from Ticket where password='" + getTicketPassword() + "'");

            ticket = null;

            if (qt.list().size() != 0) {
                ticket = (Ticket) qt.list().get(0);
            }

            Iterator it3 = ticket.getStudySampleAssaies().iterator();
            while (it3.hasNext()) {
                StudySampleAssay ssa = (StudySampleAssay) it3.next();
                String name_raw_file = ssa.getNameRawfile();
                String ssa_id = ssa.getId().toString();
                error_message = error_message + name_raw_file;

                String gct_file_generated = gct_file + ".gct";
                ArrayList<Double> values = writeFile(pr, chip_annotation_ids, ssa_id, gct_file_generated,
                        name_raw_file);

                Statistics stat = new Statistics();
                stat.setData(values);
                Double average = stat.getAverage();
                Double std = stat.getSTD();

                ssa.setXREF(name_raw_file);
                ssa.setAverage(average);
                ssa.setStd(std);
            }

        } catch (IOException e) {
        }
        pr.close();
        out.close();

        Transaction tr2 = session2.beginTransaction();
        session2.update(ticket);
        session2.persist(ticket);
        tr2.commit();

        session2.close();

        String u = "--user=" + db_username;
        String passw = "--password=" + db_password;
        String[] commands = new String[] { "mysqlimport", u, passw, "--local", db_database, data_file };

        Process p4 = Runtime.getRuntime().exec(commands);

        message = message + " RMA and GRSN on the CEL-files is done, data is stored.";
        //close the ticket when finished, normalization can only be performed once by the client.
        CloseTicket();

        //remove data_file
        Process p5 = Runtime.getRuntime().exec("rm -f " + data_file);

        //set permissions folder
        String command1 = "chmod 500 " + zip_folder;
        String command1_1 = "chmod +t " + zip_folder;

        Process p4_0_1 = Runtime.getRuntime().exec(command1_1);
        Process p4_0 = Runtime.getRuntime().exec(command1);

        //set permissions gct-file
        String command2 = "chmod 040 " + gct_file + ".gct";
        String command3 = "chown " + owner + " " + gct_file + ".gct";
        String command4 = "chgrp " + group + " " + gct_file + ".gct";

        Process p4_1 = Runtime.getRuntime().exec(command2);
        Process p4_2 = Runtime.getRuntime().exec(command3);
        Process p4_3 = Runtime.getRuntime().exec(command4);
    }

    ////////////////////
    //SKARINGA
    result.setErrorMessage(error_message);

    result.setMessage(message);
    ObjectTransformer trans = null;
    try {
        trans = ObjectTransformerFactory.getInstance().getImplementation();
    } catch (NoImplementationException ex) {
        Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, null, ex);
    }
    message = trans.serializeToJsonString(result);
    return message;
}

From source file:ctd.services.getJsonCleanData.java

License:Apache License

private void CloseTicket() {

    //open hibernate connection
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();

    Query q = session.createQuery("from Ticket where password='" + getTicketPassword() + "'");

    Ticket ticket = null;//from   ww  w.  ja v  a2s  .com

    if (q.list().size() != 0) {
        ticket = (Ticket) q.list().get(0);
        ticket.setClosed("yes");
    }

    Transaction tr = session.beginTransaction();
    session.saveOrUpdate(ticket);
    session.persist(ticket);
    tr.commit();
    session.close();

}

From source file:ctd.services.getJsonTicket.java

License:Apache License

public String getTicket() throws SerializerException {

    //init parameters
    ResourceBundle res = ResourceBundle.getBundle("settings");

    String webservice_password = res.getString("ws.password");

    String ftp_folder = res.getString("ws.ftp_folder");
    String prefix_ctd_reference = res.getString("ws.prefix_ticket_reference");
    String prefix_ftp_subfolder = res.getString("ws.prefix_ftp_subfolders");
    String ftp_username = res.getString("ws.ftp_username");
    String group = res.getString("ws.group");
    String hostname = res.getString("ws.hostname");

    TicketClient ticket_client = new TicketClient();
    String new_folder = "";
    String message = "";

    String password_client = getWsPassword();

    if (webservice_password.equals(password_client)) {
        //open hibernate connection
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tr = session.beginTransaction();

        Integer id = 1;/*from  w ww.ja va 2 s  . c o  m*/
        SQLQuery q1 = session.createSQLQuery("Select MAX(id) FROM ticket");
        Iterator it1 = q1.list().iterator();
        while (it1.hasNext()) {
            id = (Integer) it1.next();
            if (id != null) {
                id++;
            }
            if (id == null) {
                id = 1;
            }
        }

        ///Get unique password for processing the submitted celfiles
        UUID uuid = null;

        ///check if this uuid is not allready used in this database
        Boolean check = true;
        while (check) {
            uuid = UUID.randomUUID();
            Query q2 = session.createQuery("from Ticket where password='" + uuid.toString() + "'");
            if (q2.list().isEmpty()) {
                check = false;
            }
        }

        //String db_password = password_client+"_"+webservice_password;//uuid.toString();
        String db_password = uuid.toString();
        //ctd reference id
        String ctd_ref = prefix_ctd_reference + String.valueOf(id);
        //ctd ftp subfolder
        String ctd_ftp_folder = prefix_ftp_subfolder + String.valueOf(id);

        //create subdir
        new_folder = ftp_folder + ctd_ftp_folder;
        boolean success = (new File(new_folder)).mkdir();
        //change owner from root to cleandata for this new directory

        //Adjust permissions
        String command1 = "chown " + ftp_username + " " + new_folder;
        String command4 = "chgrp " + group + " " + new_folder;
        String command2 = "chmod 700 " + new_folder;
        String command3 = "chmod +t " + new_folder;

        Process child;
        try {
            child = Runtime.getRuntime().exec(command1);
            child = Runtime.getRuntime().exec(command4);
            child = Runtime.getRuntime().exec(command2);
            child = Runtime.getRuntime().exec(command3);
        } catch (IOException ex) {
            Logger.getLogger(getJsonTicket.class.getName()).log(Level.SEVERE, null, ex);
        }

        //location ftp folder
        String link = "sftp://" + ftp_username + "@" + hostname + ":" + new_folder + "/";
        ticket_client.setLocationFTPFolder(link);

        Ticket ticket = new Ticket();
        ticket.setFolder(ctd_ftp_folder);
        ticket.setPassword(db_password);
        ticket.setCtdRef(ctd_ref);
        ticket.setClosed("no");

        ticket_client.setCtdRef(ctd_ref);
        ticket_client.setFolder(ctd_ftp_folder);
        ticket_client.setPassword(db_password);

        session.save(ticket);
        session.persist(ticket);
        tr.commit();

        session.close();
        sessionFactory.close();
        session = null;
        sessionFactory = null;
    }

    ////////////////////
    //SKARINGA
    ObjectTransformer trans = null;
    try {
        trans = ObjectTransformerFactory.getInstance().getImplementation();
    } catch (NoImplementationException ex) {
        Logger.getLogger(getJsonTicket.class.getName()).log(Level.SEVERE, null, ex);
    }
    message = trans.serializeToJsonString(ticket_client);

    return message;
}

From source file:ctd.services.getTicket.java

License:Apache License

public String getTicket() throws SerializerException {

    //init parameters
    ResourceBundle res = ResourceBundle.getBundle("settings");

    String webservice_password = res.getString("ws.password");

    String ftp_folder = res.getString("ws.ftp_folder");
    String prefix_ctd_reference = res.getString("ws.prefix_ticket_reference");
    String prefix_ftp_subfolder = res.getString("ws.prefix_ftp_subfolders");

    TicketClient ticket_client = new TicketClient();
    String new_folder = "";
    String message = "";

    String password_client = getPassword();

    if (webservice_password.equals(password_client)) {
        //open hibernate connection
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tr = session.beginTransaction();

        Integer id = 1;//from w ww .jav  a 2 s  .  c om
        SQLQuery q1 = session.createSQLQuery("Select MAX(id) FROM ticket");
        Iterator it1 = q1.list().iterator();
        while (it1.hasNext()) {
            id = (Integer) it1.next();
            if (id != null) {
                id++;
            }
            if (id == null) {
                id = 1;
            }
        }

        ///Get unique password for processing the submitted celfiles
        UUID uuid = null;

        ///check if this uuid is not allready used in this database
        Boolean check = true;
        while (check) {
            uuid = UUID.randomUUID();
            Query q2 = session.createQuery("from Ticket where password='" + uuid.toString() + "'");
            if (q2.list().isEmpty()) {
                check = false;
            }
        }

        //String db_password = password_client+"_"+webservice_password;//uuid.toString();
        String db_password = uuid.toString();
        //ctd reference id
        String ctd_ref = prefix_ctd_reference + String.valueOf(id);
        //ctd ftp subfolder
        String ctd_ftp_folder = prefix_ftp_subfolder + String.valueOf(id);

        //create subdir
        new_folder = ftp_folder + ctd_ftp_folder;
        boolean success = (new File(new_folder)).mkdir();
        //change owner from root to cleandata for this new directory

        //Adjust permissions
        String command1 = "chown cleandata " + new_folder;
        String command2 = "chgrp cleandata " + new_folder;
        String command3 = "chmod 777 " + new_folder;
        String command4 = "chmod +t " + new_folder;
        Process child;
        try {
            child = Runtime.getRuntime().exec(command1);
            child = Runtime.getRuntime().exec(command2);
            child = Runtime.getRuntime().exec(command3);
            child = Runtime.getRuntime().exec(command4);
        } catch (IOException ex) {
            Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, null, ex);
        }

        Ticket ticket = new Ticket();
        ticket.setFolder(ctd_ftp_folder);
        ticket.setPassword(db_password);
        ticket.setCtdRef(ctd_ref);
        ticket.setClosed("no");

        ticket_client.setCtdRef(ctd_ref);
        ticket_client.setFolder(ctd_ftp_folder);
        ticket_client.setPassword(db_password);

        session.save(ticket);
        session.persist(ticket);
        tr.commit();

        session.close();
        sessionFactory.close();
        session = null;
        sessionFactory = null;
    }

    ////////////////////
    //SKARINGA
    ObjectTransformer trans = null;
    try {
        trans = ObjectTransformerFactory.getInstance().getImplementation();
    } catch (NoImplementationException ex) {
        Logger.getLogger(getTicket.class.getName()).log(Level.SEVERE, null, ex);
    }
    message = trans.serializeToJsonString(ticket_client);

    return message;
}

From source file:cz.uhk.fim.kulhama1.skolniprojectchaty.dao.AddressDAO.java

public Address addAddress(Address address) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(address);
    return address;
}

From source file:DAL.DACursist.java

public static void AddCursist(Cursist cursist) {
    Session session = HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();/*from  w w  w.  ja  v a  2 s .c o  m*/
    session.persist(cursist);
    session.getTransaction().commit();
}

From source file:Dao.AccountDAO.java

public void addAccount(Account u) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(u);
    logger.info("Account saved successfully, Account Details=" + u);
}

From source file:Dao.AccountTypeDAO.java

public void addAccountType(AccountType u) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(u);
    logger.info("AccountType saved successfully, AccountType Details=" + u);
}

From source file:Dao.ActorDAO.java

public void addActor(Actor u) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(u);
    logger.info("Actor saved successfully, Actor Details=" + u);
}