Example usage for java.lang Exception getStackTrace

List of usage examples for java.lang Exception getStackTrace

Introduction

In this page you can find the example usage for java.lang Exception getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

public static String toProperties(Map m) {
    Properties props = new Properties();
    Iterator keys = m.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object val = m.get(key);
        if (val instanceof Collection) {
            Collection col = (Collection) val;
            int i = 0;
            for (Iterator it = col.iterator(); it.hasNext(); i++) {
                Object o = it.next();
                if (o instanceof Map) {
                    Map valmap = (Map) o;
                    Iterator fields = valmap.keySet().iterator();
                    while (fields.hasNext()) {
                        String field = (String) fields.next();
                        props.put(key + "." + i + "." + field, valmap.get(field).toString());
                    }/*from   ww  w .j  av  a2  s. c  om*/
                } else {
                    props.put(key + "." + i, o.toString());
                }
            }
        } else if (val instanceof Map) {
            Map m2 = (Map) val;
            for (Iterator it = m2.keySet().iterator(); it.hasNext();) {
                String k2 = (String) it.next();
                props.put(key + "." + k2, (String) m2.get(k2));
            }
        } else if (val instanceof Exception) {
            Exception ex = (Exception) val;
            props.put(key + ".summary", ex.toString());
            StackTraceElement[] elem = ex.getStackTrace();
            for (int i = 0; i < elem.length; i++) {
                props.put(key + "." + i, elem[i].toString());
            }
        } else {
            props.put(key, val.toString());
        }
    }

    // serialize to a string
    String content = null;
    try {
        StringWriter sw = new StringWriter();
        props.store(sw, null);
        content = sw.toString();
    } catch (Exception ex) {
        content = "Error serializing properties: " + ex.toString();
        log.error(content, ex);
    }

    return content;
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

public static String toHTML(Map m) {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("html");
    doc.setRootElement(root);/*from   w  w  w  .  j  a va  2  s  . co  m*/
    Element body = root.addElement("body");
    Element table = body.addElement("table");
    Iterator keys = m.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object val = m.get(key);
        Element row = table.addElement("tr");
        Element keyCell = row.addElement("td");
        keyCell.setText(key);
        Element valCell = row.addElement("td");
        if (val instanceof String) {
            valCell.setText(val.toString());
        } else if (val instanceof Collection) {
            Collection col = (Collection) val;
            for (Iterator it = col.iterator(); it.hasNext();) {
                Element p = valCell.addElement("p");
                Object o = it.next();
                if (o instanceof Map) {
                    Map valmap = (Map) o;
                    Iterator fields = valmap.keySet().iterator();
                    while (fields.hasNext()) {
                        String field = (String) fields.next();
                        String value = (String) valmap.get(field);
                        p.addText(field + ": " + value);
                        if (fields.hasNext()) {
                            p.addElement("br");
                        }
                    }
                } else {
                    p.setText(o.toString());
                }
            }
        } else if (val instanceof Map) {
            Map m2 = (Map) val;
            for (Iterator it = m2.keySet().iterator(); it.hasNext();) {
                String k2 = (String) it.next();
                String v2 = (String) m2.get(k2);
                Element div = valCell.addElement("div");
                div.setText(k2 + ": " + v2);
            }
        } else if (val instanceof Exception) {
            Exception ex = (Exception) val;
            valCell.addElement("p").setText(ex.toString());
            StackTraceElement[] elem = ex.getStackTrace();
            for (int i = 0; i < elem.length; i++) {
                valCell.addText(elem[i].toString());
                valCell.addElement("br");
            }
        }

    }
    return doc.asXML();
}

From source file:com.ut.healthelink.service.impl.transactionInManagerImpl.java

