Example usage for java.lang NullPointerException printStackTrace

List of usage examples for java.lang NullPointerException printStackTrace

Introduction

In this page you can find the example usage for java.lang NullPointerException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:jdbc.pool.JDBCPoolMySQLTest.java

public void testGetPoolStatistics() {
    testGetInstanceNull();/* ww  w . j  ava  2 s  .co  m*/
    CConnectionPoolManager manager = null;
    try {
        manager = create();

        try {
            manager.getPoolStatistics("MYSQL2");
        } catch (NullPointerException e) {
            assertTrue("Pool attribute load-on-startup is false", true);
        }
        CPoolStatisticsBean bean = manager.getPoolStatistics("MYSQL");
        assertEquals("MYSQL", bean.getPoolName());
        assertEquals("Bad Connections Count", 0, bean.getBadConnectionCount());
        assertEquals("Connections High Count", 0, bean.getConnectionsHighCount());
        assertEquals("Current Free Connections", 3, bean.getCurrentFreeConnectionCount());
        assertEquals("Current Used Connection count", 0, bean.getCurrentUsedConnectionCount());
        assertEquals("Leaked Connection Count", 0, bean.getLeakedConnectionCount());
        assertEquals("Leaked Statement Count", 0, bean.getLeakedStatementCount());
        assertEquals("Leaked ResultSet Count", 0, bean.getLeakedResultSetCount());
        //            assertEquals("Connections Closed Count", 0, bean.getNoOfConnectionsClosed());
        //            assertEquals("Connections Created Count", 0, bean.getNoOfConnectionsCreated());
        //            assertEquals("Connections Locked", 0, bean.getNoOfConnectionsLocked());
        //            assertEquals("Connections Requested Count", 0, bean.getNoOfConnectionsRequested());
        //            assertEquals("Connections Unlocked Count", 0, bean.getNoOfConnectionsUnlocked());
        //            assertEquals("New Connections Created Count", 0, bean.getNoOfNewConnectionsRequested());
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    } finally {
        manager.destroy(true);
    }

}

From source file:org.adl.validator.contentpackage.CPValidator.java

/**
 * This method retrieves the directory location of the test subject by
 * truncating the filename off of the URL passed in.
 * //from  ww w  .  j  a  v a2s  .co  m
 * @param iFileName
 *            The absolute path of the test subject file
 * @return String - the directory that the file is located
 */
