Example usage for java.lang InterruptedException getLocalizedMessage

List of usage examples for java.lang InterruptedException getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang InterruptedException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:se.trixon.filebydate.Operation.java

public void start() {
    long startTime = System.currentTimeMillis();

    Date date = new Date(startTime);
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    mListener.onOperationStarted();/*from w w  w .  j a v  a 2 s.  c  om*/
    mListener.onOperationProcessingStarted();
    mListener.onOperationLog(dateFormat.format(date));

    mInterrupted = !generateFileList();
    String status;

    if (!mInterrupted && !mFiles.isEmpty()) {
        mListener.onOperationLog(String.format(mBundle.getString("found_count"), mFiles.size()));
        mListener.onOperationLog("");
        status = Dict.PROCESSING.toString();
        mListener.onOperationLog(status);

        int progress = 0;
        SimpleDateFormat simpleDateFormat = mProfile.getDateFormat();
        for (File sourceFile : mFiles) {
            try {
                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException ex) {
                    mInterrupted = true;
                    break;
                }

                String fileDate = simpleDateFormat.format(getDate(sourceFile));
                File destDir = new File(mProfile.getDestDir(), fileDate);

                if (destDir.isFile()) {
                    mListener.onOperationLog(String.format(Dict.Dialog.ERROR_DEST_DIR_IS_FILE.toString(),
                            destDir.getAbsolutePath()));
                    break;
                } else if (!destDir.exists() && !mProfile.isDryRun()) {
                    FileUtils.forceMkdir(destDir);
                }

                String destFilename = sourceFile.getName();
                String base = FilenameUtils.getBaseName(destFilename);
                String ext = FilenameUtils.getExtension(destFilename);
                NameCase caseBase = mProfile.getCaseBase();
                NameCase caseExt = mProfile.getCaseExt();

                if (caseBase != NameCase.UNCHANGED || caseExt != NameCase.UNCHANGED) {
                    if (caseBase == NameCase.LOWER) {
                        base = base.toLowerCase();
                    } else if (caseBase == NameCase.UPPER) {
                        base = base.toUpperCase();
                    }

                    if (caseExt == NameCase.LOWER) {
                        ext = ext.toLowerCase();
                    } else if (caseBase == NameCase.UPPER) {
                        ext = ext.toUpperCase();
                    }

                    if (base.length() == 0) {
                        destFilename = String.format(".%s", ext);
                    } else if (ext.length() == 0) {
                        destFilename = base;
                    } else {
                        destFilename = String.format("%s.%s", base, ext);
                    }
                }

                File destFile = new File(destDir, destFilename);
                String log;
                if (destFile.exists() && !mProfile.isReplaceExisting()) {
                    log = String.format(Dict.Dialog.ERROR_DEST_FILE_EXISTS.toString(),
                            destFile.getAbsolutePath());
                } else {
                    Command command = mProfile.getCommand();
                    String cmd = command == Command.COPY ? "cp" : "mv";
                    log = String.format("%s %s  %s", cmd, sourceFile.getAbsolutePath(), destFile.toString());

                    if (destDir.canWrite()) {
                        if (!mProfile.isDryRun()) {
                            if (command == Command.COPY) {
                                FileUtils.copyFile(sourceFile, destFile);
                            } else if (command == Command.MOVE) {
                                if (File.listRoots().length > 1 || destFile.exists()) {
                                    FileUtils.copyFile(sourceFile, destFile);
                                    FileUtils.deleteQuietly(sourceFile);
                                } else {
                                    FileUtils.moveFile(sourceFile, destFile);
                                }
                            }
                        }
                    } else if (!mProfile.isDryRun()) {
                        log = Dict.Dialog.ERROR_DEST_CANT_WRITE.toString();
                    }
                }

                mListener.onOperationLog(getMessage(log));
            } catch (IOException | ImageProcessingException | NullPointerException ex) {
                mListener.onOperationLog(getMessage(ex.getLocalizedMessage()));
            }
            mListener.onOperationProgress(++progress, mFiles.size());
        }
    }

    if (mInterrupted) {
        status = Dict.TASK_ABORTED.toString();
        mListener.onOperationLog("\n" + status);
        mListener.onOperationInterrupted();
    } else {
        mExceptions.stream().forEach((exception) -> {
            mListener.onOperationLog(String.format("#%s", exception.getLocalizedMessage()));
        });
        long millis = System.currentTimeMillis() - startTime;
        long min = TimeUnit.MILLISECONDS.toMinutes(millis);
        long sec = TimeUnit.MILLISECONDS.toSeconds(millis)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
        status = String.format("%s (%d %s, %d %s)", Dict.TASK_COMPLETED.toString(), min,
                Dict.TIME_MIN.toString(), sec, Dict.TIME_SEC.toString());
        mListener.onOperationFinished(status, mFiles.size());

        if (!mProfile.isDryRun()) {
            mProfile.setLastRun(System.currentTimeMillis());
            try {
                ProfileManager.getInstance().save();
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.piketec.jenkins.plugins.tpt.TptPluginSlaveExecutor.java

/**
 * Executes a small chunks of tests. It binds to the Tpt Api , check if the given Execution
 * Configuration exists. Prepares the test- and data-directories. Creates a temporary testSet from
 * the chunk of test (if no testSet is given). Then through the tpt api executes the testCases and
 * then it copies the results to the master workspace.
 * /*from   www  .  j  a  v a 2s.  c  om*/
 * @return true if the tpt execution has been successfully.
 */
public boolean execute() {
    logger = new TptLogger(listener.getLogger());
    try {
        // start tpt and recieve API
        TptApi api;
        try {
            api = Utils.getTptApi(build, launcher, logger, exePaths, tptPort, tptBindingName,
                    tptStartupWaitTime);
        } catch (InterruptedException e) {
            logger.interrupt(e.getMessage());
            return false;
        }
        if (api == null) {
            return false;
        }
        // open TPT File
        OpenResult openProject = api.openProject(tptFile);
        if (openProject.getProject() == null) {
            logger.error("Could not open project:\n" + Utils.toString(openProject.getLogs(), "\n"));
            return false;
        }
        new CleanUpTask(openProject.getProject(), masterId);
        // search execution configuration by name
        Collection<ExecutionConfiguration> execConfigs = openProject.getProject().getExecutionConfigurations()
                .getItems();
        ExecutionConfiguration config = null;
        for (ExecutionConfiguration elem : execConfigs) {
            if (elem.getName().equals(execCfg)) {
                config = elem;
                break;
            }
        }
        if (config == null) {
            logger.error("Could not find config");
            return false;
        }
        // adjust config to execute only the given one test case
        File oldReportDir = config.getReportDir();
        File oldTestDataDir = config.getDataDir();

        Collection<Scenario> foundScenearios = new HashSet<>();
        find(openProject.getProject().getTopLevelTestlet().getTopLevelScenarioOrGroup().getItems(),
                testSetString, foundScenearios);
        if (foundScenearios.size() != testSetString.size()) {
            logger.error("Could only find " + foundScenearios.size() + " of " + testSetString.size() + ".");
            return false;
        }

        FilePath slaveDataDir = null;
        FilePath slaveReportDir = null;
        try {
            slaveDataDir = new FilePath(build.getWorkspace(), testDataDir).absolutize();
            if (!masterWorkspace.equals(build.getWorkspace())) {
                logger.info("Creating and/or cleaning test data directory");
                Utils.deleteFiles(slaveDataDir);
            }
        } catch (IOException e) {
            logger.error("Could not create or clear test data dir");
            return false;
        } catch (InterruptedException e) {
            logger.interrupt(e.getMessage());
            return false;
        }
        logger.info("Setting test data directory to " + slaveDataDir.getRemote());
        config.setDataDir(new File(slaveDataDir.getRemote()));

        try {
            slaveReportDir = new FilePath(build.getWorkspace(), reportDir).absolutize();
            if (!masterWorkspace.equals(build.getWorkspace())) {
                logger.info("Creating and/or cleaning report directory");
                slaveReportDir.mkdirs();
                slaveReportDir.deleteContents();
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            config.setDataDir(oldTestDataDir);
            return false;
        } catch (InterruptedException e) {
            logger.interrupt(e.getMessage());
            config.setDataDir(oldTestDataDir);
            return false;
        }
        logger.info("Setting report directory to " + slaveReportDir.getRemote());
        config.setReportDir(new File(slaveReportDir.getRemote()));

        // store information to undo changes
        List<TestSet> oldTestSets = new ArrayList<>();
        List<TestSet> newTestSets = new ArrayList<>();
        List<ExecutionConfigurationItem> deactivated = new ArrayList<>();
        int i = 0;
        if (StringUtils.isEmpty(testSetName)) {
            for (ExecutionConfigurationItem item : config.getItems()) {
                oldTestSets.add(item.getTestSet());
                if (item.isActive()) {
                    Collection<Scenario> intersectionSet = intersectByHash(
                            item.getTestSet().getTestCases().getItems(), foundScenearios);
                    if (intersectionSet.isEmpty()) {
                        item.setActive(false);
                        deactivated.add(item);
                    } else {
                        String tmpTestSetName = "JENKINS Exec " + i;
                        i++;
                        logger.info("Create test set \"" + tmpTestSetName + "\" for execution of \""
                                + remoteScenarioSetToString(intersectionSet) + "\"");
                        TestSet testSet = openProject.getProject().createTestSet(tmpTestSetName);
                        newTestSets.add(testSet);
                        for (Scenario scen : intersectionSet) {
                            testSet.addTestCase(scen);
                        }
                        item.setTestSet(testSet);
                    }
                }
            }
        } else {
            String tmpTestSetName = "JENKINS Exec " + testSetName;
            logger.info("Create test set \"" + tmpTestSetName + "\" for execution of \""
                    + remoteScenarioSetToString(foundScenearios) + "\" from File " + tptFile.getName());

            TestSet testSet = openProject.getProject().createTestSet(tmpTestSetName);
            newTestSets.add(testSet);
            for (Scenario scen : foundScenearios) {
                testSet.addTestCase(scen);
            }
            for (ExecutionConfigurationItem item : config.getItems()) {
                oldTestSets.add(item.getTestSet());
                if (item.isActive()) {
                    item.setTestSet(testSet);
                }
            }
        }
        // execute test
        ExecutionStatus execStatus = api.run(config);
        while (execStatus.isRunning() || execStatus.isPending()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                logger.interrupt(e.getMessage());
                execStatus.cancel();
                break;
            }
        }
        // undo changes
        logger.info("Set test sets in execution config to old values.");
        for (ExecutionConfigurationItem item : config.getItems()) {
            item.setTestSet(oldTestSets.remove(0));
        }
        try {
            slaveDataDir.copyRecursiveTo(new FilePath(masterWorkspace, testDataDir));
            slaveReportDir.copyRecursiveTo(new FilePath(masterWorkspace, reportDir));

            logger.info("Copied all data to master from File " + tptFile.getName() + " to "
                    + masterWorkspace.getRemote());

        } catch (InterruptedException e) {
            logger.interrupt(e.getMessage());
            return false;
        } catch (IOException e) {
            logger.error("could not copy results to master: " + e.getMessage());
        }
        logger.info("reset test data and report directory to " + oldTestDataDir.getPath() + " and "
                + oldReportDir.getPath());
        config.setDataDir(oldTestDataDir);
        config.setReportDir(oldReportDir);
        for (TestSet testSet : newTestSets) {
            logger.info("delete temporary test set \"" + testSet.getName() + "\"");
            openProject.getProject().getTestSets().delete(testSet);
        }
        logger.info("Reactivate temporary deactivated execution config items.");
        for (ExecutionConfigurationItem item : deactivated) {
            item.setActive(true);
        }
    } catch (RemoteException e) {
        logger.error(e.getLocalizedMessage());
        e.printStackTrace(logger.getLogger());
        return false;
    } catch (ApiException e) {
        logger.error(e.getLocalizedMessage());
        e.printStackTrace(logger.getLogger());
        return false;
    }
    return true;
}

From source file:org.openhab.binding.megadevice.internal.MegaDeviceBinding.java

public void ScanPorts() {
    try {/*from w  w w  .  j  a  v a  2  s . co m*/
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String Result = "";
    for (MegaDeviceBindingProvider provider : providers) {

        for (String itemName : provider.getItemNames()) {
            try {
                if (provider.getItemType(itemName).toString().contains("NumberItem")) {
                    if (provider.getPORT(itemName).toString().contains("tget")) {
                        Result = "http://" + provider.getIP(itemName) + "/" + provider.password(itemName)
                                + "/?tget=1";
                    } else if ((provider.getPORT(itemName).toString().contains("t"))
                            || (provider.getPORT(itemName).toString().contains("h"))
                            || (provider.getPORT(itemName).toString().contains("1w"))) {
                        String[] PortParse = provider.getPORT(itemName).toString().split("[,]");

                        Result = "http://" + provider.getIP(itemName) + "/" + provider.password(itemName)
                                + "/?pt=" + PortParse[0] + "&cmd=get";
                    } else {

                        Result = "http://" + provider.getIP(itemName) + "/" + provider.password(itemName)
                                + "/?pt=" + provider.getPORT(itemName) + "&cmd=get";
                    }
                } else {
                    Result = "http://" + provider.getIP(itemName) + "/" + provider.password(itemName) + "/?pt="
                            + provider.getPORT(itemName) + "&cmd=get";
                }

                URL obj = new URL(Result);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                logger.debug(Result);

                /*
                 * logger.debug("Sleeping..."); try { Thread.sleep(delay); }
                 * catch (InterruptedException e) { e.printStackTrace(); }
                 * logger.debug("Waking up...");
                 */
                // optional default is GET
                con.setRequestMethod("GET");
                con.setConnectTimeout(500);
                con.setReadTimeout(500);

                // add request header
                con.setRequestProperty("User-Agent", "Mozilla/5.0");

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                logger.debug("input string->" + response.toString());
                if (response.toString().contains("ON")) {
                    if (provider.getItemType(itemName).toString().contains("ContactItem")) {
                        ep.postUpdate(itemName, OpenClosedType.CLOSED);
                    } else {
                        ep.postUpdate(itemName, OnOffType.ON);
                    }
                } else if (response.toString().contains("OFF")) {
                    if (provider.getItemType(itemName).toString().contains("ContactItem")) {
                        ep.postUpdate(itemName, OpenClosedType.OPEN);
                    } else {
                        ep.postUpdate(itemName, OnOffType.OFF);
                    }
                } else {
                    if (provider.getItemType(itemName).toString().contains("DimmerItem")) {
                        int percent = (int) Math.round(Integer.parseInt(response.toString()) / 2.55);
                        ep.postUpdate(itemName, PercentType.valueOf(Integer.toString(percent)));
                        logger.debug(itemName + " " + percent);
                    } else if (provider.getItemType(itemName).toString().contains("NumberItem")) {

                        if (provider.getPORT(itemName).toString().contains("dht")) {
                            String[] PortParse = provider.getPORT(itemName).toString().split("[,]");
                            for (int ind = 0; ind < PortParse.length; ind++) {
                                logger.debug(PortParse[ind]);
                            }
                            if (PortParse[2].contains("t")) {

                                String[] ResponseParse = response.toString().split("[:/]");
                                for (int ind = 0; ind < ResponseParse.length; ind++) {
                                    logger.debug(ind + ": " + ResponseParse[ind]);
                                }
                                if (ResponseParse.length > 2) {
                                    if (ResponseParse[0].contains("temp")) {
                                        ep.postUpdate(itemName, DecimalType.valueOf(ResponseParse[1]));
                                    }
                                } else {
                                    ep.postUpdate(itemName, DecimalType.valueOf(ResponseParse[0]));
                                }

                            } else if (PortParse[2].contains("h")) {
                                String[] ResponseParse = response.toString().split("[:/]");

                                for (int ind = 0; ind < ResponseParse.length; ind++) {
                                    logger.debug(ind + ": " + ResponseParse[ind]);
                                }
                                if (ResponseParse.length > 2) {
                                    if (ResponseParse[2].contains("hum")) {
                                        ep.postUpdate(itemName, DecimalType.valueOf(ResponseParse[3]));
                                    }
                                } else {
                                    ep.postUpdate(itemName, DecimalType.valueOf(ResponseParse[1]));
                                }
                            }
                        } else if (provider.getPORT(itemName).toString().contains("1w")) {
                            String[] ResponseParse = response.toString().split("[:]");
                            if (ResponseParse.length > 1) {
                                logger.debug(ResponseParse[1]);
                                if (!(response.toString().equals("NA"))) {
                                    ep.postUpdate(itemName, DecimalType.valueOf(ResponseParse[1]));
                                }
                            } else {
                                if (!(response.toString().equals("NA"))) {
                                    ep.postUpdate(itemName, DecimalType.valueOf(response.toString()));
                                }
                            }
                        } else if (provider.getPORT(itemName).toString().contains("tget")) {
                            if (response.length() > 0) {
                                ep.postUpdate(itemName, DecimalType.valueOf(response.toString()));
                            }
                        } else {
                            ep.postUpdate(itemName, DecimalType.valueOf(response.toString()));
                        }
                    }
                }
            } catch (IOException e) {
                logger.debug("Connect to megadevice " + provider.getIP(itemName) + " error: "
                        + e.getLocalizedMessage());
            }
        }

    }

}

From source file:ctd.services.getCleanData2.java

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

    try {/*from ww  w.ja v  a  2s. c  o  m*/
        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;
}