@Override
public Integer moveFilesByPath(String inPath, Integer transportMethodId, Integer orgId, Integer transportId) {
    Integer sysErrors = 0;/* w  w  w . ja  va2 s.com*/

    try {
        fileSystem fileSystem = new fileSystem();
        String fileInPath = fileSystem.setPathFromRoot(inPath);
        File folder = new File(fileInPath);

        //list files
        //we only list visible files
        File[] listOfFiles = folder.listFiles((FileFilter) HiddenFileFilter.VISIBLE);

        Organization orgDetails = organizationmanager.getOrganizationById(orgId);
        String defPath = "/bowlink/" + orgDetails.getcleanURL() + "/input files/";
        String outPath = fileSystem.setPath(defPath);

        //too many variables that could come into play regarding file types, will check files with one method
        //loop files 
        for (File file : listOfFiles) {
            String fileName = file.getName();
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
            Date date = new Date();
            /* Create the batch name (TransportMethodId+OrgId+Date/Time/Seconds) */
            String batchName = new StringBuilder().append(transportMethodId).append(orgId)
                    .append(dateFormat.format(date)).toString();

            if (!fileName.endsWith("_error")) {

                try {

                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

                    //figure out how many active transports are using fileExt method for this particular path
                    List<configurationTransport> transportList = configurationtransportmanager
                            .getTransportListForFileExtAndPath(fileExt, transportMethodId, 1, inPath);

                    //figure out if files has distinct delimiters
                    List<configurationTransport> transports = configurationtransportmanager
                            .getConfigTransportForFileExtAndPath(fileExt, transportMethodId, 1, inPath);

                    batchUploads batchInfo = new batchUploads();
                    batchInfo.setOrgId(orgId);
                    batchInfo.settransportMethodId(transportMethodId);
                    batchInfo.setstatusId(4);
                    batchInfo.setstartDateTime(date);
                    batchInfo.setutBatchName(batchName);
                    batchInfo.setOriginalFolder(inPath);

                    Integer batchId = 0;
                    String newFileName = "";
                    Integer statusId = 4;
                    Integer configId = 0;
                    Integer fileSize = 0;
                    Integer encodingId = 1;
                    Integer errorId = 0;

                    if (transportList.size() == 0 || transports.size() == 0) { //neither of them should be 0
                        //no source transport is associated with this method / file
                        batchInfo.setuserId(usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                        batchInfo.setConfigId(0);
                        newFileName = newFileName(outPath, fileName);
                        batchInfo.setoriginalFileName(newFileName);
                        batchInfo.setFileLocation(defPath);
                        batchInfo.setEncodingId(encodingId);
                        batchId = (Integer) submitBatchUpload(batchInfo);
                        //insert error
                        errorId = 13;
                        statusId = 7;
                    } else if (transports.size() == 1) {
                        encodingId = transports.get(0).getEncodingId();
                        configurationTransport ct = configurationtransportmanager
                                .getTransportDetailsByTransportId(transportId);
                        fileSize = ct.getmaxFileSize();
                        if (transportList.size() > 1) {
                            configId = 0;
                            fileSize = configurationtransportmanager.getMinMaxFileSize(fileExt,
                                    transportMethodId);
                        } else {
                            configId = ct.getconfigId();
                        }
                        batchInfo.setConfigId(configId);
                        batchInfo.setContainsHeaderRow(transports.get(0).getContainsHeaderRow());
                        batchInfo.setDelimChar(transports.get(0).getDelimChar());
                        batchInfo.setFileLocation(ct.getfileLocation());
                        outPath = fileSystem.setPath(ct.getfileLocation());
                        batchInfo.setOrgId(orgId);
                        newFileName = newFileName(outPath, fileName);
                        batchInfo.setoriginalFileName(newFileName);
                        batchInfo.setEncodingId(encodingId);

                        //find user 
                        List<User> users = usermanager.getSendersForConfig(Arrays.asList(ct.getconfigId()));
                        if (users.size() == 0) {
                            users = usermanager.getOrgUsersForConfig(Arrays.asList(ct.getconfigId()));
                        }

                        batchInfo.setuserId(users.get(0).getId());
                        batchId = (Integer) submitBatchUpload(batchInfo);
                        statusId = 2;

                    } else if (transportList.size() > 1 && transports.size() > 1) {
                        //we loop though our delimiters for this type of fileExt
                        String delimiter = "";
                        Integer fileDelimiter = 0;
                        String fileLocation = "";
                        Integer userId = 0;
                        //get distinct delimiters
                        List<configurationTransport> delimList = configurationtransportmanager
                                .getDistinctDelimCharForFileExt(fileExt, transportMethodId);
                        List<configurationTransport> encodings = configurationtransportmanager
                                .getTransportEncoding(fileExt, transportMethodId);
                        //we reject file is multiple encodings/delimiters are found for extension type as we won't know how to decode it and read delimiter
                        if (encodings.size() != 1) {
                            batchInfo.setuserId(usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                            statusId = 7;
                            errorId = 16;
                        } else {
                            encodingId = encodings.get(0).getEncodingId();
                            for (configurationTransport ctdelim : delimList) {
                                fileSystem dir = new fileSystem();
                                int delimCount = (Integer) dir.checkFileDelimiter(file, ctdelim.getDelimChar());
                                if (delimCount > 3) {
                                    delimiter = ctdelim.getDelimChar();
                                    fileDelimiter = ctdelim.getfileDelimiter();
                                    statusId = 2;
                                    fileLocation = ctdelim.getfileLocation();
                                    break;
                                }
                            }
                        }
                        // we don't have an error yet

                        if (errorId > 0) {
                            // some error detected from previous checks
                            userId = usermanager.getUserByTypeByOrganization(orgId).get(0).getId();
                            batchInfo.setConfigId(configId);
                            batchInfo.setFileLocation(defPath);
                            batchInfo.setOrgId(orgId);
                            newFileName = newFileName(outPath, fileName);
                            batchInfo.setoriginalFileName(newFileName);
                            batchInfo.setuserId(userId);
                            batchId = (Integer) submitBatchUpload(batchInfo);
                            batchInfo.setEncodingId(encodingId);
                        } else if (statusId != 2) {
                            //no vaild delimiter detected
                            statusId = 7;
                            userId = usermanager.getUserByTypeByOrganization(orgId).get(0).getId();
                            batchInfo.setConfigId(configId);
                            batchInfo.setFileLocation(defPath);
                            batchInfo.setOrgId(orgId);
                            newFileName = newFileName(outPath, fileName);
                            batchInfo.setoriginalFileName(newFileName);
                            batchInfo.setuserId(userId);
                            batchId = (Integer) submitBatchUpload(batchInfo);
                            batchInfo.setEncodingId(encodingId);
                            errorId = 15;
                        } else if (statusId == 2) {
                            encodingId = encodings.get(0).getEncodingId();
                            //we check to see if there is multi header row, if so, we reject because we don't know what header rows value to look for
                            List<configurationTransport> containsHeaderRowCount = configurationtransportmanager
                                    .getCountContainsHeaderRow(fileExt, transportMethodId);

                            if (containsHeaderRowCount.size() != 1) {
                                batchInfo.setuserId(
                                        usermanager.getUserByTypeByOrganization(orgId).get(0).getId());
                                statusId = 7;
                                errorId = 14;
                            } else {
                                List<Integer> totalConfigs = configurationtransportmanager
                                        .getConfigCount(fileExt, transportMethodId, fileDelimiter);

                                //set how many configs we have
                                if (totalConfigs.size() > 1) {
                                    configId = 0;
                                } else {
                                    configId = totalConfigs.get(0);
                                }

                                //get path
                                fileLocation = configurationtransportmanager
                                        .getTransportDetails(totalConfigs.get(0)).getfileLocation();
                                fileSize = configurationtransportmanager
                                        .getTransportDetails(totalConfigs.get(0)).getmaxFileSize();
                                List<User> users = usermanager.getSendersForConfig(totalConfigs);
                                if (users.size() == 0) {
                                    users = usermanager.getOrgUsersForConfig(totalConfigs);
                                }
                                userId = users.get(0).getId();
                                batchInfo.setContainsHeaderRow(
                                        containsHeaderRowCount.get(0).getContainsHeaderRow());
                                batchInfo.setDelimChar(delimiter);
                                batchInfo.setConfigId(configId);
                                batchInfo.setFileLocation(fileLocation);
                                outPath = fileSystem.setPath(fileLocation);
                                batchInfo.setOrgId(orgId);
                                newFileName = newFileName(outPath, fileName);
                                batchInfo.setoriginalFileName(newFileName);
                                batchInfo.setuserId(userId);
                                batchInfo.setEncodingId(encodingId);
                                batchId = (Integer) submitBatchUpload(batchInfo);
                            }
                        }
                    }
                    /** insert log**/
                    try {
                        //log user activity
                        UserActivity ua = new UserActivity();
                        ua.setUserId(0);
                        ua.setFeatureId(0);
                        ua.setAccessMethod("System");
                        ua.setActivity("System Uploaded File");
                        ua.setBatchUploadId(batchInfo.getId());
                        usermanager.insertUserLog(ua);

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.err.println("moveFilesByPath - insert user log" + ex.toString());
                    }
                    //we encoded user's file if it is not
                    File newFile = new File(outPath + newFileName);
                    // now we move file
                    Path source = file.toPath();
                    Path target = newFile.toPath();

                    File archiveFile = new File(fileSystem.setPath(archivePath) + batchName
                            + newFileName.substring(newFileName.lastIndexOf(".")));
                    Path archive = archiveFile.toPath();
                    //we keep original file in archive folder
                    Files.copy(source, archive);

                    /**
                     * we check encoding here *
                     */
                    if (encodingId < 2) { //file is not encoded
                        String encodedOldFile = filemanager.encodeFileToBase64Binary(file);
                        filemanager.writeFile(newFile.getAbsolutePath(), encodedOldFile);
                        Files.delete(source);
                    } else {
                        Files.move(source, target);
                    }

                    if (statusId == 2) {
                        /**
                         * check file size if configId is 0 we go with the smallest file size *
                         */
                        long maxFileSize = fileSize * 1000000;
                        if (Files.size(target) > maxFileSize) {
                            statusId = 7;
                            errorId = 12;
                        }
                    }

                    if (statusId != 2) {
                        insertProcessingError(errorId, 0, batchId, null, null, null, null, false, false, "");
                    }

                    updateBatchStatus(batchId, statusId, "endDateTime");

                } catch (Exception exAtFile) {
                    exAtFile.printStackTrace();
                    System.err.println("moveFilesByPath " + exAtFile.toString());
                    try {
                        sendEmailToAdmin(
                                (exAtFile.toString() + "<br/>" + Arrays.toString(exAtFile.getStackTrace())),
                                "moveFilesByPath - at rename file to error ");
                        //we need to move that file out of the way
                        file.renameTo((new File(file.getAbsolutePath() + batchName + "_error")));
                    } catch (Exception ex1) {
                        ex1.printStackTrace();
                        System.err.println("moveFilesByPath " + ex1.getMessage());

                    }
                }
            }

        }

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            sendEmailToAdmin((ex.toString() + "<br/>" + Arrays.toString(ex.getStackTrace())),
                    "moveFilesByPath - issue with looping folder files");
        } catch (Exception ex1) {
            ex1.printStackTrace();
            System.err.println("moveFilesByPath " + ex1.getMessage());
        }
        return 1;
    }
    return sysErrors;
}

From source file:org.apache.stanbol.enhancer.engine.disambiguation.mlt.DisambiguatorEngine.java

public void computeEnhancements(ContentItem ci) throws EngineException {

    MGraph graph = ci.getMetadata();//w  w w. j  a va  2 s  .c om
    LiteralFactory literalFactory = LiteralFactory.getInstance();

    List<String> allEntities = new ArrayList<String>();
    Map<SavedEntity, List<UriRef>> textAnnotations = new HashMap<SavedEntity, List<UriRef>>();
    String contentLangauge = null;

    List<Triple> loseConfidence = new ArrayList<Triple>();//List to contain old confidence values that are to removed
    List<Triple> gainConfidence = new ArrayList<Triple>();//List to contain new confidence values to be added to metadata

    RemoveConf = new ArrayList<Triple>();
    AddConf = new ArrayList<Triple>();

    ci.getLock().readLock().lock();
    try {
        contentLangauge = EnhancementEngineHelper.getLanguage(ci);
        readEntities(loseConfidence, allEntities, textAnnotations, graph);
    } catch (Exception e) {
        //JOptionPane.showMessageDialog(null, "dfnnndd33n");

        LOG.info(" readEntities" + e.getMessage());

    }
    ci.getLock().readLock().unlock();

    // ci.getLock().writeLock().lock();

    //removeOldConfidenceFromGraph(graph,l);
    //addNewConfidenceToGraph(graph,w);
    //ci.getLock().writeLock().unlock();

    Site dbpediaSite = null;
    try {
        dbpediaSite = siteManager.getSite("dbpedia");

        for (Entry<SavedEntity, List<UriRef>> entry : textAnnotations.entrySet()) {

            SavedEntity savedEntity = entry.getKey();
            String label = savedEntity.getName();// the selected text of the TextAnnotation to
                                                 // disambiguate
            Collection<String> types = null; // potential types of entities
            String language = contentLangauge; // the language of the analyzed text
            List<UriRef> subsumed = entry.getValue();
            boolean casesensitive = false;
            String savedEntityLabel = casesensitive ? label : label.toLowerCase();

            if (subsumed.size() <= 1) {
                continue;
            }
            // JOptionPane.showMessageDialog(null, " tobaccos  ");

            String extractionContext = savedEntity.getContext();
            // 
            extractionContext = findContext(label, allEntities, extractionContext); // the surrounding text of the
            // extraction

            //JOptionPane.showMessageDialog(null, "extractionContext="+extractionContext);

            QueryResultList<Entity> results = queryDbpedia(dbpediaSite, savedEntityLabel, language,
                    extractionContext);
            LOG.info(" - {} results returned by query {}", results.size(), results.getQuery());
            // JOptionPane.showMessageDialog(null, " dsf  "+results.size()+"kk"+extractionContext);

            List<Suggestion> matches = rankResults(results, casesensitive, language, savedEntityLabel);
            Collections.sort(matches);

            ci.getLock().readLock().lock();
            try {
                if (intersectionCheck(matches, subsumed, graph, contentLangauge)) {
                    gainConfidence = intersection(matches, subsumed, graph, gainConfidence, contentLangauge);
                } else {
                    loseConfidence = unchangedConfidences(subsumed, graph, loseConfidence);
                }
            } finally {
                ci.getLock().readLock().unlock();
            }
        }
        //   JOptionPane.showMessageDialog(null, " 11");

        ci.getLock().writeLock().lock();
        try {
            // JOptionPane.showMessageDialog(null, " 22");

            removeOldConfidenceFromGraph(graph, loseConfidence);
            //   JOptionPane.showMessageDialog(null, " 33");

            addNewConfidenceToGraph(graph, gainConfidence);
        } finally {
            ci.getLock().writeLock().unlock();
        }

    }

    catch (Exception e) {
        LOG.info("Error " + e.getMessage());
        LOG.info("Error " + e.getStackTrace());
        JOptionPane.showMessageDialog(null, "dfnnnn");

        // JOptionPane.showMessageDialog(null, e.getStackTrace());

    }
}

From source file:rems.Global.java

public static String decrypt(String inpt, String key) {
    try {/*from   www .  j av a 2 s. co  m*/
        String fnl_str = "";
        String[] charset1 = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
                "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
                "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
                "s", "t", "u", "v", "w", "x", "y", "z" };
        String keyString = Global.getNewKey(key);
        String[] charset2 = new String[keyString.length()];
        int cntr = keyString.length();
        for (int i = 0; i < cntr; i++) {
            charset2[i] = String.valueOf(keyString.charAt(i));
        }

        String[] wldChars = { "`", "", "!", "\"", "", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+",
                "{", "[", "]", "}", ":", ";", "@", "'", "#", "~", "/", "?", ">", ".", "<", ",", "\\", "|" };
        int wldCharsLen = wldChars.length;

        for (int i = inpt.length() - 1; i >= 0; i--) {
            String tst_str = String.valueOf(inpt.charAt(i));
            if (tst_str.equals("_")) {
                continue;
            }
            int j = Global.findCharIndx(tst_str, charset2);
            if (j == -1) {
                fnl_str += tst_str;
            } else if (i < inpt.length() - 1) {
                if (String.valueOf(inpt.charAt(i + 1)).equals("_") && j < wldCharsLen) {
                    fnl_str += wldChars[j];
                } else {
                    fnl_str += charset1[j];
                }
            } else {
                fnl_str += charset1[j];
            }
        }
        String nwStr1 = fnl_str.substring(0, 4);
        String nwStr2 = fnl_str.substring(4, 8);
        int StringLn = Integer.valueOf(nwStr2) - Integer.valueOf(nwStr1);
        String nwStr3 = fnl_str.substring(8, StringLn + 8);
        return nwStr3;
    } catch (Exception ex) {
        Global.errorLog = ex.getMessage() + "\r\n" + Arrays.toString(ex.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        return inpt;
    }
}

From source file:rems.Global.java

public static boolean isTransPrmttd(int accntID, String trnsdate, double amnt, String outptMsg[]) {
    try {/*from   ww w  .j ava  2 s  .  co m*/
        //trnsdate = DateTime.ParseExact(
        //trnsdate, "dd-MMM-yyyy HH:mm:ss",
        //System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss");
        //Transaction date must be >= the latest prd start date
        if (accntID <= 0 || trnsdate.equals("")) {
            return false;
        }

        SimpleDateFormat frmtr = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        SimpleDateFormat frmtr1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat frmtr2 = new SimpleDateFormat("dd-MMM-yyyy");
        SimpleDateFormat frmtr3 = new SimpleDateFormat("dddd");
        Calendar trnsDte = Calendar.getInstance();
        trnsDte.setTime(frmtr.parse(trnsdate));
        Calendar dte1 = Calendar.getInstance();
        dte1.setTime(frmtr.parse(Global.getLtstPrdStrtDate()));
        Calendar dte1Or = Calendar.getInstance();
        dte1Or.setTime(frmtr.parse(Global.getLastPrdClseDate()));
        Calendar dte2 = Calendar.getInstance();
        dte2.setTime(frmtr.parse(Global.getLtstPrdEndDate()));

        if (trnsDte.equals(dte1Or) || trnsDte.before(dte1Or)) {
            outptMsg[0] += "Transaction Date cannot be On or Before " + frmtr.format(dte1Or);
            return false;
        }
        if (trnsDte.before(dte1)) {
            outptMsg[0] += "Transaction Date cannot be before " + frmtr.format(dte1);
            return false;
        }
        if (trnsDte.after(dte2)) {
            outptMsg[0] += "Transaction Date cannot be after " + frmtr.format(dte2);
            return false;
        }
        //Check if trnsDate exists in an Open Period
        long prdHdrID = Global.getPrdHdrID(Global.UsrsOrg_ID);
        //Global.showMsg(Global.Org_iString.valueOf(d) + "-" + prdHdrID.ToString(), 0);
        if (prdHdrID > 0) {
            //Global.showMsg(trnsDte.ToString("yyyy-MM-dd HH:mm:ss") + "-" + prdHdrID.ToString(), 0);
            if (Global.getTrnsDteOpenPrdLnID(prdHdrID, frmtr1.format(trnsDte)) < 0) {
                outptMsg[0] += "Cannot use a Transaction Date (" + frmtr.format(trnsDte)
                        + ") which does not exist in any OPEN period!";
                return false;
            }
            //Check if Date is not in Disallowed Dates
            String noTrnsDatesLov = Global.getGnrlRecNm("accb.accb_periods_hdr", "periods_hdr_id",
                    "no_trns_dates_lov_nm", prdHdrID);
            String noTrnsDayLov = Global.getGnrlRecNm("accb.accb_periods_hdr", "periods_hdr_id",
                    "no_trns_wk_days_lov_nm", prdHdrID);
            //Global.showMsg(noTrnsDatesLov + "-" + noTrnsDayLov + "-" + trnsDte.ToString("dddd").ToUpper() + "-" + trnsDte.ToString("dd-MMM-yyyy").ToUpper(), 0);

            if (!noTrnsDatesLov.equals("")) {
                if (Global.getEnbldPssblValID(frmtr2.format(trnsDte).toUpperCase(),
                        Global.getEnbldLovID(noTrnsDatesLov)) > 0) {
                    outptMsg[0] += "Transactions on this Date (" + frmtr.format(trnsDte)
                            + ") have been banned on this system!";
                    return false;
                }
            }
            //Check if Day of Week is not in Disaalowed days
            if (!noTrnsDatesLov.equals("")) {
                if (Global.getEnbldPssblValID(frmtr3.format(trnsDte).toUpperCase(),
                        Global.getEnbldLovID(noTrnsDayLov)) > 0) {
                    outptMsg[0] += "Transactions on this Day of Week (" + frmtr3.format(trnsDte)
                            + ") have been banned on this system!";
                    return false;
                }
            }
        }

        //Amount must not disobey budget settings on that account
        long actvBdgtID = Global.getActiveBdgtID(Global.UsrsOrg_ID);
        double amntLmt = Global.getAcntsBdgtdAmnt(actvBdgtID, accntID, frmtr.format(trnsDte));

        Calendar bdte1 = Calendar.getInstance();
        bdte1.setTime(frmtr.parse(Global.getAcntsBdgtStrtDte(actvBdgtID, accntID, frmtr.format(trnsDte))));

        Calendar bdte2 = Calendar.getInstance();
        bdte2.setTime(frmtr.parse(Global.getAcntsBdgtEndDte(actvBdgtID, accntID, frmtr.format(trnsDte))));

        double crntBals = Global.getTrnsSum(accntID, frmtr.format(bdte1), frmtr.format(bdte2), "1");

        String actn = Global.getAcntsBdgtLmtActn(actvBdgtID, accntID, trnsdate);

        if ((amnt + crntBals) > amntLmt) {
            if (actn.equals("Disallow")) {
                outptMsg[0] += "This transaction will cause budget on \r\nthe chosen account to be exceeded! ";
                return false;
            } else if (actn.equals("Warn")) {
                outptMsg[0] += "This is just to WARN you that the budget on \r\nthe chosen account will be exceeded!";
                return true;
            } else if (actn.equals("Congratulate")) {
                outptMsg[0] += "This is just to CONGRATULATE you for exceeding the targetted Amount! ";
                return true;
            } else {
                return true;
            }
        }
        return true;
    } catch (Exception ex) {
        outptMsg[0] += Arrays.toString(ex.getStackTrace()) + "\r\n" + ex.getMessage();
        return false;
    }
}

From source file:base.BasePlayer.BedCanvas.java

boolean annotate(BedNode head, VarNode node) {

    if (FileRead.head.getNext() == null && head.getTrack().small) {
        head.getTrack().used = false;//from   ww w .ja  v a2  s  . c  o  m

        return false;
    }
    //if(current.getPosition() == 36852366) {}

    int varlength = 0;
    BedNode currentBed = head.getNext();
    Object[] t2 = new Object[Main.bedCanvas.bedTrack.size()];
    Object[] t1 = new Object[Main.bedCanvas.bedTrack.size()];

    for (int i = 0; i < t1.length; i++) {
        if (!Main.bedCanvas.bedTrack.get(i).intersect) {
            continue;
        }
        if (Main.bedCanvas.bedTrack.get(i).getIntersectBox().isSelected()
                && !Main.bedCanvas.bedTrack.get(i).annotator) {
            t1[i] = 1;
        }
    }
    if (head.getTrack().used) {
        VarNode current = FileRead.head.getNext();
        while (current != null) {

            current.bedhit = checkIntersect(current, t1, t2);
            current = current.getNext();
        }

        Draw.updatevars = true;
        Draw.calculateVars = true;
        Main.drawCanvas.repaint();
        return true;
    }

    if (currentBed == null) {
        return false;
    }

    VarNode current = node;
    node = null;
    int position = 0;

    try {

        if (current != null) {

            while (currentBed != null) {
                if (!Main.drawCanvas.loading) {
                    break;
                }
                if (current.getNext() == null) {
                    if (currentBed.getPosition() > current.getPosition() + 1) {
                        break;
                    }
                }

                if (current.getPrev().getPrev() == null
                        && currentBed.getPosition() + currentBed.getLength() < current.getPosition()) {
                    currentBed = currentBed.getNext();
                    continue;
                }

                if (current != null && current.getPrev() != null) {
                    while (current.getPrev().getPosition() >= currentBed.getPosition()) {
                        if (current.getPrev() != null) {
                            current = current.getPrev();
                        } else {

                            current = current.getNext();
                            break;
                        }
                    }
                }

                position = current.getPosition();

                if (current.indel) {

                    varlength = MethodLibrary.getBaseLength(current.vars, 1);
                } else {

                    varlength = 0;
                }

                /*if(position == 34286255) {
                           
                   if(position+varlength >= currentBed.getPosition()) {
                      System.out.println(position +" " +(currentBed.getPosition()+currentBed.getLength()) +" " +currentBed.getPosition());
                   }
                           
                }*/
                while (position < currentBed.getPosition() + currentBed.getLength()) {

                    if (!Main.drawCanvas.loading) {
                        break;
                    }

                    try {

                        if (position + varlength >= currentBed.getPosition()) {

                            if (!currentBed.getTrack().used) {

                                if (current.getBedHits() == null) {
                                    current.setBedhits();
                                }
                                found = true;
                                if (currentBed.id != null || currentBed.getTrack().selex) {

                                    if (currentBed.getTrack().getAffinityBox().isSelected()) {
                                        if (currentBed.getTrack().limitValue != (double) Integer.MIN_VALUE
                                                && currentBed.getTrack().limitValue != null) {
                                            found = false;
                                            for (int i = 0; i < current.vars.size(); i++) {
                                                if (Math.abs(MethodLibrary.calcAffiniyChange(current,
                                                        current.vars.get(i).getKey(), currentBed)) > Math
                                                                .abs(currentBed.getTrack().limitValue)) {
                                                    found = true;
                                                    break;
                                                }
                                            }

                                        }
                                    }
                                }
                                if (found) {
                                    if (currentBed.getTrack().basecolumn != null) {
                                        for (int i = 0; i < current.vars.size(); i++) {
                                            if (currentBed.name.equals(current.vars.get(i).getKey())) {
                                                current.getBedHits().add(currentBed);
                                                current.setBedhit(true);

                                                if (currentBed.varnodes == null) {
                                                    currentBed.varnodes = new ArrayList<VarNode>();
                                                }
                                                if (!currentBed.varnodes.contains(current)) {
                                                    currentBed.varnodes.add(current);
                                                }
                                            }
                                        }
                                    } else {

                                        current.getBedHits().add(currentBed);
                                        current.setBedhit(true);

                                        if (currentBed.varnodes == null) {
                                            currentBed.varnodes = new ArrayList<VarNode>();
                                        }
                                        if (!currentBed.varnodes.contains(current)) {
                                            currentBed.varnodes.add(current);
                                        }
                                    }
                                }
                            }
                        }

                        if (current != null) {

                            if (!head.getTrack().annotator) {

                                current.bedhit = checkIntersect(current, t1, t2);
                            }
                            if (current.getNext() != null) {
                                current = current.getNext();
                            } else {
                                break;
                            }

                            position = current.getPosition();
                            //System.out.println(position +" " +(currentBed.getPosition()+currentBed.getLength()));
                            if (current.indel) {
                                //   position = current.getPosition()+1;   
                                varlength = MethodLibrary.getBaseLength(current.vars, 1);

                            } else {
                                //   position = current.getPosition();
                                varlength = 0;
                            }

                        } else {

                            break;
                        }
                    } catch (Exception e) {

                        e.printStackTrace();
                        break;
                    }
                }

                currentBed = currentBed.getNext();

            }

        }
    } catch (Exception e) {
        ErrorLog.addError(e.getStackTrace());
        e.printStackTrace();

    }

    if (!head.getTrack().annotator && !FileRead.bigcalc) {
        head.getTrack().used = true;
        while (current != null) {

            current.bedhit = checkIntersect(current, t1, t2);
            current = current.getNext();
        }
    }

    current = null;
    currentBed = null;

    return true;
}

From source file:rems.Global.java

public static void exprtToHTMLTblr(ResultSet dtst, String fileNm, String rptTitle, String[] colsToGrp,
        String[] colsToCnt, String[] colsToSum, String[] colsToAvrg, String[] colsToFrmt, boolean isfirst,
        boolean islast, boolean shdAppnd) {
    try {/*from   w  w  w . j  av  a 2s .c  o m*/
        System.out.println(fileNm);
        DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
        DecimalFormat myFormatter2 = new DecimalFormat("###,##0");
        dtst.last();
        int totlRows = dtst.getRow();
        dtst.beforeFirst();
        ResultSetMetaData dtstmd = dtst.getMetaData();
        int colCnt = dtstmd.getColumnCount();
        long totlLen = 0;
        for (int d = 0; d < colCnt; d++) {
            totlLen += dtstmd.getColumnName(d + 1).length();
        }
        long[] colcntVals = new long[colCnt];
        double[] colsumVals = new double[colCnt];
        double[] colavrgVals = new double[colCnt];
        String cption = "";
        if (isfirst) {
            cption = "<caption align=\"top\">" + rptTitle + "</caption>";
            Global.strSB.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
                    + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"[]><html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en-US\" xml:lang=\"en\"><head><meta http-equiv=\"Content-Type\" "
                    + "content=\"text/html; charset=utf-8\">" + System.getProperty("line.separator") + "<title>"
                    + rptTitle + "</title>" + System.getProperty("line.separator")
                    + "<link rel=\"stylesheet\" href=\"../amcharts/rpt.css\" type=\"text/css\"></head><body>");

            Files.copy(
                    new File(Global.getOrgImgsDrctry() + "/" + String.valueOf(Global.UsrsOrg_ID) + ".png")
                            .toPath(),
                    new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                            + String.valueOf(Global.UsrsOrg_ID) + ".png").toPath(),
                    StandardCopyOption.REPLACE_EXISTING);

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/images/" + String.valueOf(Global.UsrsOrg_ID) + ".png");
            }
            //Org Name
            String orgNm = Global.getOrgName(Global.UsrsOrg_ID);
            String pstl = Global.getOrgPstlAddrs(Global.UsrsOrg_ID);
            //Contacts Nos
            String cntcts = Global.getOrgContactNos(Global.UsrsOrg_ID);
            //Email Address
            String email = Global.getOrgEmailAddrs(Global.UsrsOrg_ID);

            Global.strSB
                    .append("<p><img src=\"../images/" + String.valueOf(Global.UsrsOrg_ID) + ".png\">" + orgNm
                            + "<br/>" + pstl + "<br/>" + cntcts + "<br/>" + email + "<br/>" + "</p>")
                    .append(System.getProperty("line.separator"));
        }

        Global.strSB.append("<table style=\"margin-top:5px;\">" + cption + "<thead>")
                .append(System.getProperty("line.separator"));

        int wdth = 0;
        String finalStr = " ";
        for (int d = 0; d < colCnt; d++) {
            String algn = "left";
            int colLen = dtstmd.getColumnName(d + 1).length();
            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
            if (colLen >= 3) {
                if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                    algn = "right";
                    finalStr = StringUtils.leftPad(dtstmd.getColumnName(d + 1).trim(), colLen, ' ');
                } else {
                    finalStr = dtstmd.getColumnName(d + 1).trim() + " ";
                }
                Global.strSB
                        .append("<th align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                + finalStr.replace(" ", "&nbsp;") + "</th>")
                        .append(System.getProperty("line.separator"));
            }
        }

        Global.strSB.append("</thead><tbody>").append(System.getProperty("line.separator"));

        String[][] prevRowVal = new String[totlRows][colCnt];
        dtst.beforeFirst();
        System.out.println(Global.strSB.toString());
        for (int a = 0; a < totlRows; a++) {
            dtst.next();
            Global.strSB.append("<tr>").append(System.getProperty("line.separator"));
            for (int d = 0; d < colCnt; d++) {
                String algn = "left";
                double nwval = 0;
                boolean mstgrp = Global.mustColBeGrpd(String.valueOf(d), colsToGrp);
                if (Global.mustColBeCntd(String.valueOf(d), colsToCnt) == true) {
                    if ((a > 0) && (mstgrp == true)) {
                        if ((prevRowVal[a - 1][d].equals(dtst.getString(d + 1)))) {

                        } else {
                            colcntVals[d] += 1;
                        }
                    } else {
                        colcntVals[d] += 1;
                    }
                } else if (Global.mustColBeSumd(String.valueOf(d), colsToSum) == true) {
                    nwval = Double.parseDouble(dtst.getString(d + 1));
                    if ((a > 0) && (mstgrp == true)) {
                        if ((prevRowVal[a - 1][d].equals(dtst.getString(d + 1)))) {

                        } else {
                            colsumVals[d] += nwval;
                        }
                    } else {
                        colsumVals[d] += nwval;
                    }
                } else if (Global.mustColBeAvrgd(String.valueOf(d), colsToAvrg) == true) {
                    nwval = Double.parseDouble(dtst.getString(d + 1));
                    if ((a > 0) && (mstgrp == true)) {
                        if (prevRowVal[a - 1][d].equals(dtst.getString(d + 1))) {

                        } else {
                            colcntVals[d] += 1;
                            colsumVals[d] += nwval;
                        }
                    } else {
                        colcntVals[d] += 1;
                        colsumVals[d] += nwval;
                    }
                }

                int colLen = dtstmd.getColumnName(d + 1).length();
                if (colLen >= 3) {
                    if ((a > 0) && (Global.mustColBeGrpd(String.valueOf(d), colsToGrp) == true)) {
                        if (prevRowVal[a - 1][d].equals(dtst.getString(d + 1))) {
                            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                            Global.strSB
                                    .append("<td align=\"" + algn + "\"  width=\"" + wdth + "%\">"
                                            + " ".replace(" ", "&nbsp;") + "</td>")
                                    .append(System.getProperty("line.separator"));
                        } else {
                            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                            String frsh = " ";
                            if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                                algn = "right";
                                double num = Double.parseDouble(dtst.getString(d + 1).trim());
                                if (!dtst.getString(d + 1).equals("")) {
                                    frsh = myFormatter.format(num);//.Trim().PadRight(60, ' ')
                                } else {
                                    frsh = dtst.getString(d + 1) + " ";
                                }
                            } else {
                                frsh = dtst.getString(d + 1) + " ";
                            }
                            Global.strSB.append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                    + Global.breakTxtDownHTML(frsh, dtstmd.getColumnName(d + 1).length())
                                            .replace(" ", "&nbsp;")
                                    + "</td>").append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
                        }
                    } else {
                        wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                        String frsh = " ";
                        if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                            algn = "right";
                            double num = Double.parseDouble(dtst.getString(d + 1).trim());
                            if (!dtst.getString(d + 1).equals("")) {
                                frsh = myFormatter.format(num);//.Trim().PadRight(60, ' ')
                            } else {
                                frsh = dtst.getString(d + 1) + " ";
                            }
                        } else {
                            frsh = dtst.getString(d + 1) + " ";
                        }
                        Global.strSB
                                .append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                        + Global.breakTxtDownHTML(frsh, dtstmd.getColumnName(d + 1).length())
                                                .replace(" ", "&nbsp;")
                                        + "</td>")
                                .append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
                    }
                }
            }
            Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
        }
        //Populate Counts/Sums/Averages
        Global.strSB.append("<tr>").append(System.getProperty("line.separator"));

        for (int f = 0; f < colCnt; f++) {
            String algn = "left";
            int colLen = dtstmd.getColumnName(f + 1).length();
            finalStr = " ";
            if (colLen >= 3) {
                if (Global.mustColBeCntd(String.valueOf(f), colsToCnt) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Count = " + myFormatter2.format(colcntVals[f]));
                    } else {
                        finalStr = ("Count = " + String.valueOf(colcntVals[f]));
                    }
                } else if (Global.mustColBeSumd(String.valueOf(f), colsToSum) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Sum = " + myFormatter.format(colsumVals[f]));
                    } else {
                        finalStr = ("Sum = " + String.valueOf(colcntVals[f]));
                    }
                } else if (Global.mustColBeAvrgd(String.valueOf(f), colsToAvrg) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Average = " + myFormatter.format(colsumVals[f] / colcntVals[f]));
                    } else {
                        finalStr = ("Average = " + String.valueOf(colsumVals[f] / colcntVals[f]));
                    }
                } else {
                    finalStr = " ";
                }
                Global.strSB
                        .append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                + Global.breakTxtDownHTML(finalStr, dtstmd.getColumnName(f + 1).length())
                                        .replace(" ", "&nbsp;")
                                + "</td>")
                        .append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
            }
        }
        Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
        Global.strSB.append("</tbody></table>").append(System.getProperty("line.separator"));
        if (islast) {
            Global.strSB.append("</body></html>");

            File file = new File(fileNm);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(Global.strSB.toString());
            bw.close();

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/samples/" + String.valueOf(Global.runID) + ".html");
            }
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n\r\n");
        Global.errorLog += ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n\r\n";
        Global.writeToLog();
    }
}