private String getPathOfFile(String iFileName) {
    mLogger.debug("CPValidator getPathOfFile()");

    String result = "";
    String tmp = "";

    try {
        StringTokenizer token = new StringTokenizer(iFileName, File.separator, true);

        int numTokens = token.countTokens();

        // We want all but the last token added
        numTokens--;

        for (int i = 0; i < numTokens; i++) {
            tmp = token.nextToken();

            mLogger.debug("token = " + tmp);

            result = result + tmp;
        }
    } catch (NullPointerException npe) {
        npe.printStackTrace();
    }

    mLogger.debug("CPValidator getPathOfFile()");

    return result;
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * This is the main method that does the Kerberos authentication and 
 * should be invoked by the classes that would like to open a new 
 * authentication process against a Kerberized protected source.
 * <p>/*from w  w w  .  j  a v a 2s . c o m*/
 * It behaves differently if the it's set up as a Negotiation process or 
 * the Kerberos credentials are got from the username and password 
 * credentials. It reads "isNegotiate" var and invokes the proper method 
 * that manages Kerberos authentication specifically for each method.
 * <p>
 * If the Kerberos authentication result is OK, a cookie is created with an  
 * encoded information that includes the username to be reused if this is 
 * needed in any other Authn/AuthZ module. It also populates the credentials 
 * vector with the user's Kerberos credential ("krb5") that the caller 
 * process should reuse when authorizing.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    //Vars             
    int responseCode = HttpServletResponse.SC_UNAUTHORIZED;
    Cookie[] cookies = null;

    // Read cookies
    cookies = request.getCookies();

    //Protection
    logger.debug("Checking if user already has Krb credentials. If so, return OK");

    try {
        if (creds != null) {
            if (creds.getCredential(KRB5_ID) != null) {

                logger.debug("Credential found: " + KRB5_ID);

                if (creds.getCredential(KRB5_ID).getSubject() != null) {

                    //user Kerberos subject already created, so user is authenticated                        
                    logger.debug("Kerberos subject already exists. Returning...");

                    // Set status code
                    responseCode = HttpServletResponse.SC_OK;

                    // Return
                    return responseCode;
                }
            }
        }
    } catch (NullPointerException e) {
        logger.debug("Krb subject does not exist. Continue with the process...");
    }

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    try {
        logger.debug("Getting credentials");
        //Get Krb config files            
        krbconfig = valveConf.getKrbConfig().getKrbconfig();
        logger.debug("Krb config file: " + krbconfig);
        krbini = valveConf.getKrbConfig().getKrbini();
        logger.debug("Krb ini file: " + krbini);

        if ((isNegotiate) && (serverSubject == null)) {

            try {

                initializeKerberos();

            } catch (Exception ex) {
                logger.error("Exception during Server Kerberos config initialization: " + ex.getMessage(), ex);
            } finally {
            }

        }

        //Get user credentials
        //First read the u/p the credentails store, in this case using the same as the root login
        Credential userNamePwdCred = null;

        if (isNegotiate) {
            logger.debug("KerbAuth: IsNegotiate");
            responseCode = authNegotiate(request, response);
        } else {
            logger.debug("KerbAuth: It's NOT IsNegotiate with id: " + id);

            try {
                logger.debug("HttpKrb: trying to get creds from repository id: " + id);
                userNamePwdCred = creds.getCredential(id);
            } catch (NullPointerException npe) {
                logger.error("NPE while reading credentials of ID: " + id);
            }

            if (userNamePwdCred == null) {
                logger.debug("HttpKrb: trying to get creds from repository \"root\"");
                userNamePwdCred = creds.getCredential("root");
            }

            //Execute Authentication method with username and password
            responseCode = authUsernamePassword(userNamePwdCred);
        }

        if (responseCode == HttpServletResponse.SC_OK) {
            //create cookie
            createCookie(request, response);
            //add cookie to the cookie array
            authCookies.add(gsaKrbAuthCookie);
            //add Krb credentials
            Credential krb5Cred = new Credential(KRB5_ID);
            krb5Cred.setKrbSubject(getUserSubject());
            krb5Cred.setUsername(getUsername());
            creds.add(krb5Cred);
        }

    } catch (Exception e) {
        logger.debug("Error creating Credentials: " + e.getMessage());
        e.printStackTrace();
        responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return responseCode;
}

From source file:org.ala.dao.TaxonConceptSHDaoImpl.java

/**
 * Index the supplied taxon concept./*from  ww  w  .  j  a  v  a 2  s  .  co  m*/
 * 
 * @param guid
 * @return
 */
public List<SolrInputDocument> indexTaxonConcept(String guid, Scanner scanner) throws Exception {

    List<SolrInputDocument> docsToAdd = new ArrayList<SolrInputDocument>();

    // get taxon concept details
    TaxonConcept taxonConcept = scanner != null
            ? (TaxonConcept) scanner.getValue(ColumnType.TAXONCONCEPT_COL.getColumnName(), TaxonConcept.class)
            : getByGuid(guid);

    if (taxonConcept != null) {
        // get synonyms concepts
        List<SynonymConcept> synonyms = scanner != null
                ? (List) scanner.getListValue(ColumnType.SYNONYM_COL.getColumnName(), SynonymConcept.class)
                : getSynonymsFor(guid);

        // get congruent concepts
        // List<TaxonConcept> congruentTcs = getCongruentConceptsFor(guid);

        // treat congruent objects the same way we do synonyms
        // synonyms.addAll(congruentTcs);

        // get common names
        List<CommonName> commonNames = scanner != null
                ? (List) scanner.getListValue(ColumnType.VERNACULAR_COL.getColumnName(), CommonName.class)
                : getCommonNamesFor(guid);

        // add the parent id to enable tree browsing with this index
        List<TaxonConcept> children = scanner != null
                ? (List) scanner.getListValue(ColumnType.IS_PARENT_COL_OF.getColumnName(), TaxonConcept.class)
                : getChildConceptsFor(guid);

        // add conservation and pest status'
        List<ConservationStatus> conservationStatuses = scanner != null
                ? (List) scanner.getListValue(ColumnType.CONSERVATION_STATUS_COL.getColumnName(),
                        ConservationStatus.class)
                : getConservationStatuses(guid);
        // List<PestStatus> pestStatuses = getPestStatuses(guid);

        List<Category> categories = scanner != null
                ? (List) scanner.getListValue(ColumnType.CATEGORY_COL.getColumnName(), Category.class)
                : getCategories(guid);

        // add text properties
        List<SimpleProperty> simpleProperties = scanner != null
                ? (List) scanner.getListValue(ColumnType.TEXT_PROPERTY_COL.getColumnName(),
                        SimpleProperty.class)
                : getTextPropertiesFor(guid);

        // save all infosource ids to add in a Set to index at the end
        Set<String> infoSourceIds = new TreeSet<String>();
        Set<String> infoSourceUids = new TreeSet<String>();

        // get alternative ids
        List<String> identifiers = scanner != null
                ? (List) scanner.getListValue(ColumnType.IDENTIFIER_COL.getColumnName(), String.class)
                : getIdentifiers(guid);

        List<TaxonConcept> otherTaxonConcepts = scanner != null
                ? (List) scanner.getListValue(ColumnType.SAME_AS_COL.getColumnName(), TaxonConcept.class)
                : getSameAsFor(guid);

        // TODO this index should also include nub ids
        SolrInputDocument doc = new SolrInputDocument();

        //if the doc is an ala generated concept include a flag
        if (guid.startsWith("ALA"))
            doc.addField("is_ala_b", "true");

        //add the "isExcluded" value
        doc.addField("is_excluded_b", taxonConcept.getIsExcluded());

        doc.addField("idxtype", IndexedTypes.TAXON);

        // is this species iconic
        Boolean iconic = null;
        Boolean australian = null;
        if (scanner != null) {
            iconic = (Boolean) scanner.getValue(ColumnType.IS_ICONIC.getColumnName(), Boolean.class);
            if (iconic == null)
                iconic = false;
            australian = (Boolean) scanner.getValue(ColumnType.IS_AUSTRALIAN.getColumnName(), Boolean.class);
            if (australian == null)
                australian = false;
        }
        Boolean isAustralian = australian == null ? isAustralian(guid) : australian;
        boolean isIconic = iconic == null ? isIconic(guid) : iconic;
        // does this taxon have occurrence records associated with it?
        Integer count = scanner != null
                ? (Integer) scanner.getValue(ColumnType.OCCURRENCE_RECORDS_COUNT_COL.getColumnName(),
                        Integer.class)
                : getOccurrenceRecordCount(guid);
        // boolean isGs=count != null && count.size() >0 && count.get(0)>0;
        if (count != null) {
            doc.addField("occurrenceCount", count);
        }
        //Index the Georeferenced count
        Integer gsCount = scanner != null
                ? (Integer) scanner.getValue(ColumnType.GEOREF_RECORDS_COUNT_COL.getColumnName(), Integer.class)
                : getGeoreferencedRecordsCount(guid);
        if (gsCount != null) {
            doc.addField("georeferencedCount", gsCount);
        }

        if (taxonConcept.getNameString() != null) {

            doc.addField("id", taxonConcept.getGuid());
            doc.addField("guid", taxonConcept.getGuid());

            for (TaxonConcept tc : otherTaxonConcepts) {
                doc.addField("otherGuid", tc.getGuid());
            }

            for (String identifier : identifiers) {
                doc.addField("otherGuid", identifier);
            }
            // add the numeric checklistbank id
            doc.addField("otherGuid", taxonConcept.getId());

            addToSetSafely(infoSourceIds, taxonConcept.getInfoSourceId());
            addToSetSafely(infoSourceUids, taxonConcept.getInfoSourceUid());

            //TODO do we want to add all the associated TaxonNames???
            TaxonName taxonName = null;
            if (scanner != null) {
                List<TaxonName> tns = (List) scanner.getListValue(ColumnType.TAXONNAME_COL.getColumnName(),
                        TaxonName.class);
                if (tns.size() > 0) {
                    taxonName = tns.get(0);
                }
            } else {
                taxonName = getTaxonNameFor(guid);
            }
            if (taxonName != null && taxonName.getNameComplete() != null) {
                doc.addField("nameComplete", taxonName.getNameComplete());
            } else {
                doc.addField("nameComplete", taxonConcept.getNameString());
            }

            // add multiple forms of the scientific name to the index]
            try {
                addScientificNameToIndex(doc, taxonConcept.getNameString(), taxonConcept.getRankString(),
                        taxonConcept.getRankID());
                //now add the supplied name string as the "sortable" singleScientificName
                doc.addField(SINGLE_SCI_NAME, taxonConcept.getNameString());
            } catch (NullPointerException e) {
                System.out.println("TAXONCONCEPT WITH NPE: " + taxonConcept);
                e.printStackTrace();
            }

            if (taxonConcept.getParentGuid() != null) {
                doc.addField("parentGuid", taxonConcept.getParentGuid());
            }
            if (taxonConcept.getParentId() != null) {
                doc.addField("parentId", taxonConcept.getParentId());
            }

            // add the nested set values
            doc.addField("left", taxonConcept.getLeft());
            doc.addField("right", taxonConcept.getRight());
            doc.addField("author", taxonConcept.getAuthor());

            for (ConservationStatus cs : conservationStatuses) {
                if (cs.getRawStatus() != null) {
                    doc.addField("conservationStatus", cs.getRawStatus(), 0.6f);
                    addToSetSafely(infoSourceIds, cs.getInfoSourceId());
                    addToSetSafely(infoSourceUids, cs.getInfoSourceUid());
                    if (cs.getRegion() != null && Regions.getRegion(cs.getRegion()) != null) {
                        Regions r = Regions.getRegion(cs.getRegion());
                        doc.addField("conservationStatus" + r.getAcronym(), cs.getRawStatus());
                    }
                }
            }

            //add the category information
            for (Category category : categories) {
                //add the category to the "general" field so all categories from all dr's can be filetred on
                doc.addField("category_m_s", category.getCategory());
                //add to a dr specific category so that faceting can be performed on individual DR's categories eg weeds or animal pests.
                doc.addField(category.getInfoSourceUid() + "_category_m_s", category.getCategory());
                //add state limiting facet if necessary
                if (StringUtils.isNotBlank(category.getStateProvince())) {
                    doc.addField("category_" + getStateAbbreviation(category.getStateProvince()) + "_m_s",
                            category.getCategory());
                }
                addToSetSafely(infoSourceUids, category.getInfoSourceUid());
            }

            for (SimpleProperty sp : simpleProperties) {
                // index *Text properties
                if (sp.getName().endsWith("Text")) {
                    // Field textField = new Field("simpleText",
                    // sp.getValue(), Store.YES, Index.ANALYZED);
                    // textField.setBoost(0.4f);
                    doc.addField("simpleText", sp.getValue(), 0.4f);
                    addToSetSafely(infoSourceIds, sp.getInfoSourceId());
                    addToSetSafely(infoSourceUids, sp.getInfoSourceUid());
                }
            }

            // StringBuffer cnStr = new StringBuffer();
            Set<String> commonNameSet = new TreeSet<String>();
            List<String> higherPriorityNames = new ArrayList<String>();
            for (CommonName cn : commonNames) {
                if (cn.getNameString() != null && !cn.getIsBlackListed()) {
                    // normalise the common names for display
                    String commonNameString = WordUtils.capitalizeFully(cn.getNameString());
                    commonNameString.trim();
                    commonNameSet.add(commonNameString);

                    if (cn.isPreferred()) {
                        higherPriorityNames.add(cn.getNameString());
                    }
                    addToSetSafely(infoSourceIds, cn.getInfoSourceId());
                    addToSetSafely(infoSourceUids, cn.getInfoSourceUid());

                    // push CAAB preferred common name up
                    if (cn.getRanking() != null && cn.getRanking() > 90000) {
                        logger.debug("**********: " + cn.getNameString() + " , " + cn.getRanking() + "\n");
                        doc.addField("preferredName", cn.getNameString().trim().toLowerCase());
                    }
                }
            }

            if (commonNameSet.size() > 0) {
                String commonNamesConcat = StringUtils.deleteWhitespace(StringUtils.join(commonNameSet, " "));
                doc.addField("commonNameSort", commonNamesConcat);
                // add each common name separately
                // We need to add all common names to the commonNameExact
                // because the CommonName also stores the "parts" of the
                // common name
                for (String commonName : commonNameSet) {
                    if (isIconic) {
                        doc.addField("commonName", commonName, 100f);
                        doc.addField("commonNameExact", commonName, 100f);
                    } else if (higherPriorityNames.contains(commonName)) {
                        doc.addField("commonName", commonName, 5f);
                        doc.addField("commonNameExact", commonName, 5f);
                    } else {
                        doc.addField("commonName", commonName, 1.4f);
                        doc.addField("commonNameExact", commonName, 1.4f);
                    }
                    // pull apart the common name
                    String[] parts = commonName.split(" ");
                    if (parts.length > 1) {
                        String lastPart = parts[parts.length - 1];
                        if (isIconic) {
                            doc.addField("commonName", lastPart, 100f);
                        } else {
                            doc.addField("commonName", lastPart, 2.5f);
                        }
                    }
                }

                doc.addField("commonNameDisplay", StringUtils.join(commonNameSet, ", "));
                doc.addField("commonNameSingle", commonNames.get(0).getNameString().trim());
            }
            String lastNameLsid = null;
            for (SynonymConcept synonym : synonyms) {
                if (synonym.getNameString() != null
                        && (synonym.getNameGuid() != null && !synonym.getNameGuid().equals(lastNameLsid))) {
                    lastNameLsid = synonym.getNameGuid();
                    logger.debug("adding synonym to index: " + synonym.getNameString());
                    // add a new document for each synonym
                    SolrInputDocument synonymDoc = new SolrInputDocument();
                    synonymDoc.addField("id", synonym.getGuid() + taxonConcept.getGuid());//combination of the 2 uniquely identifies a synonym
                    synonymDoc.addField("syn_guid", synonym.getGuid());
                    synonymDoc.addField("guid", taxonConcept.getGuid());
                    synonymDoc.addField("idxtype", IndexedTypes.TAXON);
                    addScientificNameToIndex(synonymDoc, synonym.getNameString(), null, -1);
                    synonymDoc.addField("acceptedConceptName", taxonConcept.getNameString());
                    if (!commonNames.isEmpty()) {
                        synonymDoc.addField("commonNameSort", commonNames.get(0).getNameString());
                        synonymDoc.addField("commonNameDisplay", StringUtils.join(commonNameSet, ", "));
                    }
                    addRankToIndex(synonymDoc, taxonConcept.getRankString(), taxonConcept.getRankID(),
                            taxonConcept.getRawRankString());
                    //add the synonym author
                    synonymDoc.addField("author", synonym.getAuthor());

                    //set the concept as australian if the "accepted" concept is australian
                    if (isAustralian != null && isAustralian) {
                        synonymDoc.addField("australian_s", "recorded");
                        synonymDoc.addField("aus_s", "yes");
                    }
                    //add the synonym type
                    synonymDoc.addField("synonymRelationship_s", synonym.getRelationship());
                    synonymDoc.addField("synonymDescription_s", synonym.getDescription());

                    // add the synonym as a separate document
                    docsToAdd.add(synonymDoc);
                    // store the source
                    if (synonym.getInfoSourceId() != null) {
                        infoSourceIds.add(synonym.getInfoSourceId()); // getting
                        // NPE
                    }
                    addToSetSafely(infoSourceUids, synonym.getInfoSourceUid());
                }
            }

            List<Classification> classifications = scanner != null
                    ? (List) scanner.getListValue(ColumnType.CLASSIFICATION_COL.getColumnName(),
                            Classification.class)
                    : getClassifications(guid);

            for (Classification classification : classifications) {
                addIfNotNull(doc, "kingdom", classification.getKingdom());
                addIfNotNull(doc, "phylum", classification.getPhylum());
                addIfNotNull(doc, "class", classification.getClazz());
                addIfNotNull(doc, "bioOrder", classification.getOrder());
                addIfNotNull(doc, "family", classification.getFamily());
                addIfNotNull(doc, "genus", classification.getGenus());

                //if we have something higher than a genus, add groups
                if (classification.getRankId() != null && classification.getRankId() > 6000) {
                    List<String> speciesGroups = speciesGroupsUtil.getSpeciesGroup(classification);
                    for (String g : speciesGroups) {
                        doc.addField("speciesGroup", g);
                    }
                    List<String> speciesSubgroups = speciesGroupsUtil.getSpeciesSubgroup(classification);
                    for (String g : speciesSubgroups) {
                        doc.addField("speciesSubgroup", g);
                    }
                }
            }

            //check valid image (not blacklisted)
            List<Image> images = scanner != null
                    ? (List) scanner.getListValue(ColumnType.IMAGE_COL.getColumnName(), Image.class)
                    : getImages(guid);

            boolean hasImages = false;
            int firstValidImage = -1;
            int imageCount = 0;
            Set<String> imageSources = new HashSet<String>();
            if (!images.isEmpty()) {
                for (int i = 0; i < images.size(); i++) {
                    Image image = images.get(i);
                    if (!image.getIsBlackListed()) {
                        if (firstValidImage < 0) {
                            firstValidImage = i;
                            hasImages = true;
                        }
                        imageCount++;
                        imageSources.add(image.getInfoSourceUid());
                    }
                }
            }

            //get image count (non-blacklisted sources only)
            doc.addField("imageCount", imageCount);
            //get infosource count  (non-blacklisted sources only)
            doc.addField("imagesSourceCount", imageSources.size());
            //get infosource count  (non-blacklisted sources only)
            for (String imageSource : imageSources)
                doc.addField("imageSources", imageSource);

            if (hasImages && firstValidImage >= 0) {
                // FIXME should be replaced by the highest ranked image
                Image image = images.get(firstValidImage);
                if (image.getRepoLocation() != null) {
                    doc.addField("image", image.getRepoLocation());
                    try {
                        String imageInfosourceId = getImageInfosourceId(image.getRepoLocation());
                        logger.debug("!!!" + imageInfosourceId);
                        infoSourceIds.add(imageInfosourceId);
                        addToSetSafely(infoSourceUids, image.getInfoSourceUid());
                    } catch (Exception e) {
                        logger.warn("Image infosourceId could not be retrieved");
                    }
                    // Change to adding this in earlier
                    String thumbnail = image.getRepoLocation().replace("raw", "thumbnail");
                    doc.addField("thumbnail", thumbnail);
                    doc.addField("imageSource", image.getInfoSourceUid());
                } else {
                    logger.error("Error adding image to concept: " + image);
                }
            }

            doc.addField("hasImage", hasImages);

            if (isAustralian != null && isAustralian) {
                doc.addField("australian_s", "recorded");
                doc.addField("aus_s", "yes");
            }

            String linkIdentifier = scanner != null
                    ? (String) scanner.getValue(ColumnType.LINK_IDENTIFIER.getColumnName(), String.class)
                    : getLinkIdentifier(guid);
            if (linkIdentifier != null) {
                doc.addField("linkIdentifier", linkIdentifier);
            }

            addRankToIndex(doc, taxonConcept.getRankString(), taxonConcept.getRankID(),
                    taxonConcept.getRawRankString());

            doc.addField("hasChildren", Boolean.toString(!children.isEmpty()));
            //doc.addField("dataset", StringUtils.join(infoSourceIds, " "));
            //Add all the dataset id's individually so that they can be searched indivdually
            for (String iid : infoSourceIds) {
                doc.addField("dataset", iid);
            }
            for (String uid : infoSourceUids) {
                doc.addField("uid", uid);
            }
            docsToAdd.add(doc);
        }
    }
    return docsToAdd;
}

From source file:org.entrystore.repository.impl.EntryImpl.java

private boolean loadFromStatements(List<Statement> existingStatements) throws RepositoryException {
    if (existingStatements.isEmpty()) {
        return false;
    }//from w w w .j ava2  s  .c  om
    administerPrincipals = null;
    readMetadataPrincipals = null;
    writeMetadataPrincipals = null;
    readResourcePrincipals = null;
    writeResourcePrincipals = null;
    entryURI = null;
    resURI = null;
    created = null;
    creator = null;
    modified = null;
    externalMdURI = null;
    cachedAt = null;
    locType = EntryType.Local;
    repType = ResourceType.InformationResource;
    resourceType = GraphType.None;

    //Following are cached on request. (Move more values here if possible)
    format = null;
    fileSize = -1;
    filename = null;
    mimeType = null;

    RepositoryConnection rc = null;

    try {
        rc = this.repository.getConnection();
        //         referredIn = new HashSet<java.net.URI>();
        for (Statement statement : existingStatements) {
            URI predicate = statement.getPredicate();
            if (predicate.equals(RepositoryProperties.resource)) {
                this.entryURI = (org.openrdf.model.URI) statement.getSubject();
                this.resURI = (org.openrdf.model.URI) statement.getObject();
            } else if (predicate.equals(RepositoryProperties.metadata)) {
                localMdURI = ((URI) statement.getObject());
            } else if (predicate.equals(RepositoryProperties.externalMetadata)) {
                externalMdURI = ((URI) statement.getObject());
            } else if (predicate.equals(RepositoryProperties.cachedExternalMetadata)) {
                cachedExternalMdURI = ((URI) statement.getObject());
            } else if (predicate.equals(RepositoryProperties.relation)) {
                relationURI = ((URI) statement.getObject());
            } else if (predicate.equals(RepositoryProperties.cached)) {
                // TODO: also wrong
                cachedAt = ((Literal) statement.getObject()).calendarValue();
                //            } else if (predicate.equals(RepositoryProperties.referredIn)) {
                //               referredIn.add(java.net.URI.create(statement.getObject().stringValue()));
            } else if (predicate.equals(RepositoryProperties.Created)) {
                created = ((Literal) statement.getObject()).calendarValue();
            } else if (predicate.equals(RepositoryProperties.Creator)) {
                creator = ((URI) statement.getObject());
            } else if (predicate.equals(RepositoryProperties.Contributor)) {
                contributors.add((URI) statement.getObject());
            } else if (predicate.equals(RepositoryProperties.Modified)) {
                try {
                    //log.info(statement.getObject().stringValue()); 
                    modified = ((Literal) statement.getObject()).calendarValue();
                } catch (NullPointerException e) {
                    log.error(e);
                }
            }
        }

        //Detect types.
        for (Statement statement : existingStatements) {
            org.openrdf.model.Resource subject = statement.getSubject();
            if (statement.getPredicate().equals(RDF.TYPE)) {
                if (this.resURI.equals(subject)) {
                    GraphType bt = getBuiltinType(statement.getObject());
                    if (bt != null) {
                        this.resourceType = bt;
                    } else {
                        ResourceType rt = getRepresentationType(statement.getObject());
                        if (rt != null) {
                            repType = rt;
                        }
                    }
                } else if (this.entryURI.equals(subject)) {
                    EntryType lt = getLocationType(statement.getObject());
                    if (lt != null) {
                        locType = lt;
                    }
                }
            }
        }

        //                  log.info("*****************************"); 
        //                  log.info("entryUri: " + entryURI); 
        //                  log.info("resURI :" + resURI);
        //                  log.info("locType :" + locType);
        //                  log.info("repType :" + repType);
        //                  log.info("resourceType :" + resourceType);
        //                  log.info("created :" + created);
        //                  log.info("modified :" + modified);
        //                  log.info("externalMdURI :" + externalMdURI);
        //                  log.info("cachedAt:" + cachedAt);
        //                  log.info("*****************************"); 
        //TODO check that neccessary things where found among the statements.
    } catch (RepositoryException e) {
        e.printStackTrace();
        throw e;
    } finally {
        rc.close();
    }
    return true;
}

From source file:pl.betoncraft.betonquest.config.ConfigUpdater.java

@SuppressWarnings("unused")
private void update_from_v18() {
    try {//ww  w . j a  va  2s.  c  o  m
        ConfigAccessor confMessages = Config.getMessages();
        FileConfiguration messages = confMessages.getConfig();
        for (String lang : messages.getKeys(false)) {
            if (lang.equalsIgnoreCase("global"))
                continue;
            Debug.info("Updating " + lang + " language");
            try {
                messages.set(lang + ".purged", messages.getString(lang + ".purged").replace("%player%", "{1}"));
                messages.set(lang + ".item_created",
                        messages.getString(lang + ".item_created").replace("%item%", "{1}"));
                messages.set(lang + ".player_event",
                        messages.getString(lang + ".player_event").replace("%event%", "{1}"));
                messages.set(lang + ".player_condition", messages.getString(lang + ".player_condition")
                        .replace("%condition%", "{1}").replace("%outcome%", "{2}"));
                messages.set(lang + ".quest_canceled",
                        messages.getString(lang + ".quest_canceled").replace("%quest%", "{1}"));
                messages.set(lang + ".items_given", messages.getString(lang + ".items_given")
                        .replace("%name%", "{1}").replace("%amount%", "{2}"));
                messages.set(lang + ".items_taken", messages.getString(lang + ".items_taken")
                        .replace("%name%", "{1}").replace("%amount%", "{2}"));
                messages.set(lang + ".blocks_to_break",
                        messages.getString(lang + ".blocks_to_break").replace("%amount%", "{1}"));
                messages.set(lang + ".blocks_to_place",
                        messages.getString(lang + ".blocks_to_place").replace("%amount%", "{1}"));
                messages.set(lang + ".mobs_to_kill",
                        messages.getString(lang + ".mobs_to_kill").replace("%amount%", "{1}"));
                messages.set(lang + ".conversation_start",
                        messages.getString(lang + ".conversation_start").replace("%quester%", "{1}"));
                messages.set(lang + ".conversation_end",
                        messages.getString(lang + ".conversation_end").replace("%quester%", "{1}"));
            } catch (NullPointerException e) {
                Debug.error(
                        "The language " + lang + " is not present in the defaults, please update it manually.");
            }
        }
        confMessages.saveConfig();
        Debug.broadcast("Updated messages to new replace format");
    } catch (Exception e) {
        e.printStackTrace();
        Debug.error(ERROR);
    }
    config.set("version", "v19");
    instance.saveConfig();
}

From source file:com.ephesoft.gxt.admin.server.BatchClassManagementServiceImpl.java

/**
 * Barcode classification API for performing the classification of barcode for input images..
 * //from   www .j  a  va  2s  .com
 * @param batchClassID {@link String} the batch class identifier.
 * @param inputFilesPath {@link String} the path for input files to be processed.
 * @param batchClassPPService {@link PluginPropertiesService} the service to extract properties of plugin.
 * @param barcodeService {@link BarcodeService} the service for performing bar code classifications.
 * @param listOfPages {@link List<Page>} the list of pages to be processed.
 * @return {@link List<Page>} the updated list of pages.
 * @throws DCMAException
 * @throws DCMAApplicationException
 */
private List<Page> barcodeClassificationAPI(String batchClassID, String inputFilesPath,
        PluginPropertiesService batchClassPPService, BarcodeService barcodeService, List<Page> listOfPages,
        RegexService regexService) throws DCMAException, DCMAApplicationException {
    Map<BarcodeProperties, String> batchClassConfigMap = new HashMap<BarcodeProperties, String>();
    try {
        batchClassConfigMap.put(BarcodeProperties.BARCODE_VALID_EXTNS, batchClassPPService.getPropertyValue(
                batchClassID, ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.BARCODE_VALID_EXTNS));
        batchClassConfigMap.put(BarcodeProperties.BARCODE_READER_TYPES, batchClassPPService.getPropertyValue(
                batchClassID, ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.BARCODE_READER_TYPES));
        batchClassConfigMap.put(BarcodeProperties.MAX_CONFIDENCE, batchClassPPService.getPropertyValue(
                batchClassID, ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.MAX_CONFIDENCE));
        batchClassConfigMap.put(BarcodeProperties.MIN_CONFIDENCE, batchClassPPService.getPropertyValue(
                batchClassID, ICommonConstants.BARCODE_READER_PLUGIN, BarcodeProperties.MIN_CONFIDENCE));
    } catch (NullPointerException nullPointerException) {
        LOGGER.error("Exception in fetching the properties for Barcode plugin. " + nullPointerException);
        nullPointerException.printStackTrace();
        throw new DCMAException(
                "Problem fetching the properties of Barcode plugin. Please verify the plugin in batch class with identifier: "
                        + batchClassID);
    }
    // SearchClassificationService searchClassificationService = this.getSingleBeanOfType(SearchClassificationService.class);
    // ocrInputFiles(batchClassID, inputFilesPath, searchClassificationService, false);
    ObjectFactory objectFactory = new ObjectFactory();
    CustomFileFilter filter = new CustomFileFilter(false, FileType.TIF.getExtension());
    String listOfFiles[] = new File(inputFilesPath).list(filter);

    List<Document> xmlDocuments = new ArrayList<Document>();
    Document doc = objectFactory.createDocument();
    Pages pages = new Pages();
    List<Page> pageList = pages.getPage();
    if (null != listOfPages) {
        // if still value is null then we have to check for pages part.
        pageList.addAll(listOfPages);
    } else {
        int pageID = 0;
        for (String page : listOfFiles) {
            if (new File(inputFilesPath + File.separator + page).isFile() && !page.contains("_th.")) {
                Page pageType = objectFactory.createPage();
                pageType.setIdentifier(EphesoftProperty.PAGE.getProperty() + pageID);
                // String pageName = EphesoftStringUtil.concatenate(page.substring(0, page.indexOf("-0")), FileType.TIF
                // .getExtensionWithDot());
                pageType.setNewFileName(page);
                pageType.setHocrFileName(page.substring(0, page.indexOf(".tif")) + "_HOCR.xml");
                pageType.setOldFileName(page);
                pageID++;
                pageList.add(pageType);
            }
        }

    }
    xmlDocuments.add(doc);
    doc.setPages(pages);
    String batchInstanceIdentifier = new File(inputFilesPath).getName() + Math.random();
    try {
        barcodeService.extractPageBarCodeAPI(xmlDocuments, batchInstanceIdentifier, inputFilesPath,
                batchClassConfigMap);
    } catch (DCMAException dcmaException) {
        LOGGER.error("Exception in fetching the properties for Barcode plugin. " + dcmaException);
        dcmaException.printStackTrace();
        throw new DCMAApplicationException("Could not generate the confidence for barcode extraction.");
    }
    // addition of KV_PP_plugin results in barcode.
    try {
        regexService.regexPPReaderAPI(batchClassID, xmlDocuments, inputFilesPath);
    } catch (DCMAException dcmaException) {
        LOGGER.error("Exception in executing KV Page Process plugin. " + dcmaException);
        dcmaException.printStackTrace();
    }
    return pageList;
}

From source file:org.sample.whiteboardapp.MyWhiteboard.java

@OnMessage
public void broadcastFigure(Figure figure, Session session) throws IOException, EncodeException {
    System.out.println("broadcastFigure: " + figure);
    JSONObject coordinates = new JSONObject();
    JSONArray lat_json = new JSONArray();
    JSONArray long_json = new JSONArray();
    try {// www.j  a  v  a 2 s . c  o m
        /*   FileInputStream in = new FileInputStream("C:\\Users\\Nirmit Shah\\Desktop\\mapsapp_ec504\\location.txt");
           BufferedReader br = new BufferedReader(new InputStreamReader(in));*/
        //sample values
        try {
            double latitude = figure.getJson().getJsonObject("coords").getJsonNumber("Latitude").doubleValue();
            double longitude = figure.getJson().getJsonObject("coords").getJsonNumber("Longitude")
                    .doubleValue();
            double[] coord = { latitude, longitude };
            coordinates = findKNN(coord, root, 1000);
        } catch (NullPointerException e) {
            double max_lat = figure.getJson().getJsonObject("coords").getJsonObject("North_east")
                    .getJsonNumber("lat").doubleValue();
            double max_lng = figure.getJson().getJsonObject("coords").getJsonObject("North_east")
                    .getJsonNumber("lng").doubleValue();
            double min_lat = figure.getJson().getJsonObject("coords").getJsonObject("South_west")
                    .getJsonNumber("lat").doubleValue();
            double min_lng = figure.getJson().getJsonObject("coords").getJsonObject("South_west")
                    .getJsonNumber("lng").doubleValue();
            double[] max = { max_lat, min_lng };
            double[] min = { min_lat, max_lng };
            System.out.println(max_lat + " " + min_lng);
            Vector<Node> v = new Vector();
            rsearch(min, max, root, v);
            for (int i = 0; i < v.size(); i++) {
                Node x = v.get(i);
                // System.out.println(x.point[0] + " "+ x.point[1]);
                lat_json.add(x.point[0]);
                long_json.add(x.point[1]);
            }
            coordinates.put("latitude", lat_json);
            coordinates.put("longitude", long_json);
        }
        /*   String strLine;
           LinkedHashMap<Area, Double> newmap = new LinkedHashMap<Area, Double>();
           while ((strLine = br.readLine()) != null) {
        String[] line = strLine.split("\t");
        double lat = Math.abs(Double.valueOf(line[2])) - latitude;
        double lon = Math.abs(Double.valueOf(line[3])) - longitude;
        double radius = Math.sqrt((Math.pow(lat, 2) + (Math.pow(lon, 2))));
        if (radius != 0) {
            if (!map.isEmpty()) {
                Iterator it = map.entrySet().iterator();
                Boolean found = false;
                newmap.clear();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    if ((Double) pair.getValue() >= radius && radius != 0) {
                        found = true;
                        newmap.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
                        if (newmap.size() < 10) {
                            newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                            while (it.hasNext() && newmap.size() < 10) {
                                pair = (Map.Entry) it.next();
                                newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                            }
                        }
                        map = (LinkedHashMap<Area, Double>) newmap.clone();
                        break;
                    } else {
                        newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                    }
                }
                if (!found && map.size() < 10) {
                    map.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
                }
            } else {
                map.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
            }
        }
           }
           in.close();
           Iterator it = map.entrySet().iterator();
           while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        String[] latlong = pair.getKey().toString().split(":") ;
        String lat1 = latlong[1];
        String long1 = latlong[3];
        lat_json.add(lat1);
        long_json.add(long1);                
           }
           coordinates.put("latitude", lat_json);
           coordinates.put("longitude", long_json);*/
        figure.setJson(Json.createReader(new StringReader(coordinates.toString())).readObject());
        RemoteEndpoint.Basic other = session.getBasicRemote();
        other.sendObject(figure);
        System.out.println("sent");
    } catch (Exception e) {
        System.out.println("here");
        e.printStackTrace();
    }

}

From source file:org.rti.zcore.dar.remote.ReportHelper.java

/**
 * Update report value and saves report to an Excel file.
 * @param identifier/*from w w  w . j  a  va  2 s  . c  o  m*/
 * @param reportName
 * @param value
 * @param isFacilityReport
 * @return
 */
public static String updateReport(String identifier, String reportName, String value, Boolean isFacilityReport)
        throws FileNotFoundException {
    String result = "";
    WebContext exec = WebContextFactory.get();
    String username = null;
    SessionUtil zeprs_session = null;
    Site site = null;
    String siteAbbrev = null;
    try {
        username = exec.getHttpServletRequest().getUserPrincipal().getName();
    } catch (NullPointerException e) {
        // unit testing - it's ok...
        username = "demo";
    }
    HttpSession session = exec.getSession();
    try {
        zeprs_session = (SessionUtil) session.getAttribute("zeprs_session");
    } catch (Exception e) {
        // unit testing - it's ok...
    }
    try {
        ClientSettings clientSettings = zeprs_session.getClientSettings();
        site = clientSettings.getSite();
        siteAbbrev = site.getAbbreviation();
    } catch (SessionUtil.AttributeNotFoundException e) {
        log.error(e);
    } catch (NullPointerException e) {
        // it's ok - unit testing
        siteAbbrev = "test";
    }

    String parentField = null;
    String childField = null;

    if (identifier.equals("Save") || identifier.equals("SaveNext")) {

    } else {
        String[] identArray = identifier.split("\\.");
        parentField = identArray[0];
        childField = identArray[1];
    }

    Register report = null;
    String className = "org.rti.zcore.dar.report." + StringManipulation.fixClassname(reportName);
    Class clazz = null;
    try {
        clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
        log.error(e);
    }
    try {
        report = (Register) clazz.newInstance();
    } catch (InstantiationException e) {
        log.error(e);
    } catch (IllegalAccessException e) {
        log.error(e);
    }

    if (identifier.equals("Save") || identifier.equals("SaveNext") || value != null) {
        Integer valueInt = null;
        report = SessionUtil.getInstance(session).getReports().get(reportName);
        String totalIdent = "";
        String reportFileName = report.getReportFileName();
        String pathXml = Constants.ARCHIVE_PATH + site.getAbbreviation() + "/reports/" + reportFileName
                + ".xml";
        String pathExcel = Constants.ARCHIVE_PATH + site.getAbbreviation() + "/reports/" + reportFileName
                + ".xls";
        String bdate = report.getBeginDate().toString();
        String edate = report.getEndDate().toString();
        String siteId = String.valueOf(report.getSiteId());
        String jsessionId = session.getId();
        String[] identifierArray = identifier.split("\\.");
        int len = identifierArray.length;
        String keyForMap = null;
        try {
            if (identifier.equals("Save")) {
                result = "Report saved at " + pathExcel;
            } else if (identifier.equals("SaveNext")) {
                String reportId = null;
                if (reportName.equals("CDRRArtReport")) {
                    if ((isFacilityReport != null) && (isFacilityReport == Boolean.TRUE)) {
                        reportId = "7";
                        result = "/dar/ChooseReportAction.do;jsessionid=" + jsessionId + "?bdate=" + bdate
                                + "&edate=" + edate + "&siteId=" + siteId + "&report=" + reportId
                                + "&isCombinedReport=1&isFacilityReport=1";
                    } else {
                        // Skipping CDRROIReport
                        reportId = "6";
                        result = "/dar/ChooseReportAction.do;jsessionid=" + jsessionId + "?bdate=" + bdate
                                + "&edate=" + edate + "&siteId=" + siteId + "&report=" + reportId
                                + "&isCombinedReport=1";
                    }
                } else if (reportName.equals("CDRROIReport")) {
                    reportId = "6";
                    result = "/dar/ChooseReportAction.do;jsessionid=" + jsessionId + "?bdate=" + bdate
                            + "&edate=" + edate + "&siteId=" + siteId + "&report=" + reportId
                            + "&isCombinedReport=1&isFacilityReport=1";
                } else {
                    if ((isFacilityReport != null) && (isFacilityReport == Boolean.TRUE)) {
                        result = "/dar/reports/combined/gen.do;jsessionid=" + jsessionId
                                + "?isFacilityReport=1";
                    } else {
                        result = "/dar/reports/combined/gen.do;jsessionid=" + jsessionId;
                    }
                }
            } else {
                try {
                    valueInt = Integer.valueOf(value);
                } catch (NumberFormatException e) {
                    try {
                        throw new PersistenceException(
                                "This input field requires an integer value (e.g.: 55). You entered : " + value,
                                e, false);
                    } catch (PersistenceException e1) {
                        return result = identifier + "=" + "Error:" + e1.getMessage();
                    }
                }

                if (identifier.contains("regimenReportMap")) {
                    keyForMap = identifierArray[len - 1];
                    // should be newEstimatedArtPatients.
                    String parentObjectName = identifier
                            .replace("." + identifierArray[len - 2] + "." + keyForMap, "");
                    try {
                        Object parent = null;
                        parent = PropertyUtils.getNestedProperty(report, parentObjectName);
                        PropertyUtils.setMappedProperty(parent, "regimenReportMap", keyForMap, valueInt);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else if (identifier.contains("stockReportMap")) {
                    keyForMap = identifierArray[len - 2];
                    //String propertyName = identifierArray[len-1];
                    // parentObjectName should be stockReportMap
                    //String parentObjectName = identifier.replace("." +  keyForMap + "." + childField, "");
                    try {
                        PropertyUtils.setNestedProperty(report, identifier, valueInt);
                        //Object parent = PropertyUtils.getNestedProperty(report, parentObjectName);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    PropertyUtils.setProperty(report, identifier, valueInt);
                }
                //valueInt = (Integer) PropertyUtils.getProperty(report, identifier);
                /*HashMap<String, Integer> regimenReportMap = report.get
                regimenReportMap.put(key, amount);*/

                // CDRR (Stock) Reports
                if (parentField.equals("stockReportMap")) {
                    String propertyField = identifierArray[2];
                    if (propertyField.equals("quantityRequiredNewPatients")) {
                        String quantityRequiredResupplyIdent = identifier.replace(propertyField,
                                "quantityRequiredResupply");
                        Integer quantityRequiredResupply = 0;
                        if (PropertyUtils.getNestedProperty(report, quantityRequiredResupplyIdent) != null) {
                            quantityRequiredResupply = (Integer) PropertyUtils.getNestedProperty(report,
                                    quantityRequiredResupplyIdent);
                        }
                        Integer totalQuantityRequired = quantityRequiredResupply + valueInt;
                        String totalQuantityRequiredIdent = identifier.replace(propertyField,
                                "totalQuantityRequired");
                        try {
                            PropertyUtils.setNestedProperty(report, totalQuantityRequiredIdent, valueInt);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        result = identifier + "=" + valueInt + ";" + totalQuantityRequiredIdent + "="
                                + totalQuantityRequired;
                    } else {
                        result = "0=0;" + identifier + "=" + valueInt;
                    }
                    // Regimen report
                } else if (parentField.equals("newEstimatedArtPatients")) {
                    //String quantityRequiredResupplyIdent = "artRegimenReport." + childField;
                    Integer quantityRequiredResupply = 0;
                    /*if (PropertyUtils.getProperty(report, quantityRequiredResupplyIdent) != null) {
                       quantityRequiredResupply = (Integer) PropertyUtils.getProperty(report, quantityRequiredResupplyIdent);
                    }*/

                    if (PropertyUtils.getMappedProperty(report, "regimenReportMap", keyForMap) != null) {
                        //value = regimenReportMap.get("regimen" + regimenCode);
                        quantityRequiredResupply = (Integer) PropertyUtils.getMappedProperty(report,
                                "regimenReportMap", keyForMap);
                    }

                    totalIdent = "totalEstimatedArtPatients." + childField + "." + keyForMap;
                    Integer totalQuantityRequired = quantityRequiredResupply + valueInt;

                    //String parentObjectName = identifier.replace("." +  identifierArray[len-2] + "." + keyForMap, "");
                    //Object parent = PropertyUtils.getNestedProperty(report, parentObjectName);

                    Object parent = PropertyUtils.getNestedProperty(report, "totalEstimatedArtPatients");
                    PropertyUtils.setMappedProperty(parent, "regimenReportMap", keyForMap,
                            totalQuantityRequired);
                    //PropertyUtils.setProperty(report, totalIdent, totalQuantityRequired);
                    result = identifier + "=" + valueInt + ";" + totalIdent + "=" + totalQuantityRequired;
                } else if (parentField.equals("totalQuantityRequired")) {
                    result = "0=0;" + identifier + "=" + valueInt;
                }
            }
            try {
                ReportOutput.outputReport(reportName, report, clazz, pathXml, pathExcel, null);
            } catch (FileNotFoundException e) {
                result = identifier + "=" + valueInt + ";" + totalIdent + "="
                        + "Error: the Excel file for this report is open. Please close.";
            } catch (IOException e) {
                log.debug(e);
            } catch (WrappedRuntimeException e) {
                log.error(e);
                //e.printStackTrace();
            } catch (TransformerException e) {
                log.error(e);
            }
        } catch (IllegalAccessException e) {
            log.debug(e);
        } catch (InvocationTargetException e) {
            log.debug(e);
        } catch (NoSuchMethodException e) {
            log.debug(e);
        }
        //BeanUtils.setProperty(parent, childField, value);
    } else {
        result = identifier + "=" + "Error: No value entered.";
    }
    return result;
}

From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java

public String addDocument() {
    Map sessionAttributes = ActionContext.getContext().getSession();

    System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + document.getDocumentName());
    System.out.println("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + document.getReferenceNumber());
    System.out.println("dddddddddddddddddddddddddddddd" + document.getReferenceId());
    System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + documentStageParam);
    System.out.println("fffffffffffffffffffffffffffffff" + authorizedRecipient);
    System.out.println("gggggggggggggggggggggggggggggg" + repContactIdParam);
    System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhh" + shipperContactIdParam);
    System.out.println("iiiiiiiiiiiiiiiiiiiiiiiiiiiiii" + consigneeContactIdParam);

    List<String> vendorSea = new ArrayList<String>();
    List<String> vendorOrigin = new ArrayList<String>();
    List<String> vendorDestination = new ArrayList<String>();
    List<Documents> bookingDocuments = documentsService.findDocumentsByOrderId(document.getReferenceId());

    Orders orderEntity = orderService.findOrdersById(document.getReferenceId());
    order = transformToOrderFormBean(orderEntity);
    List<OrderItems> orderItemsList = operationsService.findAllOrderItemsByOrderId(document.getReferenceId());

    // Shipping vendors set will be stored in VendorSea variable
    Integer vendorSeaCount = 0;/*  w  w w .j av a  2 s  .c  o  m*/
    for (OrderItems everyItem : orderItemsList) {
        if (vendorSea.isEmpty()) {
            vendorSea.add(everyItem.getVendorSea());
            vendorSeaCount = vendorSeaCount + 1;
        } else {
            if (!vendorSea.contains(everyItem.getVendorSea())) {
                vendorSea.add(everyItem.getVendorSea());
                vendorSeaCount = vendorSeaCount + 1;
            }
        }
    }

    // Origin vendors set will be stored in VendorOrigin Variable
    Integer vendorOriginCount = 0;
    for (OrderItems everyItem : orderItemsList) {
        if (vendorOrigin.isEmpty()) {
            vendorOrigin.add(everyItem.getVendorOrigin());
            vendorOriginCount = vendorOriginCount + 1;
        } else {
            if (!vendorOrigin.contains(everyItem.getVendorOrigin())) {
                vendorOrigin.add(everyItem.getVendorOrigin());
                vendorOriginCount = vendorOriginCount + 1;
            }
        }
    }

    // Destination vendors set will be stored in VendorDestination Variable
    Integer vendorDestinationCount = 0;
    for (OrderItems everyItem : orderItemsList) {
        if (vendorDestination.isEmpty()) {
            vendorDestination.add(everyItem.getVendorDestination());
            vendorDestinationCount = vendorDestinationCount + 1;
        } else {
            if (!vendorDestination.contains(everyItem.getVendorDestination())) {
                vendorDestination.add(everyItem.getVendorDestination());
                vendorDestinationCount = vendorDestinationCount + 1;
            }
        }
    }

    // Count Proforma Bill of Lading documents
    Integer countProforma = 0;
    for (Documents ProformaDocs : bookingDocuments) {
        if (ProformaDocs.getDocumentName().equals("PROFORMA BILL OF LADING")) {
            countProforma = countProforma + 1;
        }
    }

    // Count House Waybill Origin documents
    Integer countWaybillOrigin = 0;
    for (Documents waybillOriginDocs : bookingDocuments) {
        if (waybillOriginDocs.getDocumentName().equals("HOUSE WAYBILL ORIGIN")) {
            countWaybillOrigin = countWaybillOrigin + 1;
        }
    }

    String documentName = document.getDocumentName().toUpperCase();

    if (documentName.equals("BOOKING REQUEST FORM") || documentName.equals("HOUSE WAYBILL ORIGIN")
            || documentName.equals("PROFORMA BILL OF LADING")
            || documentName.equals("HOUSE WAYBILL DESTINATION")) {
        clearErrorsAndMessages();
        addActionError("Document cannot be created!");

        return INPUT;

    } else if (documentName.equals("HOUSE BILL OF LADING")) {

        // will delete all existing House Bill of Lading document
        for (Documents freightDocumentElem : bookingDocuments) {
            String docName = freightDocumentElem.getDocumentName().toUpperCase();
            if (docName.equals("HOUSE BILL OF LADING")) {
                Documents documentEntity = documentsService
                        .findDocumentById(freightDocumentElem.getDocumentId());
                documentsService.deleteDocument(documentEntity);
            }
        }
        // Add House Bill of Lading based on number for Proforma Bill of Lading

        for (String seaVendor : vendorSea) {
            if (seaVendor != null) {

                Documents documentEntity = new Documents();
                Client client = clientService.findClientById(getClientId().toString());

                documentEntity.setClient(client);
                documentEntity.setDocumentName(documentName);
                documentEntity.setReferenceId(document.getReferenceId());
                documentEntity.setReferenceTable("ORDERS");
                documentEntity.setOrderNumber(
                        orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                documentEntity.setCreatedDate(new Date());
                documentEntity.setVendorCode(seaVendor);

                if (documentStageParam.equals("OUTBOUND")) {
                    documentEntity.setOutboundStage(1);
                    documentEntity.setDocumentProcessed(0);
                    documentEntity.setDocumentStatus("OUTBOUND");
                } else if (documentStageParam.equals("INBOUND")) {
                    documentEntity.setInboundStage(1);
                    documentEntity.setDocumentProcessed(1);
                    documentEntity.setDocumentStatus("INBOUND");
                } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                    documentEntity.setDocumentProcessed(2);
                    documentEntity.setFinalOutboundStage(1);
                    documentEntity.setDocumentStatus("FINAL OUTBOUND");
                } else {
                    documentEntity.setFinalInboundStage(1);
                    documentEntity.setDocumentProcessed(3);
                    documentEntity.setDocumentStatus("FINAL INBOUND");
                }

                documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                documentEntity.setReferenceNumber(document.getReferenceNumber());
                documentEntity.setDocumentComments(document.getDocumentComments());
                String documentCode = documentsService.findNextControlNo(getClientId(), "HBL"); // HBL for House Bill of Lading Form Document Code
                documentEntity.setControlNumber(documentCode);

                documentEntity.setReferenceNumber(documentCode.replace("HBL-", ""));

                documentsService.addDocuments(documentEntity);

            } else {
                clearErrorsAndMessages();
                addActionError("No Shipping vendor set!");

                return INPUT;
            }
        }

    } else if (documentName.equals("MASTER BILL OF LADING")) {

        // will delete all existing Master Bill of Lading document
        for (Documents freightDocumentElem : bookingDocuments) {
            String docName = freightDocumentElem.getDocumentName().toUpperCase();
            if (docName.equals("MASTER BILL OF LADING")) {
                Documents documentEntity = documentsService
                        .findDocumentById(freightDocumentElem.getDocumentId());
                documentsService.deleteDocument(documentEntity);
            }
        }

        // Add Master Bill of Lading based on number for Proforma Bill of Lading
        for (String seaVendor : vendorSea) {
            if (seaVendor != null) {

                Documents documentEntity = new Documents();
                Client client = clientService.findClientById(getClientId().toString());

                documentEntity.setClient(client);
                documentEntity.setDocumentName(documentName);
                documentEntity.setReferenceId(document.getReferenceId());
                documentEntity.setReferenceTable("ORDERS");
                documentEntity.setOrderNumber(
                        orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                documentEntity.setCreatedDate(new Date());
                documentEntity.setVendorCode(seaVendor);

                if (documentStageParam.equals("OUTBOUND")) {
                    documentEntity.setOutboundStage(1);
                    documentEntity.setDocumentProcessed(0);
                    documentEntity.setDocumentStatus("OUTBOUND");
                } else if (documentStageParam.equals("INBOUND")) {
                    documentEntity.setInboundStage(1);
                    documentEntity.setDocumentProcessed(1);
                    documentEntity.setDocumentStatus("INBOUND");
                } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                    documentEntity.setDocumentProcessed(2);
                    documentEntity.setFinalOutboundStage(1);
                    documentEntity.setDocumentStatus("FINAL OUTBOUND");
                } else {
                    documentEntity.setFinalInboundStage(1);
                    documentEntity.setDocumentProcessed(3);
                    documentEntity.setDocumentStatus("FINAL INBOUND");
                }

                documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                documentEntity.setReferenceNumber(document.getReferenceNumber());
                documentEntity.setDocumentComments(document.getDocumentComments());
                String documentCode = documentsService.findNextControlNo(getClientId(), "MBL"); // MBL for Master Bill of Lading Form Document Code
                documentEntity.setControlNumber(documentCode);

                /*documentEntity.setReferenceNumber(documentCode.replace("MBL-",""));*/

                documentsService.addDocuments(documentEntity);

            } else {
                clearErrorsAndMessages();
                addActionError("No Shipping vendor set!");

                return INPUT;
            }
        }

    } else if (documentName.equals("MASTER WAYBILL ORIGIN")) {

        // will delete all existing House Waybill Origin documents
        for (Documents freightDocumentElem : bookingDocuments) {
            String docName = freightDocumentElem.getDocumentName().toUpperCase();
            if (docName.equals("MASTER WAYBILL ORIGIN")) {
                Documents documentEntity = documentsService
                        .findDocumentById(freightDocumentElem.getDocumentId());
                documentsService.deleteDocument(documentEntity);
            }
        }

        // Add Master Waybill Origin based on number for House Waybill Origin
        for (String originVendor : vendorOrigin) {
            if (originVendor != null) {

                Documents documentEntity = new Documents();
                Client client = clientService.findClientById(getClientId().toString());

                documentEntity.setClient(client);
                documentEntity.setDocumentName(documentName);
                documentEntity.setReferenceId(document.getReferenceId());
                documentEntity.setReferenceTable("ORDERS");
                documentEntity.setOrderNumber(
                        orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                documentEntity.setCreatedDate(new Date());
                documentEntity.setVendorCode(originVendor);

                if (documentStageParam.equals("OUTBOUND")) {
                    documentEntity.setOutboundStage(1);
                    documentEntity.setDocumentProcessed(0);
                    documentEntity.setDocumentStatus("OUTBOUND");
                } else if (documentStageParam.equals("INBOUND")) {
                    documentEntity.setInboundStage(1);
                    documentEntity.setDocumentProcessed(1);
                    documentEntity.setDocumentStatus("INBOUND");
                } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                    documentEntity.setDocumentProcessed(2);
                    documentEntity.setFinalOutboundStage(1);
                    documentEntity.setDocumentStatus("FINAL OUTBOUND");
                } else {
                    documentEntity.setFinalInboundStage(1);
                    documentEntity.setDocumentProcessed(3);
                    documentEntity.setDocumentStatus("FINAL INBOUND");
                }

                documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                documentEntity.setReferenceNumber(document.getReferenceNumber());
                documentEntity.setDocumentComments(document.getDocumentComments());
                String documentCode = documentsService.findNextControlNo(getClientId(), "MWO"); // MWO for Master Waybill Origin Form Document Code
                documentEntity.setControlNumber(documentCode);

                /*documentEntity.setReferenceNumber(documentCode.replace("MWO-",""));*/

                documentsService.addDocuments(documentEntity);

            } else {
                clearErrorsAndMessages();
                addActionError("No Origin vendor set!");

                return INPUT;
            }
        }

    } else if (documentName.equals("MASTER WAYBILL DESTINATION")) {

        // will delete all existing House Waybill Destination documents
        for (Documents freightDocumentElem : bookingDocuments) {
            String docName = freightDocumentElem.getDocumentName().toUpperCase();
            if (docName.equals("MASTER WAYBILL DESTINATION")) {
                Documents documentEntity = documentsService
                        .findDocumentById(freightDocumentElem.getDocumentId());
                documentsService.deleteDocument(documentEntity);
            }
        }

        // Add Master Waybill Destination based on number for House Waybill Destination
        for (String destinationVendor : vendorDestination) {
            if (destinationVendor != null) {

                Documents documentEntity = new Documents();
                Client client = clientService.findClientById(getClientId().toString());

                documentEntity.setClient(client);
                documentEntity.setDocumentName(documentName);
                documentEntity.setReferenceId(document.getReferenceId());
                documentEntity.setReferenceTable("ORDERS");
                documentEntity.setOrderNumber(
                        orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                documentEntity.setCreatedDate(new Date());
                documentEntity.setVendorCode(destinationVendor);

                if (documentStageParam.equals("OUTBOUND")) {
                    documentEntity.setOutboundStage(1);
                    documentEntity.setDocumentProcessed(0);
                    documentEntity.setDocumentStatus("OUTBOUND");
                } else if (documentStageParam.equals("INBOUND")) {
                    documentEntity.setInboundStage(1);
                    documentEntity.setDocumentProcessed(1);
                    documentEntity.setDocumentStatus("INBOUND");
                } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                    documentEntity.setDocumentProcessed(2);
                    documentEntity.setFinalOutboundStage(1);
                    documentEntity.setDocumentStatus("FINAL OUTBOUND");
                } else {
                    documentEntity.setFinalInboundStage(1);
                    documentEntity.setDocumentProcessed(3);
                    documentEntity.setDocumentStatus("FINAL INBOUND");
                }

                documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                documentEntity.setReferenceNumber(document.getReferenceNumber());
                documentEntity.setDocumentComments(document.getDocumentComments());
                String documentCode = documentsService.findNextControlNo(getClientId(), "MWD"); // MWD for Master Waybill Destination Form Document Code
                documentEntity.setControlNumber(documentCode);

                /*documentEntity.setReferenceNumber(documentCode.replace("MWD-",""));*/

                documentsService.addDocuments(documentEntity);

            } else {
                clearErrorsAndMessages();
                addActionError("No Destination vendor set!");

                return INPUT;
            }
        }

    } else if (documentName.equals("AUTHORIZATION TO WITHDRAW")) {

        if (repContactIdParam == null || shipperContactIdParam == null || consigneeContactIdParam == null) {
            documentflag = 8; // Shows error that no document was checked
            sessionAttributes.put("documentflag", documentflag);
            return INPUT;
        }

        Integer vendorIdHolder = 0;
        Driver contactEntity = vendorService.findDriverById(repContactIdParam);

        if (contactEntity != null) {
            vendorIdHolder = contactEntity.getVendorId();
        } else {
            Contacts contactElem = vendorService.findContactById(repContactIdParam);
            vendorIdHolder = contactElem.getReferenceId();
        }

        Vendor vendorEntity = vendorService.findVendorById(vendorIdHolder);

        for (OrderItems orderItemElem : orderItemsList) {

            if (documentStageParam.equals("OUTBOUND")) {

                try {
                    if (orderItemElem.getVendorOrigin().equals(vendorEntity.getVendorCode())
                            || vendorEntity.getVendorCode().equals("ELC")) {

                        // will delete ATW document if it exists
                        for (Documents freightDocumentElem : bookingDocuments) {
                            String docName = freightDocumentElem.getDocumentName().toUpperCase();
                            if (docName.equals("AUTHORIZATION TO WITHDRAW")) {
                                Documents documentEntity = documentsService
                                        .findDocumentById(freightDocumentElem.getDocumentId());

                                if (documentEntity != null) {

                                    if (vendorEntity.getVendorCode().equals("ELC")) {

                                        for (OrderItems orderItemInsideElem : orderItemsList) {
                                            if (documentEntity.getVendorCode().equals("ELC")
                                                    && documentEntity.getOrderItemId()
                                                            .equals(orderItemInsideElem.getOrderItemId())
                                                    && documentEntity.getDocumentStatus().equals("OUTBOUND")) {
                                                documentsService.deleteDocument(documentEntity);
                                            }
                                        }

                                    } else {

                                        if (documentEntity.getVendorCode()
                                                .equals(orderItemElem.getVendorOrigin())
                                                && documentEntity.getOrderItemId()
                                                        .equals(orderItemElem.getOrderItemId())) {
                                            documentsService.deleteDocument(documentEntity);
                                        }

                                    }
                                }
                            }
                        }

                    }

                } catch (NullPointerException npe) {

                    System.out.println("vendor origin is null");
                    npe.printStackTrace();

                } finally {

                    // will delete ATW document if it exists
                    for (Documents freightDocumentElem : bookingDocuments) {
                        String docName = freightDocumentElem.getDocumentName().toUpperCase();
                        if (docName.equals("AUTHORIZATION TO WITHDRAW")) {
                            Documents documentEntity = documentsService
                                    .findDocumentById(freightDocumentElem.getDocumentId());

                            if (documentEntity != null) {

                                for (OrderItems orderItemInsideElem : orderItemsList) {
                                    if (documentEntity.getVendorCode().equals("ELC")
                                            && documentEntity.getDocumentStatus().equals("OUTBOUND")) {
                                        documentsService.deleteDocument(documentEntity);
                                    }
                                }

                            }
                        }
                    }

                    Documents documentEntity = new Documents();
                    Client client = clientService.findClientById(getClientId().toString());

                    documentEntity.setClient(client);
                    documentEntity.setDocumentName(documentName);
                    documentEntity.setReferenceId(document.getReferenceId());
                    documentEntity.setReferenceTable("ORDERS");
                    documentEntity.setOrderNumber(
                            orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                    documentEntity.setCreatedDate(new Date());
                    documentEntity.setOrderItemId(orderItemElem.getOrderItemId());
                    documentEntity.setVendorCode(vendorEntity.getVendorCode());

                    documentEntity.setRepContact(repContactIdParam);
                    documentEntity.setOriContact(shipperContactIdParam);
                    documentEntity.setDesContact(consigneeContactIdParam);

                    if (documentStageParam.equals("OUTBOUND")) {
                        documentEntity.setOutboundStage(1);
                        documentEntity.setDocumentProcessed(0);
                        documentEntity.setDocumentStatus("OUTBOUND");
                    } else if (documentStageParam.equals("INBOUND")) {
                        documentEntity.setInboundStage(1);
                        documentEntity.setDocumentProcessed(1);
                        documentEntity.setDocumentStatus("INBOUND");
                    } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                        documentEntity.setDocumentProcessed(2);
                        documentEntity.setFinalOutboundStage(1);
                        documentEntity.setDocumentStatus("FINAL OUTBOUND");
                    } else {
                        documentEntity.setFinalInboundStage(1);
                        documentEntity.setDocumentProcessed(3);
                        documentEntity.setDocumentStatus("FINAL INBOUND");
                    }

                    documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                    documentEntity.setReferenceNumber(document.getReferenceNumber());
                    documentEntity.setDocumentComments(document.getDocumentComments());
                    String documentCode = documentsService.findNextControlNo(getClientId(), "ATW"); // ATW for Authorization to Withdraw Form Document Code
                    documentEntity.setControlNumber(documentCode);

                    documentEntity.setReferenceNumber(documentCode.replace("ATW-", ""));
                    documentEntity.setDocumentType("EMPTY");

                    documentsService.addDocuments(documentEntity);
                }

            } else if (documentStageParam.equals("FINAL OUTBOUND")) {

                try {
                    if (orderItemElem.getVendorDestination().equals(vendorEntity.getVendorCode())
                            || vendorEntity.getVendorCode().equals("ELC")) {

                        // will delete ATW document if it exists
                        for (Documents freightDocumentElem : bookingDocuments) {
                            String docName = freightDocumentElem.getDocumentName().toUpperCase();
                            if (docName.equals("AUTHORIZATION TO WITHDRAW")) {
                                Documents documentEntity = documentsService
                                        .findDocumentById(freightDocumentElem.getDocumentId());

                                if (documentEntity != null) {

                                    if (vendorEntity.getVendorCode().equals("ELC")) {

                                        for (OrderItems orderItemInsideElem : orderItemsList) {
                                            if (documentEntity.getVendorCode().equals("ELC")
                                                    && documentEntity.getOrderItemId()
                                                            .equals(orderItemInsideElem.getOrderItemId())
                                                    && documentEntity.getDocumentStatus()
                                                            .equals("FINAL OUTBOUND")) {
                                                documentsService.deleteDocument(documentEntity);
                                            }
                                        }

                                    } else {

                                        if (documentEntity.getVendorCode()
                                                .equals(orderItemElem.getVendorDestination())
                                                && documentEntity.getOrderItemId()
                                                        .equals(orderItemElem.getOrderItemId())) {
                                            documentsService.deleteDocument(documentEntity);
                                        }
                                    }
                                }
                            }
                        }

                    }

                } catch (NullPointerException npe) {

                    System.out.println("vendor destination is null");
                    npe.printStackTrace();

                } finally {

                    if (!orderEntity.getServiceType().equals("SHIPPING")) {
                        // will delete ATW document if it exists
                        for (Documents freightDocumentElem : bookingDocuments) {
                            String docName = freightDocumentElem.getDocumentName().toUpperCase();
                            if (docName.equals("AUTHORIZATION TO WITHDRAW")) {
                                Documents documentEntity = documentsService
                                        .findDocumentById(freightDocumentElem.getDocumentId());

                                if (documentEntity != null) {

                                    for (OrderItems orderItemInsideElem : orderItemsList) {
                                        if (documentEntity.getVendorCode().equals("ELC") && documentEntity
                                                .getDocumentStatus().equals("FINAL OUTBOUND")) {
                                            documentsService.deleteDocument(documentEntity);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Documents documentEntity = new Documents();
                    Client client = clientService.findClientById(getClientId().toString());

                    documentEntity.setClient(client);
                    documentEntity.setDocumentName(documentName);
                    documentEntity.setReferenceId(document.getReferenceId());
                    documentEntity.setReferenceTable("ORDERS");
                    documentEntity.setOrderNumber(
                            orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                    documentEntity.setCreatedDate(new Date());
                    documentEntity.setOrderItemId(orderItemElem.getOrderItemId());
                    documentEntity.setVendorCode(vendorEntity.getVendorCode());

                    documentEntity.setRepContact(repContactIdParam);
                    documentEntity.setOriContact(shipperContactIdParam);
                    documentEntity.setDesContact(consigneeContactIdParam);

                    if (documentStageParam.equals("OUTBOUND")) {
                        documentEntity.setOutboundStage(1);
                        documentEntity.setDocumentProcessed(0);
                        documentEntity.setDocumentStatus("OUTBOUND");
                    } else if (documentStageParam.equals("INBOUND")) {
                        documentEntity.setInboundStage(1);
                        documentEntity.setDocumentProcessed(1);
                        documentEntity.setDocumentStatus("INBOUND");
                    } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                        documentEntity.setDocumentProcessed(2);
                        documentEntity.setFinalOutboundStage(1);
                        documentEntity.setDocumentStatus("FINAL OUTBOUND");
                    } else {
                        documentEntity.setFinalInboundStage(1);
                        documentEntity.setDocumentProcessed(3);
                        documentEntity.setDocumentStatus("FINAL INBOUND");
                    }

                    documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                    documentEntity.setReferenceNumber(document.getReferenceNumber());
                    documentEntity.setDocumentComments(document.getDocumentComments());
                    String documentCode = documentsService.findNextControlNo(getClientId(), "ATW"); // ATW for Authorization to Withdraw Form Document Code
                    documentEntity.setControlNumber(documentCode);

                    documentEntity.setReferenceNumber(documentCode.replace("ATW-", ""));
                    documentEntity.setDocumentType("LADEN");

                    documentsService.addDocuments(documentEntity);

                }
            }
        }

    } else if (documentName.equals("ACCEPTANCE RECEIPT")) {

        // will delete all existing Acceptance Receipt documents
        for (Documents freightDocumentElem : bookingDocuments) {
            String docName = freightDocumentElem.getDocumentName().toUpperCase();
            if (docName.equals("ACCEPTANCE RECEIPT")) {
                Documents documentEntity = documentsService
                        .findDocumentById(freightDocumentElem.getDocumentId());
                documentsService.deleteDocument(documentEntity);
            }
        }

        for (String seaVendor : vendorSea) {
            if (seaVendor != null) {

                for (OrderItems orderItemElem : orderItemsList) {

                    Documents documentEntity = new Documents();
                    Client client = clientService.findClientById(getClientId().toString());

                    documentEntity.setClient(client);
                    documentEntity.setDocumentName(documentName);
                    documentEntity.setReferenceId(document.getReferenceId());
                    documentEntity.setReferenceTable("ORDERS");
                    documentEntity.setOrderNumber(
                            orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                    documentEntity.setCreatedDate(new Date());
                    documentEntity.setVendorCode(seaVendor);

                    if (documentStageParam.equals("OUTBOUND")) {
                        documentEntity.setOutboundStage(1);
                        documentEntity.setDocumentProcessed(0);
                        documentEntity.setDocumentStatus("OUTBOUND");
                    } else if (documentStageParam.equals("INBOUND")) {
                        documentEntity.setInboundStage(1);
                        documentEntity.setDocumentProcessed(1);
                        documentEntity.setDocumentStatus("INBOUND");
                    } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                        documentEntity.setDocumentProcessed(2);
                        documentEntity.setFinalOutboundStage(1);
                        documentEntity.setDocumentStatus("FINAL OUTBOUND");
                    } else {
                        documentEntity.setFinalInboundStage(1);
                        documentEntity.setDocumentProcessed(3);
                        documentEntity.setDocumentStatus("FINAL INBOUND");
                    }

                    documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                    documentEntity.setReferenceNumber(document.getReferenceNumber());
                    documentEntity.setDocumentComments(document.getDocumentComments());
                    documentEntity.setOrderItemId(orderItemElem.getOrderItemId());
                    String documentCode = documentsService.findNextControlNo(getClientId(), "ARF"); // ARF for Acceptance Receipt Form Document Code
                    documentEntity.setControlNumber(documentCode);

                    documentEntity.setReferenceNumber(documentCode.replace("ARF-", ""));

                    documentsService.addDocuments(documentEntity);

                }

            } else {
                clearErrorsAndMessages();
                addActionError("No Shipping vendor set!");

                return INPUT;
            }
        }

    } else if (documentName.equals("RELEASE ORDER")) {

        // will delete all existing Release Order documents
        for (Documents freightDocumentElem : bookingDocuments) {
            String docName = freightDocumentElem.getDocumentName().toUpperCase();
            if (docName.equals("RELEASE ORDER")) {
                Documents documentEntity = documentsService
                        .findDocumentById(freightDocumentElem.getDocumentId());
                documentsService.deleteDocument(documentEntity);
            }
        }

        for (String seaVendor : vendorSea) {
            if (seaVendor != null) {

                for (OrderItems orderItemElem : orderItemsList) {

                    Documents documentEntity = new Documents();
                    Client client = clientService.findClientById(getClientId().toString());

                    documentEntity.setClient(client);
                    documentEntity.setDocumentName(documentName);
                    documentEntity.setReferenceId(document.getReferenceId());
                    documentEntity.setReferenceTable("ORDERS");
                    documentEntity.setOrderNumber(
                            orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
                    documentEntity.setCreatedDate(new Date());
                    documentEntity.setVendorCode(seaVendor);

                    if (documentStageParam.equals("OUTBOUND")) {
                        documentEntity.setOutboundStage(1);
                        documentEntity.setDocumentProcessed(0);
                        documentEntity.setDocumentStatus("OUTBOUND");
                    } else if (documentStageParam.equals("INBOUND")) {
                        documentEntity.setInboundStage(1);
                        documentEntity.setDocumentProcessed(1);
                        documentEntity.setDocumentStatus("INBOUND");
                    } else if (documentStageParam.equals("FINAL OUTBOUND")) {
                        documentEntity.setDocumentProcessed(2);
                        documentEntity.setFinalOutboundStage(1);
                        documentEntity.setDocumentStatus("FINAL OUTBOUND");
                    } else {
                        documentEntity.setFinalInboundStage(1);
                        documentEntity.setDocumentProcessed(3);
                        documentEntity.setDocumentStatus("FINAL INBOUND");
                    }

                    documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
                    documentEntity.setReferenceNumber(document.getReferenceNumber());
                    documentEntity.setDocumentComments(document.getDocumentComments());
                    documentEntity.setOrderItemId(orderItemElem.getOrderItemId());
                    String documentCode = documentsService.findNextControlNo(getClientId(), "ROF"); // ROF for Release Order Form Document Code
                    documentEntity.setControlNumber(documentCode);

                    documentEntity.setReferenceNumber(documentCode.replace("ROF-", ""));

                    documentsService.addDocuments(documentEntity);

                }

            } else {
                clearErrorsAndMessages();
                addActionError("No Shipping vendor set!");

                return INPUT;
            }
        }

    } else {

        Documents documentEntity = new Documents();
        Client client = clientService.findClientById(getClientId().toString());

        documentEntity.setClient(client);
        documentEntity.setDocumentName(documentName);
        documentEntity.setReferenceId(document.getReferenceId());
        documentEntity.setReferenceTable("ORDERS");
        documentEntity.setOrderNumber(orderService.findOrdersById(document.getReferenceId()).getOrderNumber());
        documentEntity.setCreatedDate(new Date());

        if (documentStageParam.equals("OUTBOUND")) {
            documentEntity.setOutboundStage(1);
            documentEntity.setDocumentProcessed(0);
            documentEntity.setDocumentStatus("OUTBOUND");
        } else if (documentStageParam.equals("INBOUND")) {
            documentEntity.setInboundStage(1);
            documentEntity.setDocumentProcessed(1);
            documentEntity.setDocumentStatus("INBOUND");
        } else if (documentStageParam.equals("FINAL OUTBOUND")) {
            documentEntity.setDocumentProcessed(2);
            documentEntity.setFinalOutboundStage(1);
            documentEntity.setDocumentStatus("FINAL OUTBOUND");
        } else {
            documentEntity.setFinalInboundStage(1);
            documentEntity.setDocumentProcessed(3);
            documentEntity.setDocumentStatus("FINAL INBOUND");
        }

        documentEntity.setCreatedBy(commonUtils.getUserNameFromSession());
        documentEntity.setReferenceNumber(document.getReferenceNumber());
        documentEntity.setDocumentComments(document.getDocumentComments());

        documentsService.addDocuments(documentEntity);
    }

    sessionAttributes.put("orderIdParam", document.getReferenceId());

    return SUCCESS;
}