From source file:com.castis.xylophone.adsmadapter.convert.axistree.ConvertInventoryBox.java

public boolean generateInventorySizePolicy(ADSMJobNameType jobName, ADSMJobNameType inventorySizePolicy) {
    long start = System.currentTimeMillis();

    InventoryBoxDTO inventoryBox = tambourineConnector.findNewInventoryBox(jobName, inventorySizePolicy.name());
    if (inventoryBox == null)
        return true;

    log.info("generateInventorySizePolicy start [jobName : " + jobName.name() + "] ");

    // ?  ?.//from w  w w. j  a v a 2 s  .  c om
    tambourineConnector.generateKtTimeTableTree(inventoryBox.getTimeDefine(), inventoryBox.getStart_DT());

    ADSMSchedulerLogDTO schedulerLog = null;
    try {
        //??  schedulerLog ?.
        schedulerLog = tambourineConnector.startLog(inventorySizePolicy.name(),
                "inventoryLogId:" + inventoryBox.getSchedulerLogId());
        if (schedulerLog == null)
            return false;

        /*===============================================
         * 1. ', , ?'  . + 'OpportunityEvent'  (?? preplay, midplay ? )
         ================================================*/
        AxisTreeDTO categoryAxisTreeDTO = null;
        AxisTreeDTO regionAxisTreeDTO = null;
        AxisTreeDTO weekAxisTreeDTO = null;

        try {
            String categoryTreeName = Constants.tree.CATEGORY_TREE_NAME;
            String regionTreeName = Constants.tree.REGION_TREE_NAME;
            String weekTreeName = AxisTree.wellKnownTreeNameTimeTableTree;

            categoryAxisTreeDTO = inventoryExportSysCompForAdapter
                    .findAxisTreeByName(TreeType.CATEGORY_AXIS_TREE, categoryTreeName, new Date(), new Date());
            if (categoryAxisTreeDTO == null)
                return false;
            regionAxisTreeDTO = inventoryExportSysCompForAdapter.findAxisTreeByName(TreeType.REGION_AXIS_TREE,
                    regionTreeName, new Date(), new Date());
            if (regionAxisTreeDTO == null)
                return false;
            weekAxisTreeDTO = inventoryExportSysCompForAdapter.findAxisTreeByName(TreeType.TIME_AXIS_TREE,
                    weekTreeName, new Date(), new Date());
            if (weekAxisTreeDTO == null)
                return false;
            log.info("tree load done");
        } catch (Exception e) {
            log.error("tree load - fail", e);
            throw e;
        }

        /*===============================================
         * 2.  mapping ID mapper 
         ================================================*/
        InventorySizePolicyGenerator sizePolicyGenerator = new InventorySizePolicyGenerator();

        try {
            int cateSize = sizePolicyGenerator.setCategoryMap(categoryAxisTreeDTO);
            int regionSize = sizePolicyGenerator.setRegionMap(regionAxisTreeDTO);
            int timeSize = sizePolicyGenerator.setWeekMap(weekAxisTreeDTO);
            //            int opportunitySize = sizePolicyGenerator.setOpportunityMap(oppAxisTreeDTO);

            //time Define?  size
            TimeDefineDTO timeDefine = inventoryBox.getTimeDefine();
            sizePolicyGenerator.setTimeNodeCellCountMap(timeDefine);

            /*===============================================
             * 3. license ? ?  ? ? ? 
             ================================================*/
            sizePolicyGenerator.setInventoryBoxPeriod(inventoryBox.getStart_DT(), inventoryBox.getEnd_DT());
            sizePolicyGenerator.setInventoryBoxVersion(inventoryBox.getInventoryVer());

            log.info("mapper generate done(cateSize:" + cateSize + ",regionSize:" + regionSize + ",timeSize:"
                    + timeSize /*+ ",opportunitySize:" + opportunitySize + ")"*/);
        } catch (Exception e) {
            log.error("InventorySizePolicyGenerator make - fail", e);
            throw e;
        }

        /*===============================================
         * 4. ? list 
         ================================================*/
        List<InventorySizePolicyDTO> sizePolicyList = new ArrayList<InventorySizePolicyDTO>();
        log.info("? ?  ? ");

        ADInventoryDTO inventory = null;
        PlacementOpportunityTypeEnum oppType = null;
        try {

            if (inventoryBox.getAdInventory() != null && ADSMJobNameType.INVENTORY_BOX.equals(jobName)) {
                inventory = inventoryBox.getAdInventory();
                oppType = PlacementOpportunityTypeEnum.PREROLL;
            } else if (inventoryBox.getMidplay_adInventory() != null
                    && ADSMJobNameType.INVENTORY_BOX_MID.equals(jobName)) {
                inventory = inventoryBox.getMidplay_adInventory();
                oppType = PlacementOpportunityTypeEnum.MIDROLL;
            } else if (inventoryBox.getPostplay_adInventory() != null
                    && ADSMJobNameType.INVENTORY_BOX_POST.equals(jobName)) {
                inventory = inventoryBox.getPostplay_adInventory();
                oppType = PlacementOpportunityTypeEnum.POSTROLL;
            }
            generateSizePolicyList(sizePolicyList, inventory, oppType, sizePolicyGenerator);

            sizePolicyList.addAll(sizePolicyGenerator.generateAutoInventorySizePolicy(oppType));
            log.info("? ?  ? ( :" + sizePolicyList.size() + ")");
        } catch (Exception e) {
            log.error("InventorySizePolicy generate - fail", e);
            throw e;
        }

        /*===============================================
         * 5.  
         ================================================*/
        log.info("? ?  DB  ");
        try {
            if (sizePolicyList.size() > 0) {
                Date startDate = sizePolicyGenerator.getSizePolicyStartDate();
                Date endDate = sizePolicyGenerator.getSizePolicyEndDate();
                //TODO: ? ? 
                inventoryExportSysCompForAdapter.registerInventorySizePolicy(sizePolicyList, startDate, endDate,
                        oppType);
            }
        } catch (Exception e) {
            log.error("InventorySizePolicy register - fail", e);
            throw e;
        }

        log.info("? ?  DB  (version-" + inventoryBox.getInventoryVer() + ")");

        /*===============================================
         * 6.  ?  join Table  insert
         ================================================*/
        log.info("InventorySizePolicy  GenericAxisItem List  ? .");
        inventoryExportSysCompForAdapter.copyPolicyGenericAxisItem(oppType);
        log.info("InventorySizePolicy  GenericAxisItem List  ? .");
        schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);

    } catch (Exception e) {
        //log.error("",e);
        schedulerLog.setMessage(e.toString());
        schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
        StackTraceElement[] stackTraces = e.getStackTrace();
        if (stackTraces.length > 0) {
            schedulerLog.setFailProcess(stackTraces[0].getClassName() + " - " + stackTraces[0].getMethodName()
                    + "(" + stackTraces[0].getLineNumber() + ")");
        }
        TheLogger.getWriter().error(inventoryBox.getInventoryVer() + " Inventory Size   ");
        log.error(inventoryBox.getInventoryVer()
                + " Inventory Size   . ? ?? ?.");
        return false;
    } finally {
        //? ? ??? 
        tambourineConnector.endLog(schedulerLog);
    }
    long end = System.currentTimeMillis();
    log.info("generateInventorySizePolicy end T(" + (end - start) + ")");
    TheLogger.getWriter().info(inventoryBox.getInventoryVer() + " Inventory Size   ");
    return true;
}

From source file:de.fhg.fokus.odp.portal.managedatasets.controller.ManageController.java

/**
 * Submit./*from w  w w.  j  a  v a2  s .c o m*/
 * 
 * @return the string
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public String submit() {

    for (Licence l : licences) {
        if (selectedLicence.equals(l.getName())) {
            if (unknownLicence) {
                l.setTitle(unknownLicenceText);
                l.setUrl(unknownLicenceUrl);
                l.setOther(unknownLicenceText);
            }
            metadataController.getMetadata().setLicence(l);
            break;
        }
    }

    metadataController.getMetadata().getCategories().clear();

    for (Category c : categories) {
        for (String cName : selectedManyCategories) {
            if (cName.equals(c.getName())) {
                metadataController.getMetadata().getCategories().add(c);
            }
        }
    }

    metadataController.getMetadata().getTags().clear();
    for (String t : selectedTags) {
        Tag tag = metadataController.getMetadata().newTag(t);
        metadataController.getMetadata().getTags().add(tag);
    }

    metadataController.getMetadata().getContacts().clear();
    metadataController.getMetadata().getContacts().add(author);
    metadataController.getMetadata().getContacts().add(maintainer);
    metadataController.getMetadata().getContacts().add(distributor);
    Contact publisher = author;
    metadataController.getMetadata().getContacts().add(publisher);

    LiferayFacesContext lfc = LiferayFacesContext.getInstance();
    ThemeDisplay themeDisplay = lfc.getThemeDisplay();

    String location = themeDisplay.getPortalURL();

    Layout layout = themeDisplay.getLayout();
    try {
        if (layout.isPublicLayout()) {
            location += themeDisplay.getPathFriendlyURLPublic();
        }
        if (layout.hasScopeGroup()) {
            location += layout.getScopeGroup().getFriendlyURL();
        } else {
            location += layout.getGroup().getFriendlyURL();
        }

        // manage DATASET-uploads for CSV/XMLFiles only
        if (metadataController.getMetadata().getType().equals(MetadataEnumType.DATASET)) {

            // CSV/XMLFile -> Storage: url to receive csv or xml file from
            // storage
            try {
                Resource res4Sorage = metadataController.getMetadata().newResource();
                res4Sorage.setUrl(CSVXMLFileUtils.uploadToStorage(uploadCSVXML.getUploadedFile()).toString());
                res4Sorage.setDescription("REST API entry point");
                res4Sorage.setFormat("rest");
            } catch (Exception e) {
                LOG.error("Error on upload csv/xml to storage: {}", uploadCSVXML.getUploadedFile(),
                        e.getMessage());
            }

            // CSV/XMLFile -> Document Library: url to receive csv or xml
            // file from ckan as gemo resource
            try {
                Resource r = metadataController.getMetadata().newResource();
                r.setUrl(CSVXMLFileUtils.uploadToDocmentLibrary(uploadCSVXML.getUploadedFile()).toString());
                r.setDescription("CSV XML");
                final String ext = FilenameUtils.getExtension(uploadCSVXML.getUploadedFile().getName());
                r.setFormat(ext);
            } catch (Exception e) {
                LOG.error("Error csv/xml upload to document library: {}", uploadCSVXML.getUploadedFile(),
                        e.getMessage());
            }
        }

        // manage DATASET-uploads for WAR-File -> Document Library: url to
        // receive war file from ckan as gemo resource
        if (metadataController.getMetadata().getType().equals(MetadataEnumType.DOCUMENT)) {

            // WAR -> DOCUMENT LIBRARY

            Resource r = metadataController.getMetadata().newResource();
            String pathToWarFile = null;
            try {
                pathToWarFile = WarFileUtils.uploadToDocmentLibrary(uploadWar.getUploadedFile()).toString();
                LOG.debug("WarFileUtils added .war file to Liferay Document Library at:" + pathToWarFile);
            } catch (IOException e) {
                LOG.error("Error WAR-Upload to document library: {}", uploadWar.getUploadedFile(),
                        e.getMessage());
                e.printStackTrace();
            } catch (PortalException e2) {
                e2.printStackTrace();
            } catch (SystemException e3) {
                e3.printStackTrace();
            } finally {
                if (pathToWarFile == null)
                    pathToWarFile = "etc/mobility-data-cloud/mobility-services-binaries";
                r.setUrl(pathToWarFile);
                r.setDescription("deployment");
                r.setFormat("war");
            }
            // WAR -> AUTO-DEPLOYMENT
            try {
                WarFileUtils.uploadToAutoDeployService(uploadWar.getUploadedFile());
            } catch (Exception e) {
                LOG.error("Error WAR-Upload to document library: {}", uploadWar.getUploadedFile(),
                        e.getMessage());
            }
        }

        switch (metadataController.getMetadata().getType()) {
        case APPLICATION:
            location += "/apps";

            try {
                metadataController.getMetadata().getImages()
                        .add(ImageGalleryUtils.uploadImage(appImage.getUploadedFile()).toString());
            } catch (URISyntaxException e) {
                // TODO: better errorhandling...
                LOG.error("App image URI. ", e.getMessage());
            } catch (IOException e) {
                // TODO: better errorhandling...
                LOG.error("Error on storing image: {}", appImage.getUploadedFile(), e.getMessage());
            } catch (NullPointerException e) {
                // TODO: better errorhandling...
                LOG.error("Error on storing image: {}", "[no image selected]", e.getMessage());
            }

            ((Application) metadataController.getMetadata()).getUsedDatasets().clear();

            /* Check and sort out empty URIs */
            for (String uri : usedDatasetUris) {
                if (!uri.isEmpty()) {
                    ((Application) metadataController.getMetadata()).getUsedDatasets().add(uri);
                }
            }

            break;
        case DOCUMENT:
            location += "/daten";
            break;
        case UNKNOWN:
            location += "/suchen";
            break;
        default:
            location += "/daten";
        }

        if (editMode || !metadataController.getMetadata().getType().equals(MetadataEnumType.APPLICATION)) {
            location += "/-/details/" + odrClient.mungeTitleToName(metadataController.getMetadata().getTitle());
        }

    } catch (PortalException e) {
        LOG.error(e.getMessage());
        LOG.debug("Error on metadata create / edit submit.", e.getStackTrace());
    } catch (SystemException e) {
        LOG.error(e.getMessage());
        LOG.debug("Error on metadata create / edit submit.", e.getStackTrace());
    }

    // to fix the empty resources error ######################
    List<Resource> listOfResources = metadataController.getMetadata().getResources();
    for (Iterator<Resource> iterator = listOfResources.iterator(); iterator.hasNext();) {
        Resource resource = iterator.next();
        if (resource.getUrl() == null) {
            // Remove the current element from the iterator and the list.
            iterator.remove();
        }
    }
    // to fix the empty resources error ######################

    try {
        try {
            odrClient.persistMetadata(currentUser.getCurrentUser(), metadataController.getMetadata());
        } catch (OpenDataRegistryException e) {
            // TODO: better errorhandling...
            LOG.error("Error on creating metadata: {}", metadataController.getMetadata().getName(),
                    e.getMessage());
        }

        if (!editMode && metadataController.getMetadata().getType().equals(MetadataEnumType.APPLICATION)) {

            Properties props = new Properties();
            props.setProperty("ckan.authorization.key", PropsUtil.get("authenticationKey"));
            props.setProperty("ckan.url", PropsUtil.get("cKANurl"));

            ODRClient appOdrClient = OpenDataRegistry.getClient();
            appOdrClient.init(props);

            Metadata newApp;
            try {
                newApp = appOdrClient.getMetadata(currentUser.getCurrentUser(),
                        metadataController.getMetadata().getName());

                newApp.setState("deleted");
                appOdrClient.persistMetadata(currentUser.getCurrentUser(), newApp);
                MailUtils.sendMail(newApp);
            } catch (OpenDataRegistryException e) {
                // TODO: better errorhandling...
                LOG.error("Error on updating state of metadata to deleted: {}",
                        metadataController.getMetadata().getName(), e.getMessage());
            } catch (PortalException e) {
                LOG.error("Error creating app: {}\n{}", metadataController.getMetadata().getName(),
                        e.getMessage());
            } catch (SystemException e) {
                LOG.error("Error creating app: {}\n{}", metadataController.getMetadata().getName(),
                        e.getMessage());
            } catch (MessagingException e) {
                LOG.error("Error creating app: {}\n{}", metadataController.getMetadata().getName(),
                        e.getMessage());
            }
        }

        FacesContext.getCurrentInstance().getExternalContext().redirect(location);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        LOG.debug("Error ob metadata create / edit submit", e.getStackTrace());
    }

    return null;
}