Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:org.dcm4chee.web.common.markup.DateTimeLabel.java

License:LGPL

@Override
public IConverter getConverter(Class<?> type) {
    return new IConverter() {

        private static final long serialVersionUID = 1L;

        public Object convertToObject(String value, Locale locale) {
            throw new UnsupportedOperationException();
        }//from ww  w .  ja  v a  2s.c  o m

        public String convertToString(Object value, Locale locale) {

            if (value == null)
                return null;
            Date d = (Date) value;
            String pattern = getTextFormat();
            DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern).withLocale(getLocale())
                    .withPivotYear(2000);
            return withoutTime ? dtf.print(d.getTime()) : dtf.print(d.getTime()) + " " + df.format(d);
        }

    };
}

From source file:org.ddialliance.ddiftp.util.Translator.java

License:Open Source License

/**
 * Format time in milli seconds to an ISO8601 time string<BR>
 * Defined by '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
 * (zzzzzz)?//from w ww .  java2 s . c om
 * 
 * @see http://www.w3.org/TR/xmlschema-2/#dateTime
 * @param time
 *            in milli seconds
 * @return ISO8601 time string
 * @throws DDIFtpException
 */
public static String formatIso8601DateTime(long time) {
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    fmt.withLocale(getLocale());
    fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
    return fmt.print(time);
}

From source file:org.devgateway.eudevfin.sheetexp.iati.transformer.IatiTransformer.java

License:Open Source License

@ServiceActivator(inputChannel = "iatiListExporterChannel")
public Boolean createIatiExportManually(final List<EntityWrapperInterface<CustomFinancialTransaction>> list,
        @Header("outputStream") final OutputStream out, @Header("exportName") final String exportName) {

    final IatiTransformerEngine engine = new IatiTransformerEngine(list);

    final IatiActivities iatiActivities = engine.transform().getIatiActivities();

    final DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis();
    final DateTime now = new DateTime().millisOfSecond().withMinimumValue();
    final XStream xStream = new XStream();

    xStream.processAnnotations(IatiActivities.class);
    xStream.registerConverter(new DateConverter("yyyy-MM-dd", new String[] {}));

    try (final OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-8"))) {
        writer.write(String.format("<iati-activities generated-datetime=\"%s\" version=\"1.04\">",
                formatter.print(now)));
        writer.write("<!-- Generated By EUDEVFIN -->");
        for (final IatiActivity iatiActivity : iatiActivities.getActivities()) {
            final String xml = xStream.toXML(iatiActivity);
            writer.write(xml);/* www  .ja va 2 s. com*/
        }
        writer.write("</iati-activities>");
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.dspace.eperson.Subscribe.java

License:BSD License

/**
 * Sends an email to the given e-person with details of new items in the
 * given collections, items that appeared yesterday. No e-mail is sent if
 * there aren't any new items in any of the collections.
 * /*from   w w w. j a  v a 2  s.c o m*/
 * @param context
 *            DSpace context object
 * @param eperson
 *            eperson to send to
 * @param collections
 *            List of collection IDs (Integers)
 * @param test 
 */
public static void sendEmail(Context context, EPerson eperson, List<Collection> collections, boolean test)
        throws IOException, MessagingException, SQLException {
    // Get a resource bundle according to the eperson language preferences
    Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
    ResourceBundle labels = ResourceBundle.getBundle("Messages", supportedLocale);

    // Get the start and end dates for yesterday

    // The date should reflect the timezone as well. Otherwise we stand to lose that information 
    // in truncation and roll to an earlier date than intended.

    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String midnightYesterday = fmt.print(new DateMidnight(System.currentTimeMillis()));

    // FIXME: text of email should be more configurable from an
    // i18n viewpoint
    StringBuffer emailText = new StringBuffer();
    boolean isFirst = true;

    for (int i = 0; i < collections.size(); i++) {
        Collection c = collections.get(i);

        try {
            boolean includeAll = ConfigurationManager
                    .getBooleanProperty("harvest.includerestricted.subscription", true);

            // we harvest all the changed item from yesterday until now
            List<HarvestedItemInfo> itemInfos = Harvest.harvest(context, c, midnightYesterday, null, 0, // Limit
                    // and
                    // offset
                    // zero,
                    // get
                    // everything
                    0, true, // Need item objects
                    false, // But not containers
                    false, // Or withdrawals
                    includeAll);

            if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false)) {
                // get only the items archived yesterday
                itemInfos = filterOutModified(itemInfos);
            } else {
                // strip out the item archived today or 
                // not archived yesterday and modified today
                itemInfos = filterOutToday(itemInfos);
            }

            // Only add to buffer if there are new items
            if (itemInfos.size() > 0) {
                if (!isFirst) {
                    emailText.append("\n---------------------------------------\n");
                } else {
                    isFirst = false;
                }

                emailText.append(labels.getString("org.dspace.eperson.Subscribe.new-items")).append(" ")
                        .append(c.getMetadata("name")).append(": ").append(itemInfos.size()).append("\n\n");

                for (int j = 0; j < itemInfos.size(); j++) {
                    HarvestedItemInfo hii = (HarvestedItemInfo) itemInfos.get(j);

                    List<MDValue> titles = hii.item.getMetadata("dc", "title", null, MDValue.ANY);
                    emailText.append("      ").append(labels.getString("org.dspace.eperson.Subscribe.title"))
                            .append(" ");

                    if (titles.size() > 0) {
                        emailText.append(titles.get(0).getValue());
                    } else {
                        emailText.append(labels.getString("org.dspace.eperson.Subscribe.untitled"));
                    }

                    List<MDValue> authors = hii.item.getMetadata("dc", "contributor", MDValue.ANY, MDValue.ANY);

                    if (authors.size() > 0) {
                        emailText.append("\n    ")
                                .append(labels.getString("org.dspace.eperson.Subscribe.authors")).append(" ")
                                .append(authors.get(0).getValue());

                        for (int k = 1; k < authors.size(); k++) {
                            emailText.append("\n             ").append(authors.get(k).getValue());
                        }
                    }

                    emailText.append("\n         ").append(labels.getString("org.dspace.eperson.Subscribe.id"))
                            .append(" ").append(HandleManager.getCanonicalForm(hii.handle)).append("\n\n");
                }
            }
        } catch (ParseException pe) {
            // This should never get thrown as the Dates are auto-generated
        }
    }

    // Send an e-mail if there were any new items
    if (emailText.length() > 0) {

        if (test) {
            log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail()));
            log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString()));

        } else {

            Email email = Email.fromTemplate(context,
                    I18nUtil.getEmailFilename(supportedLocale, "subscription"));
            email.addRecipient(eperson.getEmail());
            email.addArgument(emailText.toString());
            email.send();

            log.info(LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID()));

        }
    }
}

From source file:org.ecocean.batch.BatchProcessor.java

License:Open Source License

@Override
public void run() {
    status = Status.INIT;//  w  ww .  ja v  a  2s . c  om

    try {
        // Validate state, and abort if not configured correctly.
        if (servletContext == null)
            throw new IllegalStateException("ServletContext has not been configured");
        if (dataDir == null || dataDirUsers == null)
            throw new IllegalStateException("Data folders have not been configured");
        if (username == null)
            throw new IllegalStateException("User has not been configured");

        if (dataDirUser == null) {
            dataDirUser = new File(dataDirUsers, username);
            if (!dataDirUser.exists()) {
                if (!dataDirUser.mkdir())
                    throw new RuntimeException(
                            String.format("Unable to create user folder: %s", dataDirUser.getAbsolutePath()));
            } else if (!dataDirUser.isDirectory()) {
                throw new RuntimeException(String.format("%s isn't a folder", dataDirUser.getAbsolutePath()));
            }
        }

        // Setup progress monitoring.
        // MaxCount:
        // 1. Download of media from all encounters.
        // 2. Persistence of encounters.
        // 3. Persistence of individuals.
        // 4. Thumb for each media item of each encounter.
        // 5. Copyright-overlay thumb for each encounter.
        maxCount = listInd.size() + listEnc.size() * 2;
        for (Encounter enc : listEnc) {
            List<SinglePhotoVideo> x = enc.getSinglePhotoVideo();
            if (x != null)
                maxCount += x.size() * 2;
        }

        // Setup persistence infrastructure.
        shepherd = new Shepherd(context);
        PersistenceManager pm = shepherd.getPM();
        // Find user email address for notifications (if opted in, otherwise keep as null).
        User user = shepherd.getUser(username);
        if (user == null) {
            throw new RuntimeException("Failed to find user with username: " + username);
        } else if (user.getReceiveEmails() && user.getEmailAddress() != null) {
            userEmail = user.getEmailAddress().trim();
        }

        // Find & instantiate plugin.
        setupPlugin(context);

        // Start processing.
        status = Status.RUNNING;
        // Allow plugin to perform pre-processing.
        if (plugin != null) {
            try {
                plugin.preProcess();
            } catch (Exception ex) {
                String msg = bundle.getString("batchUpload.processError.plugin.preProcessError");
                msg = MessageFormat.format(msg, plugin.getClass().getName());
                errors.add(msg);
                throw ex;
            }
        }
        // Loop over encounters to download photos from specified
        // remote server(s) and save them to the local filesystem.
        // Done prior to persisting the individuals, to ensure files exist.
        phase = Phase.MEDIA_DOWNLOAD;
        if (dataDirUser != null && !dataDirUser.exists())
            dataDirUser.mkdir();
        final int MAX_SIZE = CommonConfiguration.getMaxMediaSizeInMegabytes(context);
        List<SinglePhotoVideo> removeAsOversized = new ArrayList<SinglePhotoVideo>();
        for (Encounter enc : listEnc) {
            if (enc.getSinglePhotoVideo() != null) {
                for (SinglePhotoVideo spv : enc.getSinglePhotoVideo()) {
                    BatchMedia bm = mapMedia.get(spv);
                    URL url = new URL(bm.getMediaURL());
                    try {
                        if (MediaUtilities.isAcceptableMediaFile(spv.getFilename())) {
                            // NOTE: If file already exists the download is skipped and the
                            // existing file used, which allows a simple type of resumable
                            // upload. If this causes problems it will need changing.
                            if (spv.getFile().exists()) {
                                log.info("Media file already exists: {}", spv.getFile().getAbsolutePath());
                            } else {
                                FileUtilities.downloadUrlToFile(url, spv.getFile());
                                log.debug("Downloaded media file: {}", url);
                                // Check downloaded file size.
                                long size = spv.getFile().length() / 1000000;
                                if (size > MAX_SIZE) {
                                    bm.setOversize(true);
                                    removeAsOversized.add(spv);
                                    String msg = bundle.getString("batchUpload.processError.mediaSize");
                                    msg = MessageFormat.format(msg, mapMedia.get(spv).getMediaURL(), MAX_SIZE);
                                    warnings.add(msg);
                                }
                            }
                            mapMedia.get(spv).setDownloaded(true);
                        } else {
                            String msg = bundle.getString("batchUpload.processError.mediaType");
                            msg = MessageFormat.format(msg, mapMedia.get(spv).getMediaURL());
                            errors.add(msg);
                        }
                    } catch (IOException iox) {
                        String msg = bundle.getString("batchUpload.processError.mediaDownload");
                        msg = MessageFormat.format(msg, mapMedia.get(spv).getMediaURL());
                        errors.add(msg);
                        log.warn(msg, iox);
                    } finally {
                        counter++;
                    }
                }
                // Remove invalid/oversized media files from encounter.
                for (SinglePhotoVideo spv : removeAsOversized)
                    enc.removeSinglePhotoVideo(spv);
            }
        }
        if (!errors.isEmpty()) {
            status = Status.ERROR;
            // Notify user via email (if requested to receive emails).
            if (userEmail != null)
                notifyByEmail(userEmail);
            return;
        }

        phase = Phase.PERSISTENCE;
        try {
            shepherd.beginDBTransaction();

            // Find all encounters related to existing individuals, creating a map
            // of Encounter-to-IndividualID for later reference. IndividualID is
            // reset to null for initial commit to database, then reassigned to
            // the correct individual later.
            Map<Encounter, String> mapEncInd = new HashMap<Encounter, String>();
            for (Encounter enc : listEnc) {
                String iid = enc.getIndividualID();
                if (iid != null) {
                    boolean found = false;
                    for (MarkedIndividual mi : listInd) {
                        if (iid.equals(mi.getIndividualID())) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        mapEncInd.put(enc, iid);
                        enc.setIndividualID(null);
                    }
                }
            }

            // Persist all encounters (assigned/unassigned) to the database.
            // Assigned encounters must also be processed to assign unique IDs,
            // otherwise JDO barfs at primary key persistence problem.
            for (Encounter enc : listEnc) {
                // Create unique ID for encounter.
                // NOTE: Due to the UID implementation, this is double-checked
                // against the database for duplicate IDs before being used.
                String uid = null;
                Object testEnc = null;
                do {
                    uid = enc.generateEncounterNumber();
                    try {
                        testEnc = pm.getObjectById(pm.newObjectIdInstance(Encounter.class, uid));
                        log.trace("Unable to use UID for encounter; already exists: {}", uid);
                    } catch (JDOObjectNotFoundException jdox) {
                        //              log.trace("No existing encounter found with UID: {}", uid);
                        testEnc = null;
                    }
                } while (testEnc != null);
                enc.setEncounterNumber(uid);
                // Populate Darwin Core attributes.
                String guid = CommonConfiguration.getGlobalUniqueIdentifierPrefix(context) + uid;
                enc.setDWCGlobalUniqueIdentifier(guid);
                enc.setDWCImageURL(("http://" + urlLocation + "/encounters/encounter.jsp?number=" + uid));
                DateTime dt = new DateTime();
                DateTimeFormatter fmt = ISODateTimeFormat.date();
                String strOutputDateTime = fmt.print(dt);
                enc.setDWCDateAdded(strOutputDateTime);
                enc.setDWCDateLastModified(strOutputDateTime);
                // Set encounter state to "approved".
                if (CommonConfiguration.getProperty("encounterState1", context) != null)
                    enc.setState(CommonConfiguration.getProperty("encounterState1", context));
                // Assign encounter ID to associated measurements.
                if (enc.getMeasurements() != null) {
                    for (Measurement x : enc.getMeasurements()) {
                        x.setCorrespondingEncounterNumber(enc.getEncounterNumber());
                    }
                }
                // Assign encounter ID to associated media.
                if (enc.getSinglePhotoVideo() != null) {
                    for (SinglePhotoVideo x : enc.getSinglePhotoVideo()) {
                        x.setCorrespondingEncounterNumber(enc.getEncounterNumber());
                    }
                }
                // Assign encounter ID to associated samples.
                if (enc.getTissueSamples() != null) {
                    for (TissueSample x : enc.getTissueSamples()) {
                        x.setCorrespondingEncounterNumber(enc.getEncounterNumber());
                    }
                }
                // Relocate associated media into encounter folder.
                try {
                    if (enc.getSinglePhotoVideo() != null)
                        relocateMedia(enc);
                } catch (IOException iox) {
                    log.error(iox.getMessage());
                }
                // Check for problem relocating media.
                List<SinglePhotoVideo> media = enc.getSinglePhotoVideo();
                if (media != null && !media.isEmpty()) {
                    for (SinglePhotoVideo spv : media.toArray(new SinglePhotoVideo[0])) {
                        BatchMedia bp = mapMedia.get(spv);
                        if (!bp.isRelocated()) {
                            String msg = bundle.getString("batchUpload.processError.mediaRename");
                            msg = MessageFormat.format(msg, bp.getMediaURL());
                            errors.add(msg);
                            if (!spv.getFile().delete()) // Remove file to maintain clean data folder.
                                log.warn("Unable to delete unassigned media file: {}",
                                        spv.getFile().getAbsoluteFile());
                            enc.removeSinglePhotoVideo(spv);
                        } else if (!bp.isPersist()) {
                            enc.removeSinglePhotoVideo(spv);
                        }
                    }
                }
                // Assign keywords to media.
                if (media != null && !media.isEmpty()) {
                    for (SinglePhotoVideo spv : media.toArray(new SinglePhotoVideo[0])) {
                        BatchMedia bp = mapMedia.get(spv);
                        String[] keywords = bp.getKeywords();
                        if (keywords != null && keywords.length > 0) {
                            for (String kw : keywords) {
                                Keyword x = shepherd.getKeyword(kw);
                                if (x != null)
                                    spv.addKeyword(x);
                            }
                        }
                    }
                }
                // (must be done within current transaction to ensure referential integrity in database).
                // Set submitterID for later reference.
                enc.setSubmitterID(username);
                // Add comment to reflect batch upload.
                enc.addComments("<p><em>" + username + " on " + (new Date()).toString() + "</em><br>"
                        + "Imported via batch upload.</p>");
                // Finally, if IndividualID for encounter is null, set it to "Unassigned".
                //if (enc.getIndividualID() == null)enc.setIndividualID("Unassigned");
                // Persist encounter.
                try {
                    pm.makePersistent(enc);
                } catch (Exception ex) {
                    // Add error message for this encounter.
                    String msg = bundle.getString("batchUpload.processError.persistEncounter");
                    msg = MessageFormat.format(msg, enc.getEncounterNumber());
                    errors.add(msg);
                    throw ex;
                }
                counter++;
            }

            // Persist all new individuals to the database.
            for (MarkedIndividual ind : listInd) {
                try {
                    ind.refreshThumbnailUrl(context);
                    pm.makePersistent(ind);
                } catch (Exception ex) {
                    // Add error message for this individual.
                    String msg = bundle.getString("batchUpload.processError.persistIndividual");
                    msg = MessageFormat.format(msg, ind.getIndividualID());
                    errors.add(msg);
                    throw ex;
                }
                counter++;
            }

            // Persist encounters for existing individuals.
            // (This is not progress tracked, as should be comparatively quick.)
            for (Map.Entry<Encounter, String> me : mapEncInd.entrySet()) {
                try {
                    MarkedIndividual ind = shepherd.getMarkedIndividual(me.getValue());
                    ind.addEncounter(me.getKey(), context);
                    ind.refreshThumbnailUrl(context);
                    pm.makePersistent(ind);
                } catch (Exception ex) {
                    String msg = bundle.getString("batchUpload.processError.assignEncounter");
                    msg = MessageFormat.format(msg, me.getKey().getEncounterNumber(), me.getValue());
                    errors.add(msg);
                    throw ex;
                }
            }

            // Allow plugin to perform media processing.
            if (plugin != null) {
                phase = Phase.PLUGIN;
                try {
                    plugin.process();
                } catch (Exception ex) {
                    log.warn(ex.getMessage(), ex);
                    String msg = bundle.getString("batchUpload.processError.plugin.processError");
                    msg = MessageFormat.format(msg, plugin.getClass().getName());
                    errors.add(msg);
                    throw ex;
                }
            }

            // Commit changes to store.
            shepherd.commitDBTransaction();

            // TODO: Nasty hack to get resources from a language folder.
            // Should be using the standard ResourceBundle lookup mechanism to find
            // the appropriate language file.
            Properties props = new Properties();
            props.load(getClass().getResourceAsStream(
                    "/" + RESOURCES + "/" + locale.getLanguage() + "/encounter.properties"));
            String copyText = props.getProperty("nocopying");

            // Generate thumbnails for encounter's media.
            // This step is performed last, as it's considered optional, and just
            // a convenience to have all the thumbnail images pre-rendered.
            // If this stage fails, all data should already be in the database.
            phase = Phase.THUMBNAILS;
            long timeStart = System.currentTimeMillis();
            File encsDir = new File(dataDir, "encounters");
            for (Encounter enc : listEnc) {
                // Create folder for encounter.
                File encDir = new File(enc.dir(dataDir.getAbsolutePath()));
                if (!encDir.exists()) {
                    if (!encDir.mkdirs())
                        log.warn(String.format("Unable to create encounter folder: %s",
                                encDir.getAbsoluteFile()));
                }
                // Process main thumbnail image.
                List<SinglePhotoVideo> media = enc.getSinglePhotoVideo();
                if (media != null && !media.isEmpty()) {
                    // Assume first media item is one to use as thumbnail.
                    // TODO: How to figure out which media item is best to use?
                    File src = media.get(0).getFile();
                    File dst = new File(src.getParentFile(), "thumb.jpg");
                    if (dst.exists()) {
                        log.info(String.format("Thumbnail for encounter %s already exists",
                                enc.getEncounterNumber()));
                    } else {
                        // TODO: If video file, copy placeholder image? Just ignores and lets JSP handle it for now.
                        if (MediaUtilities.isAcceptableImageFile(src)) {
                            // Resize image to thumbnail & write to file.
                            try {
                                createThumbnail(src, dst, 100, 75);
                                log.trace(String.format("Created thumbnail image for encounter %s",
                                        enc.getEncounterNumber()));
                            } catch (Exception ex) {
                                log.warn(String.format("Failed to create thumbnail correctly: %s",
                                        dst.getAbsolutePath()), ex);
                            }
                        }
                    }
                    // Process copyright-overlaid thumbnail for each media item.
                    for (SinglePhotoVideo spv : media) {
                        if (!MediaUtilities.isAcceptableImageFile(spv.getFile()))
                            continue;
                        src = spv.getFile();
                        dst = new File(src.getParentFile(), spv.getDataCollectionEventID() + ".jpg");
                        if (dst.exists()) {
                            log.info(String.format("Thumbnail image %s already exists",
                                    spv.getDataCollectionEventID()));
                        } else {
                            try {
                                createThumbnailWithOverlay(src, dst, 250, 200, copyText);
                                //                  log.trace(String.format("Created thumbnail for media item %s", spv.getDataCollectionEventID()));
                            } catch (Exception ex) {
                                log.warn(String.format("Failed to create thumbnail correctly: %s",
                                        dst.getAbsolutePath()), ex);
                            }
                        }
                        counter++;
                    }
                } else {
                    // Copy holding image in place.
                    File rootPath = new File(servletContext.getRealPath("/"));
                    File imgDir = new File(rootPath, "images");
                    File src = new File(imgDir, "no_images.jpg");
                    File dst = new File(encDir, "thumb.jpg");
                    FileUtilities.copyFile(src, dst);
                }
                counter++;
            }
            long timeEnd = System.currentTimeMillis();
            long timeElapsed = (timeEnd - timeStart);
            log.debug(String.format("Time taken for media processing: %,d milliseconds", timeElapsed));

            // Notify user via email (if requested to receive emails).
            if (userEmail != null)
                notifyByEmail(userEmail);

        } catch (Exception ex) {
            shepherd.rollbackDBTransaction();
            throw ex;
        } finally {
            shepherd.closeDBTransaction();
        }

        phase = Phase.DONE;
        cleanupTemporaryFiles();
        status = Status.FINISHED;
    } catch (Throwable th) {
        this.thrown = th;
        status = Status.ERROR;
        log.error(th.getMessage(), th);
    }
}

From source file:org.ecocean.Encounter.java

License:Open Source License

private String milliToMonthDayYear(Long millis) {
    DateTime dt = new DateTime(millis);
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm a");
    return dtf.print(dt);
}

From source file:org.ecocean.servlet.EncounterForm.java

License:Open Source License

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    HashMap fv = new HashMap();

    //IMPORTANT - processingNotes can be used to add notes on data handling (e.g., poorly formatted dates) that can be reconciled later by the reviewer
    //Example usage: processingNotes.append("<p>Error encountered processing this date submitted by user: "+getVal(fv, "datepicker")+"</p>");
    StringBuffer processingNotes = new StringBuffer();

    HttpSession session = request.getSession(true);
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.setAction("EncounterForm.class");
    System.out.println("in context " + context);
    //request.getSession()getServlet().getServletContext().getRealPath("/"));
    String rootDir = getServletContext().getRealPath("/");
    System.out.println("rootDir=" + rootDir);

    /*/* w  ww.  j a  v  a2s  . co m*/
        Vector<String> fbImages = new Vector<String>();
        int fbi = 0;
        while (request.getParameter("socialphoto_" + fbi) != null) {
            fbImages.add(request.getParameter("socialphoto_" + fbi));
            fbi++;
        }
    System.out.println(fbImages);
        if (fbImages.size() > 0) {
            FacebookClient fbclient = null;
            try {
    fbclient = SocialAuth.getFacebookClient(context);
            } catch (Exception ex) {
    System.out.println("SocialAuth.getFacebookClient threw exception " + ex.toString());
            }
    WebContext ctx = new J2EContext(request, response);
    //String callbackUrl = "http://localhost.wildme.org/a/SocialConnect?type=facebook";
    String callbackUrl = "http://" + CommonConfiguration.getURLLocation(request) + "/XXXSocialConnect?type=facebook";
    if (request.getParameter("disconnect") != null) callbackUrl += "&disconnect=1";
    fbclient.setCallbackUrl(callbackUrl);
    OAuthCredentials credentials = null;
    try {
        credentials = fbclient.getCredentials(ctx);
    } catch (Exception ex) {
        System.out.println("caught exception on facebook credentials: " + ex.toString());
    }
    if (credentials != null) {
        FacebookProfile facebookProfile = fbclient.getUserProfile(credentials, ctx);
        User fbuser = myShepherd.getUserBySocialId("facebook", facebookProfile.getId());
        System.out.println("getId() = " + facebookProfile.getId() + " -> user = " + fbuser);
    if (fbuser != null) System.out.println("user = " + user.getUsername() + "; fbuser = " + fbuser.getUsername());
        if ((fbuser != null) && (fbuser.getUsername().equals(user.getUsername())) && (request.getParameter("disconnect") != null)) {
            fbuser.unsetSocial("facebook");
            //myShepherd.getPM().makePersistent(user);
            session.setAttribute("message", "disconnected from facebook");
            response.sendRedirect("myAccount.jsp");
            return;
        } else if (fbuser != null) {
            session.setAttribute("error", "looks like this account is already connected to an account");
            response.sendRedirect("myAccount.jsp");
            return;
        } else {  //lets do this
            user.setSocial("facebook", facebookProfile.getId());
            //myShepherd.getPM().makePersistent(user);
            session.setAttribute("message", "connected to facebook");
            response.sendRedirect("myAccount.jsp");
            return;
        }
    } else {
    System.out.println("*** trying redirect?");
        try {
            fbclient.redirect(ctx, false, false);
        } catch (Exception ex) {
            System.out.println("caught exception on facebook processing: " + ex.toString());
        }
        return;
    }
        }
    */
    //private Map<String, Object> measurements = new HashMap<String, Object>();
    //Map<String, Object> metalTags = new HashMap<String, Object>();

    /*
          private String acousticTagSerial = "";
          private String acousticTagId = "";
          private String satelliteTagSerial = "";
          private String satelliteTagArgosPttNumber = "";
          private String satelliteTagName = "";
    */

    //set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;

    String fileName = "None";
    String username = "None";
    String fullPathFilename = "";

    boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end)
    String doneMessage = "";
    List<String> filesOK = new ArrayList<String>();
    HashMap<String, String> filesBad = new HashMap<String, String>();

    List<FileItem> formFiles = new ArrayList<FileItem>();
    List<File> socialFiles = new ArrayList<File>();

    //Calendar date = Calendar.getInstance();

    long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context);
    long maxSizeBytes = maxSizeMB * 1048576;

    if (ServletFileUpload.isMultipartContent(request)) {

        try {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            upload.setHeaderEncoding("UTF-8");
            List<FileItem> multiparts = upload.parseRequest(request);
            //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (item.isFormField()) { //plain field
                    fv.put(item.getFieldName(),
                            ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon
                    //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")");
                } else if (item.getName().startsWith("socialphoto_")) {
                    System.out.println(item.getName() + ": " + item.getString("UTF-8"));
                } else { //file
                    //System.out.println("content type???? " + item.getContentType());   TODO note, the helpers only check extension
                    if (item.getSize() > maxSizeBytes) {
                        filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB");
                    } else if (myShepherd.isAcceptableImageFile(item.getName())
                            || myShepherd.isAcceptableVideoFile(item.getName())) {
                        formFiles.add(item);
                        filesOK.add(item.getName());
                    } else {
                        filesBad.put(item.getName(), "invalid type of file");
                    }
                }
            }

            doneMessage = "File Uploaded Successfully";
            fileSuccess = true;

        } catch (Exception ex) {
            doneMessage = "File Upload Failed due to " + ex;
        }

    } else {
        doneMessage = "Sorry this Servlet only handles file upload request";
        System.out.println("Not a multi-part form submission!");
    }

    if (fv.get("social_files_id") != null) {
        System.out.println("BBB: Social_files_id: " + fv.get("social_files_id"));

        //TODO better checking of files (size, type etc)
        File socDir = new File(
                ServletUtilities.dataDir(context, rootDir) + "/social_files/" + fv.get("social_files_id"));
        for (File sf : socDir.listFiles()) {
            socialFiles.add(sf);
            System.out.println("BBB: Adding social file : " + sf.getName());

            filesOK.add(sf.getName());
        }
        filesBad = new HashMap<String, String>();
        fileSuccess = true;
    }

    session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray())));
    String badmsg = "";
    for (String key : filesBad.keySet()) {
        badmsg += key + " (" + getVal(filesBad, key) + ") ";
    }
    if (badmsg.equals("")) {
        badmsg = "none";
    }
    session.setAttribute("filesBadMessage", badmsg);

    if (fileSuccess) {

        //////////////////////////////////////////// START

        //{submitterID=tomcat, submitterProject=, photographerEmail=, metalTag(left)=, sex=unknown, measurement(weight)=34234, location=, acousticTagId=, behavior=yow behavior..., measurement(weightunits)=kilograms, acousticTagSerial=, photographerName=, lifeStage=sub-adult, submitterAddress=, satelliteTagSerial=, releaseDate=, photographerPhone=, measurement(lengthunits)=meters, measurement(weightsamplingProtocol)=samplingProtocol0, measurement(length)=, submitterOrganization=, photographerAddress=, longitude=, year=2014, lat=, measurement(lengthsamplingProtocol)=samplingProtocol0, submitterEmail=, minutes=00, elevation=, measurement(height)=, measurement(heightsamplingProtocol)=samplingProtocol0, scars=None, submitterPhone=, submitterName=tomcat, hour=-1, livingStatus=alive, depth=, country=, satelliteTagName=Wild Life Computers, metalTag(right)=, month=1, measurement(heightunits)=meters, Submit=Send encounter report, informothers=, day=0, satelliteTagArgosPttNumber=, comments=}

        //check for spamBots   TODO possibly move this to Util for general/global usage?
        boolean spamBot = false;
        String[] spamFieldsToCheck = new String[] { "submitterPhone", "submitterName", "photographerName",
                "photographerPhone", "location", "comments", "behavior" };
        StringBuffer spamFields = new StringBuffer();
        for (int i = 0; i < spamFieldsToCheck.length; i++) {
            spamFields.append(getVal(fv, spamFieldsToCheck[i]));
        }

        if (spamFields.toString().toLowerCase().indexOf("porn") != -1) {
            spamBot = true;
        }
        if (spamFields.toString().toLowerCase().indexOf("href") != -1) {
            spamBot = true;
        }

        System.out.println("spambot: " + spamBot);
        //else if(spamFields.toString().toLowerCase().indexOf("[url]")!=-1){spamBot=true;}
        //else if(spamFields.toString().toLowerCase().indexOf("url=")!=-1){spamBot=true;}
        //else if(spamFields.toString().toLowerCase().trim().equals("")){spamBot=true;}
        //else if((theForm.getSubmitterID()!=null)&&(theForm.getSubmitterID().equals("N%2FA"))) {spamBot=true;}

        String locCode = "";
        System.out.println(" **** here is what i think locationID is: " + fv.get("locationID"));
        if ((fv.get("locationID") != null) && !fv.get("locationID").toString().equals("")) {
            locCode = fv.get("locationID").toString();
        }
        //see if the location code can be determined and set based on the location String reported
        else if (fv.get("location") != null) {
            String locTemp = getVal(fv, "location").toLowerCase();
            Properties props = new Properties();

            try {
                props = ShepherdProperties.getProperties("submitActionClass.properties", "", context);

                Enumeration m_enum = props.propertyNames();
                while (m_enum.hasMoreElements()) {
                    String aLocationSnippet = ((String) m_enum.nextElement()).trim();
                    if (locTemp.indexOf(aLocationSnippet) != -1) {
                        locCode = props.getProperty(aLocationSnippet);
                    }
                }
            } catch (Exception props_e) {
                props_e.printStackTrace();
            }

        } //end else
          //end location code setter
        fv.put("locCode", locCode);

        //TODO this should live somewhere else as constant? (e.g. to build in form as well)
        String[] scarType = new String[] { "None", "Tail (caudal) fin", "1st dorsal fin", "2nd dorsal fin",
                "Left pectoral fin", "Right pectoral fin", "Head", "Body" };
        int scarNum = -1;
        try {
            scarNum = Integer.parseInt(getVal(fv, "scars"));
        } catch (NumberFormatException e) {
            scarNum = -1;
        }
        if ((scarNum < 0) || (scarNum > 7)) {
            scarNum = -1;
        }
        if (scarNum >= 0) {
            fv.put("scars", scarType[scarNum]);
        }

        //System.out.println("about to do int stuff");

        //need some ints for day/month/year/hour (other stuff seems to be strings)
        int day = 0, month = -1, year = 0, hour = 0;
        String minutes = "";
        //try { day = Integer.parseInt(getVal(fv, "day")); } catch (NumberFormatException e) { day = 0; }
        //try { month = Integer.parseInt(getVal(fv, "month")); } catch (NumberFormatException e) { month = 0; }
        //try { year = Integer.parseInt(getVal(fv, "year")); } catch (NumberFormatException e) { year = 0; }

        //switch to datepicker

        LocalDateTime dt = new LocalDateTime();

        if ((getVal(fv, "datepicker") != null) && (!getVal(fv, "datepicker").trim().equals(""))) {
            //System.out.println("Trying to read date: "+getVal(fv, "datepicker").replaceAll(" ", "T"));
            //boolean badDate=false;
            try {
                DateTimeFormatter parser1 = ISODateTimeFormat.dateOptionalTimeParser();

                LocalDateTime reportedDateTime = new LocalDateTime(
                        parser1.parseMillis(getVal(fv, "datepicker").replaceAll(" ", "T")));
                StringTokenizer str = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"), "-");

                int numTokens = str.countTokens();

                if (numTokens >= 1) {
                    //try {
                    year = reportedDateTime.getYear();
                    if (year > (dt.getYear() + 1)) {
                        //badDate=true;
                        year = 0;
                        throw new Exception(
                                "    An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format: "
                                        + year + " > " + dt.getYear());
                    }

                    //} catch (Exception e) { year=-1;}
                }
                if (numTokens >= 2) {
                    try {
                        month = reportedDateTime.getMonthOfYear();
                    } catch (Exception e) {
                        month = -1;
                    }
                } else {
                    month = -1;
                }
                //see if we can get a day, because we do want to support only yyy-MM too
                if (str.countTokens() >= 3) {
                    try {
                        day = reportedDateTime.getDayOfMonth();
                    } catch (Exception e) {
                        day = 0;
                    }
                } else {
                    day = 0;
                }

                //see if we can get a time and hour, because we do want to support only yyy-MM too
                StringTokenizer strTime = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"),
                        "T");
                if (strTime.countTokens() > 1) {
                    try {
                        hour = reportedDateTime.getHourOfDay();
                    } catch (Exception e) {
                        hour = -1;
                    }
                    try {
                        minutes = (new Integer(reportedDateTime.getMinuteOfHour()).toString());
                    } catch (Exception e) {
                    }
                } else {
                    hour = -1;
                }

                //System.out.println("At the end of time processing I see: "+year+"-"+month+"-"+day+" "+hour+":"+minutes);

            } catch (Exception e) {
                System.out.println(
                        "    An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format.");
                e.printStackTrace();
                processingNotes.append("<p>Error encountered processing this date submitted by user: "
                        + getVal(fv, "datepicker") + "</p>");

            }
        }

        String guess = "no estimate provided";
        if ((fv.get("guess") != null) && !fv.get("guess").toString().equals("")) {
            guess = fv.get("guess").toString();
        }

        //let's handle genus and species for taxonomy
        String genus = null;
        String specificEpithet = null;

        try {

            //now we have to break apart genus species
            if (fv.get("genusSpecies") != null) {
                StringTokenizer tokenizer = new StringTokenizer(fv.get("genusSpecies").toString(), " ");
                if (tokenizer.countTokens() >= 2) {

                    genus = tokenizer.nextToken();
                    //enc.setGenus(tokenizer.nextToken());
                    specificEpithet = tokenizer.nextToken().replaceAll(",", "").replaceAll("_", " ");
                    //enc.setSpecificEpithet(tokenizer.nextToken().replaceAll(",","").replaceAll("_"," "));

                }
                //handle malformed Genus Species formats
                else {
                    throw new Exception(
                            "The format of the submitted genusSpecies parameter did not have two tokens delimited by a space (e.g., \"Rhincodon typus\"). The submitted value was: "
                                    + fv.get("genusSpecies"));
                }
            }

        } catch (Exception le) {
            le.printStackTrace();
        }

        System.out.println("about to do enc()");

        Encounter enc = new Encounter(day, month, year, hour, minutes, guess, getVal(fv, "location"));
        boolean llSet = false;
        //Encounter enc = new Encounter();
        //System.out.println("Submission detected date: "+enc.getDate());

        String encID = enc.generateEncounterNumber();
        if ((fv.get("catalogNumber") != null) && (!fv.get("catalogNumber").toString().trim().equals(""))) {
            if ((!myShepherd.isEncounter(fv.get("catalogNumber").toString()))) {
                encID = fv.get("catalogNumber").toString().trim();
            }
        }
        enc.setEncounterNumber(encID);

        System.out.println("hey, i think i may have made an encounter, encID=" + encID);
        System.out.println("enc ?= " + enc.toString());

        AssetStore astore = AssetStore.getDefault(myShepherd);
        ArrayList<Annotation> newAnnotations = new ArrayList<Annotation>();

        //for directly uploaded files
        for (FileItem item : formFiles) {
            //convert each FileItem into a MediaAsset
            makeMediaAssetsFromJavaFileItemObject(item, encID, astore, enc, newAnnotations, genus,
                    specificEpithet);
        }

        ///////////////////TODO social files also!!!
        System.out.println("BBB: Checking if we have social files...");

        if (socialFiles.size() > 0) {
            int numSocialFiles = socialFiles.size();
            System.out.println("BBB: Trying to persist social files: " + numSocialFiles);

            DiskFileItemFactory factory = new DiskFileItemFactory();

            for (int q = 0; q < numSocialFiles; q++) {
                File item = socialFiles.get(q);
                makeMediaAssetsFromJavaFileObject(item, encID, astore, enc, newAnnotations, genus,
                        specificEpithet);

            }

        }

        if (fv.get("mediaAssetSetId") != null) {
            MediaAssetSet maSet = ((MediaAssetSet) (myShepherd.getPM().getObjectById(
                    myShepherd.getPM().newObjectIdInstance(MediaAssetSet.class, fv.get("mediaAssetSetId")),
                    true)));
            if ((maSet != null) && (maSet.getMediaAssets() != null) && (maSet.getMediaAssets().size() > 0)) {
                int num = maSet.getMediaAssets().size();
                for (MediaAsset ma : maSet.getMediaAssets()) {
                    newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma));
                }
                session.setAttribute("filesOKMessage", num + " " + ((num == 1) ? "file" : "files"));
            }
        }

        enc.setAnnotations(newAnnotations);

        enc.setGenus(genus);
        enc.setSpecificEpithet(specificEpithet);

        //User management
        String subN = getVal(fv, "submitterName");
        String subE = getVal(fv, "submitterEmail");
        String subO = getVal(fv, "submitterOrganization");
        if (Util.stringExists(subO))
            enc.setSubmitterOrganization(subO);
        String subP = getVal(fv, "submitterProject");
        if (Util.stringExists(subP))
            enc.setSubmitterOrganization(subP);
        //User user=null;
        List<User> submitters = new ArrayList<User>();
        if ((subE != null) && (!subE.trim().equals(""))) {

            StringTokenizer str = new StringTokenizer(subE, ",");
            int numTokens = str.countTokens();
            for (int y = 0; y < numTokens; y++) {
                String tok = str.nextToken().trim();
                String hashedTok = ServletUtilities.hashString(tok);
                if (myShepherd.getUserByHashedEmailAddress(hashedTok) != null) {
                    User user = myShepherd.getUserByHashedEmailAddress(hashedTok);
                    submitters.add(user);
                } else {
                    User user = new User(tok, Util.generateUUID());
                    user.setAffiliation(subO);
                    user.setUserProject(subP);
                    if ((numTokens == 1) && (subN != null)) {
                        user.setFullName(subN);
                    }
                    myShepherd.getPM().makePersistent(user);
                    myShepherd.commitDBTransaction();
                    myShepherd.beginDBTransaction();

                    submitters.add(user);
                }
            }
        }
        enc.setSubmitters(submitters);
        //end submitter-user processing

        //User management - photographer processing
        String photoN = getVal(fv, "photographerName");
        String photoE = getVal(fv, "photographerEmail");
        List<User> photographers = new ArrayList<User>();
        if ((photoE != null) && (!photoE.trim().equals(""))) {

            StringTokenizer str = new StringTokenizer(photoE, ",");
            int numTokens = str.countTokens();
            for (int y = 0; y < numTokens; y++) {
                String tok = str.nextToken().trim();
                if (myShepherd.getUserByEmailAddress(tok.trim()) != null) {
                    User user = myShepherd.getUserByEmailAddress(tok);
                    photographers.add(user);
                } else {
                    User user = new User(tok, Util.generateUUID());
                    myShepherd.getPM().makePersistent(user);
                    myShepherd.commitDBTransaction();
                    myShepherd.beginDBTransaction();
                    photographers.add(user);
                }
            }
        }
        enc.setPhotographers(photographers);
        //end photographer-user processing

        //User management - informOthers processing
        String othersString = getVal(fv, "informothers");
        List<User> informOthers = new ArrayList<User>();
        if ((othersString != null) && (!othersString.trim().equals(""))) {

            StringTokenizer str = new StringTokenizer(othersString, ",");
            int numTokens = str.countTokens();
            for (int y = 0; y < numTokens; y++) {
                String tok = str.nextToken().trim();
                if (myShepherd.getUserByEmailAddress(tok.trim()) != null) {
                    User user = myShepherd.getUserByEmailAddress(tok);
                    informOthers.add(user);
                } else {
                    User user = new User(tok, Util.generateUUID());
                    myShepherd.getPM().makePersistent(user);
                    myShepherd.commitDBTransaction();
                    myShepherd.beginDBTransaction();
                    informOthers.add(user);
                }
            }
        }
        enc.setInformOthers(informOthers);
        //end informOthers-user processing

        /*
                    String baseDir = ServletUtilities.dataDir(context, rootDir);
                    ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>();
                    for (FileItem item : formFiles) {
        // this will actually write file to filesystem (or [FUTURE] wherever)
        //  TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc.
        try {
            //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir);
            SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir);
            //images.add(spv);
            enc.addSinglePhotoVideo(spv);
        } catch (Exception ex) {
            System.out.println("failed to save " + item.toString() + ": " + ex.toString());
        }
                    }
                    for (File sf : socialFiles) {
                File encDir = new File(enc.dir(baseDir));
                if (!encDir.exists()) encDir.mkdirs();
        File targetFile = new File(encDir, sf.getName());
        System.out.println("socialFile copy: " + sf.toString() + " ---> " + targetFile.toString());
        Files.copy(sf.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        SinglePhotoVideo spv = new SinglePhotoVideo(encID, targetFile);
        enc.addSinglePhotoVideo(spv);
                    }
        */

        //now let's add our encounter to the database

        enc.setComments(getVal(fv, "comments").replaceAll("\n", "<br>"));
        if (fv.get("releaseDate") != null && fv.get("releaseDate").toString().length() > 0) {
            String dateFormatPattern = CommonConfiguration.getProperty("releaseDateFormat", context);
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
                enc.setReleaseDate(simpleDateFormat.parse(fv.get("releaseDate").toString()).getTime());
            } catch (Exception e) {
                enc.addComments("<p>Reported release date was problematic: " + fv.get("releaseDate") + "</p>");
            }
        }
        if (fv.get("behavior") != null && fv.get("behavior").toString().length() > 0) {
            enc.setBehavior(fv.get("behavior").toString());
        }
        if (fv.get("alternateID") != null && fv.get("alternateID").toString().length() > 0) {
            enc.setAlternateID(fv.get("alternateID").toString());
        }
        if (fv.get("lifeStage") != null && fv.get("lifeStage").toString().length() > 0) {
            enc.setLifeStage(fv.get("lifeStage").toString());
        }

        if (fv.get("flukeType") != null && fv.get("flukeType").toString().length() > 0) {
            System.out.println("        ENCOUNTERFORM:");
            System.out.println("        ENCOUNTERFORM:");
            System.out.println("        ENCOUNTERFORM:");
            String kwName = fv.get("flukeType").toString();
            Keyword kw = myShepherd.getOrCreateKeyword(kwName);
            for (Annotation ann : enc.getAnnotations()) {
                MediaAsset ma = ann.getMediaAsset();
                if (ma != null) {
                    ma.addKeyword(kw);

                    System.out.println("ENCOUNTERFORM: added flukeType keyword to encounter: " + kwName);
                }
            }
            System.out.println("        ENCOUNTERFORM:");
            System.out.println("        ENCOUNTERFORM:");

        }

        if (fv.get("manualID") != null && fv.get("manualID").toString().length() > 0) {
            String indID = fv.get("manualID").toString();
            MarkedIndividual ind = myShepherd.getMarkedIndividualQuiet(indID);
            if (ind == null) {
                ind = new MarkedIndividual(enc);
                ind.addName(request, indID); // we don't just create the individual using the encounter+indID bc this request might key the name off of the logged-in user
                myShepherd.storeNewMarkedIndividual(ind);
                ind.refreshNamesCache();
                System.out.println("        ENCOUNTERFORM: created new individual " + indID);
            } else {
                ind.addEncounter(enc);
                ind.addName(request, indID); // adds the just-entered name to the individual
                System.out.println("        ENCOUNTERFORM: added enc to individual " + indID);
            }
            if (ind != null)
                enc.setIndividual(ind);
            enc.setFieldID(indID);
        }

        if (fv.get("occurrenceID") != null && fv.get("occurrenceID").toString().length() > 0) {
            String occID = fv.get("occurrenceID").toString();
            enc.setOccurrenceID(occID);
            Occurrence occ = myShepherd.getOccurrence(occID);
            if (occ == null) {
                occ = new Occurrence(occID, enc);
                myShepherd.storeNewOccurrence(occ);
                System.out.println("        ENCOUNTERFORM: created new Occurrence " + occID);
            } else {
                occ.addEncounter(enc);
                System.out.println("        ENCOUNTERFORM: added enc to Occurrence " + occID);

            }
        }

        List<MetalTag> metalTags = getMetalTags(fv);
        for (MetalTag metalTag : metalTags) {
            enc.addMetalTag(metalTag);
        }

        List<Measurement> measurements = getMeasurements(fv, encID, context);
        for (Measurement measurement : measurements) {
            enc.setMeasurement(measurement, myShepherd);
        }

        enc.setAcousticTag(getAcousticTag(fv));
        enc.setSatelliteTag(getSatelliteTag(fv));
        enc.setSex(getVal(fv, "sex"));
        enc.setLivingStatus(getVal(fv, "livingStatus"));

        if (fv.get("scars") != null) {
            enc.setDistinguishingScar(fv.get("scars").toString());
        }

        int sizePeriod = 0;
        if ((fv.get("measureUnits") != null) && fv.get("measureUnits").toString().equals("Feet")) {

            if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) {
                try {
                    double tempDouble = (new Double(fv.get("depth").toString())).doubleValue() / 3.3;
                    String truncDepth = (new Double(tempDouble)).toString();
                    sizePeriod = truncDepth.indexOf(".");
                    truncDepth = truncDepth.substring(0, sizePeriod + 2);
                    fv.put("depth", (new Double(truncDepth)).toString());
                } catch (java.lang.NumberFormatException nfe) {
                    enc.addComments(
                            "<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>");
                    fv.put("depth", "");
                } catch (NullPointerException npe) {
                    fv.put("depth", "");
                }
            }
            System.out.println("depth --> " + fv.get("depth").toString());

            if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) {
                try {
                    double tempDouble = (new Double(fv.get("elevation").toString())).doubleValue() / 3.3;
                    String truncElev = (new Double(tempDouble)).toString();
                    //String truncElev = ((new Double(elevation)) / 3.3).toString();
                    sizePeriod = truncElev.indexOf(".");
                    truncElev = truncElev.substring(0, sizePeriod + 2);
                    fv.put("elevation", (new Double(truncElev)).toString());
                } catch (java.lang.NumberFormatException nfe) {
                    enc.addComments("<p>Reported elevation was problematic: " + fv.get("elevation").toString()
                            + "</p>");
                    fv.put("elevation", "");
                } catch (NullPointerException npe) {
                    fv.put("elevation", "");
                }
            }

            if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) {

                try {
                    double tempDouble = (new Double(fv.get("size").toString())).doubleValue() / 3.3;
                    String truncSize = (new Double(tempDouble)).toString();
                    //String truncSize = ((new Double(size)) / 3.3).toString();
                    sizePeriod = truncSize.indexOf(".");
                    truncSize = truncSize.substring(0, sizePeriod + 2);
                    fv.put("size", (new Double(truncSize)).toString());
                } catch (java.lang.NumberFormatException nfe) {

                    enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>");
                    fv.put("size", "");
                } catch (NullPointerException npe) {
                    fv.put("size", "");
                }
            }
        } //measureUnits

        if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) {
            try {
                enc.setSize(new Double(fv.get("size").toString()));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>");
                fv.put("size", "");
            } catch (NullPointerException npe) {
                fv.put("size", "");
            }
        }

        if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) {
            try {
                enc.setMaximumElevationInMeters(new Double(fv.get("elevation").toString()));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments(
                        "<p>Reported elevation was problematic: " + fv.get("elevation").toString() + "</p>");
                fv.put("elevatoin", "");
            } catch (NullPointerException npe) {
                fv.put("elevation", "");
            }
        }

        if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) {
            try {
                enc.setDepth(new Double(fv.get("depth").toString()));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments("<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>");
                fv.put("depth", "");
            } catch (NullPointerException npe) {
                fv.put("depth", "");
            }
        }

        //let's handle the GPS
        if ((fv.get("lat") != null) && (fv.get("longitude") != null) && !fv.get("lat").toString().equals("")
                && !fv.get("longitude").toString().equals("")) {
            //enc.setGPSLatitude(lat + "&deg; " + gpsLatitudeMinutes + "\' " + gpsLatitudeSeconds + "\" " + latDirection);

            try {
                double degrees = (new Double(fv.get("lat").toString())).doubleValue();
                double position = degrees;
                /*
                if (!gpsLatitudeMinutes.equals("")) {
                  double minutes2 = ((new Double(gpsLatitudeMinutes)).doubleValue()) / 60;
                  position += minutes2;
                }
                if (!gpsLatitudeSeconds.equals("")) {
                  double seconds2 = ((new Double(gpsLatitudeSeconds)).doubleValue()) / 3600;
                  position += seconds2;
                }
                if (latDirection.toLowerCase().equals("south")) {
                  position = position * -1;
                }*/
                enc.setDWCDecimalLatitude(position);

                double degrees2 = (new Double(fv.get("longitude").toString())).doubleValue();
                double position2 = degrees2;
                enc.setDWCDecimalLongitude(position2);
                llSet = true;

            } catch (Exception e) {
                System.out.println("EncounterSetGPS: problem!");
                e.printStackTrace();
            }

        }

        //enc.setMeasureUnits("Meters");
        // enc.setSubmitterPhone(getVal(fv, "submitterPhone"));
        //enc.setSubmitterAddress(getVal(fv, "submitterAddress"));

        // enc.setPhotographerPhone(getVal(fv, "photographerPhone"));
        // enc.setPhotographerAddress(getVal(fv, "photographerAddress"));
        // enc.setPhotographerName(getVal(fv, "photographerName"));
        // enc.setPhotographerEmail(getVal(fv, "photographerEmail"));
        enc.addComments("<p>Submitted on " + (new java.util.Date()).toString() + " from address: "
                + ServletUtilities.getRemoteHost(request) + "</p>");
        //enc.approved = false;

        enc.addComments(processingNotes.toString());

        if (CommonConfiguration.getProperty("encounterState0", context) != null) {
            enc.setState(CommonConfiguration.getProperty("encounterState0", context));
        }
        if (request.getRemoteUser() != null) {
            enc.setSubmitterID(request.getRemoteUser());
        } else {
            enc.setSubmitterID("N/A");
        }
        if (!getVal(fv, "locCode").equals("")) {
            enc.setLocationCode(locCode);
        }
        if (!getVal(fv, "country").equals("")) {
            enc.setCountry(getVal(fv, "country"));
        }

        // xxxxxxx
        //add research team for GAq
        if (!getVal(fv, "researchTeam").equals("")) {
            enc.setDynamicProperty("Research Team", (getVal(fv, "researchTeam")));
        }
        if (!getVal(fv, "vessel").equals("")) {
            enc.setDynamicProperty("Vessel", (getVal(fv, "vessel")));
        }
        if (!getVal(fv, "conditions").equals("")) {
            enc.setDynamicProperty("Conditions", (getVal(fv, "conditions")));
        }

        if (!getVal(fv, "camera").equals("")) {
            enc.setDynamicProperty("Camera", (getVal(fv, "camera")));
        }
        if (!getVal(fv, "lens").equals("")) {
            enc.setDynamicProperty("Lens", (getVal(fv, "lens")));
        }
        if (!getVal(fv, "card").equals("")) {
            enc.setDynamicProperty("Card", (getVal(fv, "card")));
        }
        if (!getVal(fv, "folder").equals("")) {
            enc.setDynamicProperty("Folder", (getVal(fv, "folder")));
        }

        if (!getVal(fv, "numberOfBoats").equals("")) {
            enc.setDynamicProperty("Number of boats", (getVal(fv, "numberOfBoats")));
        }

        if (!getVal(fv, "startTime").equals("")) {
            enc.setDynamicProperty("Start Time", (getVal(fv, "startTime")));
        }

        if (!getVal(fv, "endTime").equals("")) {
            enc.setDynamicProperty("End Time", (getVal(fv, "endTime")));
        }

        if (!getVal(fv, "endLongitude").equals("")) {
            enc.setDynamicProperty("End Longitude", (getVal(fv, "endLongitude")));
        }
        if (!getVal(fv, "endLatitude").equals("")) {
            enc.setDynamicProperty("End Latitude", (getVal(fv, "endLatitude")));
        }

        if (!getVal(fv, "startLongitude").equals("")) {
            enc.setDynamicProperty("Start Longitude", (getVal(fv, "startLongitude")));
        }
        if (!getVal(fv, "startLatitude").equals("")) {
            enc.setDynamicProperty("Start Latitude", (getVal(fv, "startLatitude")));
        }

        if (!getVal(fv, "beginWaypoint").equals("")) {
            enc.setDynamicProperty("Begin Waypoint", (getVal(fv, "beginWaypoint")));
        }
        if (!getVal(fv, "endWaypoint").equals("")) {
            enc.setDynamicProperty("End Waypoint", (getVal(fv, "endWaypoint")));
        }

        //xxxxxxxx

        String guid = CommonConfiguration.getGlobalUniqueIdentifierPrefix(context) + encID;

        //new additions for DarwinCore
        enc.setDWCGlobalUniqueIdentifier(guid);
        enc.setDWCImageURL((request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number=" + encID));

        //populate DarwinCore dates

        DateTimeFormatter fmt = ISODateTimeFormat.date();
        String strOutputDateTime = fmt.print(dt);
        enc.setDWCDateAdded(strOutputDateTime);
        enc.setDWCDateAdded(new Long(dt.toDateTime().getMillis()));
        //System.out.println("I set the date as a LONG to: "+enc.getDWCDateAddedLong());
        enc.setDWCDateLastModified(strOutputDateTime);

        //this will try to set from MediaAssetMetadata -- ymmv
        if (!llSet)
            enc.setLatLonFromAssets();
        if (enc.getYear() < 1)
            enc.setDateFromAssets();

        String newnum = "";
        if (!spamBot) {
            newnum = myShepherd.storeNewEncounter(enc, encID);
            enc.refreshAssetFormats(myShepherd);

            //*after* persisting this madness, then lets kick MediaAssets to IA for whatever fate awaits them
            //  note: we dont send Annotations here, as they are always(forever?) trivial annotations, so pretty disposable

            // might want to set detection status here (on the main thread)

            for (MediaAsset ma : enc.getMedia()) {
                ma.setDetectionStatus(IBEISIA.STATUS_INITIATED);
            }

            Task parentTask = null; //this is *not* persisted, but only used so intakeMediaAssets will inherit its params
            if (locCode != null) {
                parentTask = new Task();
                JSONObject tp = new JSONObject();
                JSONObject mf = new JSONObject();
                mf.put("locationId", locCode);
                tp.put("matchingSetFilter", mf);
                parentTask.setParameters(tp);
            }
            Task task = org.ecocean.ia.IA.intakeMediaAssets(myShepherd, enc.getMedia(), parentTask); //TODO are they *really* persisted for another thread (queue)
            myShepherd.storeNewTask(task);
            Logger log = LoggerFactory.getLogger(EncounterForm.class);
            log.info("New encounter submission: <a href=\"" + request.getScheme() + "://"
                    + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + encID
                    + "\">" + encID + "</a>");
            System.out.println("ENCOUNTER SAVED???? newnum=" + newnum + "; IA => " + task);
            org.ecocean.ShepherdPMF.getPMF(context).getDataStoreCache().evictAll();
        }

        if (newnum.equals("fail")) {
            request.setAttribute("number", "fail");
            return;
        }

        //return a forward to display.jsp
        System.out.println("Ending data submission.");
        if (!spamBot) {

            //send submitter on to confirmSubmit.jsp
            //response.sendRedirect(request.getScheme()+"://" + CommonConfiguration.getURLLocation(request) + "/confirmSubmit.jsp?number=" + encID);
            WebUtils.redirectToSavedRequest(request, response, ("/confirmSubmit.jsp?number=" + encID));

            //start email appropriate parties
            if (CommonConfiguration.sendEmailNotifications(context)) {
                myShepherd.beginDBTransaction();
                try {
                    // Retrieve background service for processing emails
                    ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService();
                    Properties submitProps = ShepherdProperties.getProperties("submit.properties",
                            ServletUtilities.getLanguageCode(request), context);
                    // Email new submission address(es) defined in commonConfiguration.properties
                    Map<String, String> tagMap = NotificationMailer.createBasicTagMap(request, enc);
                    List<String> mailTo = NotificationMailer
                            .splitEmails(CommonConfiguration.getNewSubmissionEmail(context));
                    String mailSubj = submitProps.getProperty("newEncounter") + enc.getCatalogNumber();
                    for (String emailTo : mailTo) {
                        NotificationMailer mailer = new NotificationMailer(context,
                                ServletUtilities.getLanguageCode(request), emailTo, "newSubmission-summary",
                                tagMap);
                        mailer.setUrlScheme(request.getScheme());
                        es.execute(mailer);
                    }

                    // Email those assigned this location code
                    if (enc.getLocationID() != null) {
                        String informMe = null;
                        try {
                            informMe = myShepherd.getAllUserEmailAddressesForLocationID(enc.getLocationID(),
                                    context);
                        } catch (Exception ef) {
                            ef.printStackTrace();
                        }
                        if (informMe != null) {
                            List<String> cOther = NotificationMailer.splitEmails(informMe);
                            for (String emailTo : cOther) {
                                NotificationMailer mailer = new NotificationMailer(context, null, emailTo,
                                        "newSubmission-summary", tagMap);
                                mailer.setUrlScheme(request.getScheme());
                                es.execute(mailer);
                            }
                        }
                    }

                    // Add encounter dont-track tag for remaining notifications (still needs email-hash assigned).
                    tagMap.put(NotificationMailer.EMAIL_NOTRACK, "number=" + enc.getCatalogNumber());

                    // Email submitter and photographer
                    if ((enc.getPhotographerEmails() != null) && (enc.getPhotographerEmails().size() > 0)) {
                        List<String> cOther = enc.getPhotographerEmails();
                        for (String emailTo : cOther) {
                            String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo,
                                    context);
                            tagMap.put(NotificationMailer.EMAIL_HASH_TAG,
                                    Encounter.getHashOfEmailString(emailTo));
                            NotificationMailer mailer = new NotificationMailer(context, null, emailTo,
                                    "newSubmission", tagMap);
                            mailer.setUrlScheme(request.getScheme());
                            es.execute(mailer);
                        }
                    }
                    if ((enc.getSubmitterEmails() != null) && (enc.getSubmitterEmails().size() > 0)) {
                        List<String> cOther = enc.getSubmitterEmails();
                        for (String emailTo : cOther) {

                            String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo,
                                    context);
                            tagMap.put(NotificationMailer.EMAIL_HASH_TAG,
                                    Encounter.getHashOfEmailString(emailTo));
                            NotificationMailer mailer = new NotificationMailer(context, null, emailTo,
                                    "newSubmission", tagMap);
                            mailer.setUrlScheme(request.getScheme());
                            es.execute(mailer);
                        }
                    }

                    // Email interested others
                    if ((enc.getInformOthersEmails() != null) && (enc.getInformOthersEmails().size() > 0)) {
                        List<String> cOther = enc.getInformOthersEmails();
                        for (String emailTo : cOther) {

                            String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo,
                                    context);
                            tagMap.put(NotificationMailer.EMAIL_HASH_TAG,
                                    Encounter.getHashOfEmailString(emailTo));
                            NotificationMailer mailer = new NotificationMailer(context, null, emailTo,
                                    "newSubmission", tagMap);
                            mailer.setUrlScheme(request.getScheme());
                            es.execute(mailer);
                        }
                    }
                    /*  
                    if ((enc.getInformOthers() != null) && (!enc.getInformOthers().trim().equals(""))) {
                      List<String> cOther = NotificationMailer.splitEmails(enc.getInformOthers());
                      for (String emailTo : cOther) {
                        String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo, context);
                        tagMap.put(NotificationMailer.EMAIL_HASH_TAG, Encounter.getHashOfEmailString(emailTo));
                        NotificationMailer mailer=new NotificationMailer(context, null, emailTo, "newSubmission", tagMap);
                        mailer.setUrlScheme(request.getScheme());
                        es.execute(mailer);
                      }
                    }
                    */

                    es.shutdown();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    myShepherd.rollbackDBTransaction();

                }
            } //end email appropriate parties

        } else {
            response.sendRedirect(
                    request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/spambot.jsp");
        }

    } //end "if (fileSuccess)

    myShepherd.closeDBTransaction();
    //return null;
}

From source file:org.ecocean.servlet.ServletUtilities.java

License:Open Source License

public static String getDate() {
    DateTime dt = new DateTime();
    DateTimeFormatter fmt = ISODateTimeFormat.date();
    return (fmt.print(dt));
}

From source file:org.ecocean.servlet.SubmitAction.java

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String mailList = "no";
    Calendar date = Calendar.getInstance();
    Random ran = new Random();
    String uniqueID = (new Integer(date.get(Calendar.DAY_OF_MONTH))).toString()
            + (new Integer(date.get(Calendar.MONTH) + 1)).toString()
            + (new Integer(date.get(Calendar.YEAR))).toString()
            + (new Integer(date.get(Calendar.HOUR_OF_DAY))).toString()
            + (new Integer(date.get(Calendar.MINUTE))).toString()
            + (new Integer(date.get(Calendar.SECOND))).toString() + (new Integer(ran.nextInt(99))).toString();
    String size = "";
    String elevation = "";
    String depth = "";
    String behavior = "";
    String lifeStage = "";
    String measureUnits = "", location = "", sex = "unknown", comments = "", primaryImageName = "",
            guess = "no estimate provided";
    String submitterName = "", submitterEmail = "", submitterPhone = "", submitterAddress = "",
            submitterOrganization = "", submitterProject = "";
    String photographerName = "", photographerEmail = "", photographerPhone = "", photographerAddress = "";
    //Vector additionalImageNames = new Vector();
    ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>();

    int encounterNumber = 0;
    int day = 1, month = 1, year = 2003, hour = 12;
    String lat = "", longitude = "", latDirection = "", longDirection = "", scars = "None";
    String minutes = "00", gpsLongitudeMinutes = "", gpsLongitudeSeconds = "", gpsLatitudeMinutes = "",
            gpsLatitudeSeconds = "", submitterID = "N/A";
    String locCode = "", informothers = "";
    String livingStatus = "";
    String genusSpecies = "";
    String country = "";
    String locationID = "";
    Shepherd myShepherd;//w w  w.j  a v a  2s.  c om

    myShepherd = new Shepherd();

    if (form instanceof SubmitForm) {
        System.out.println("Starting data submission...");
        //this line is here for when the input page is upload-utf8.jsp,
        //it sets the correct character encoding for the response
        String encoding = request.getCharacterEncoding();
        if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
            response.setContentType("text/html; charset=utf-8");
        }

        //get the form to read data from
        SubmitForm theForm = (SubmitForm) form;

        mailList = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getMailList());
        date = theForm.getDate();
        uniqueID = theForm.getUniqueID();

        if ((theForm.getSize() != null) && (!theForm.getSize().equals(""))) {
            size = theForm.getSize();
        }

        if ((theForm.getDepth() != null) && (!theForm.getDepth().equals(""))) {
            depth = theForm.getDepth();
        }

        if ((theForm.getElevation() != null) && (!theForm.getElevation().equals(""))) {

            elevation = theForm.getElevation();
        }

        measureUnits = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getMeasureUnits());
        location = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLocation());
        System.out.println("SubmitAction location: " + location);
        sex = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getSex());
        comments = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getComments());
        if (theForm.getBehavior() != null) {
            behavior = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getBehavior());
        }
        if (theForm.getLifeStage() != null) {
            lifeStage = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLifeStage());
        }
        primaryImageName = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getPrimaryImageName());
        guess = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getGuess());
        submitterName = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getSubmitterName());
        submitterEmail = ServletUtilities.preventCrossSiteScriptingAttacks(
                theForm.getSubmitterEmail().replaceAll(";", ",").replaceAll(" ", ""));
        submitterPhone = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getSubmitterPhone());
        submitterAddress = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getSubmitterAddress());
        submitterOrganization = ServletUtilities
                .preventCrossSiteScriptingAttacks(theForm.getSubmitterOrganization());
        submitterProject = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getSubmitterProject());

        photographerName = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getPhotographerName());
        photographerEmail = ServletUtilities.preventCrossSiteScriptingAttacks(
                theForm.getPhotographerEmail().replaceAll(";", ",").replaceAll(" ", ""));
        photographerPhone = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getPhotographerPhone());
        photographerAddress = ServletUtilities
                .preventCrossSiteScriptingAttacks(theForm.getPhotographerAddress());
        //additionalImageNames = theForm.getAdditionalImageNames();
        encounterNumber = theForm.getEncounterNumber();
        livingStatus = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLivingStatus());
        genusSpecies = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getGenusSpecies());
        informothers = ServletUtilities.preventCrossSiteScriptingAttacks(
                theForm.getInformothers().replaceAll(";", ",").replaceAll(" ", ""));
        country = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getCountry());
        locationID = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLocationID());

        //check for spamBots
        boolean spamBot = false;
        StringBuffer spamFields = new StringBuffer();
        spamFields.append(theForm.getSubmitterPhone());
        spamFields.append(theForm.getSubmitterName());
        spamFields.append(theForm.getPhotographerPhone());
        spamFields.append(theForm.getPhotographerName());
        spamFields.append(theForm.getLocation());
        spamFields.append(theForm.getComments());
        if (theForm.getBehavior() != null) {
            spamFields.append(theForm.getBehavior());
        }

        if (spamFields.toString().toLowerCase().indexOf("porn") != -1) {
            spamBot = true;
        }

        if (spamFields.toString().toLowerCase().indexOf("href") != -1) {
            spamBot = true;
        }
        //else if(spamFields.toString().toLowerCase().indexOf("[url]")!=-1){spamBot=true;}
        //else if(spamFields.toString().toLowerCase().indexOf("url=")!=-1){spamBot=true;}
        //else if(spamFields.toString().toLowerCase().trim().equals("")){spamBot=true;}
        //else if((theForm.getSubmitterID()!=null)&&(theForm.getSubmitterID().equals("N%2FA"))) {spamBot=true;}

        locCode = "";
        if ((locationID != null) && (!locationID.trim().equals(""))) {
            locCode = locationID;
        }
        //see if the location code can be determined and set based on the location String reported
        else {
            String locTemp = location.toLowerCase().trim();
            Properties props = new Properties();

            int numAllowedPhotos = 4;

            try {
                props.load(getClass().getResourceAsStream("/bundles/submitActionClass.properties"));

                Enumeration m_enum = props.propertyNames();
                while (m_enum.hasMoreElements()) {
                    String aLocationSnippet = ((String) m_enum.nextElement()).trim();
                    if (locTemp.indexOf(aLocationSnippet) != -1) {
                        locCode = props.getProperty(aLocationSnippet);
                    }
                }
            } catch (Exception props_e) {
                props_e.printStackTrace();
            }

        } //end else
        //end location code setter

        day = theForm.getDay();
        month = theForm.getMonth();
        year = theForm.getYear();
        hour = theForm.getHour();
        submitterID = theForm.getSubmitterID();
        lat = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLat());
        longitude = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLongitude());
        latDirection = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLatDirection());
        longDirection = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getLongDirection());
        scars = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getScars());
        if (scars.equals("1")) {
            scars = "Tail (caudal) fin";
        } else if (scars.equals("0")) {
            scars = "None";
        } else if (scars.equals("2")) {
            scars = "1st dorsal fin";
        } else if (scars.equals("3")) {
            scars = "2nd dorsal fin";
        } else if (scars.equals("4")) {
            scars = "Left pectoral fin";
        } else if (scars.equals("5")) {
            scars = "Right pectoral fin";
        } else if (scars.equals("6")) {
            scars = "Head";
        } else if (scars.equals("7")) {
            scars = "Body";
        }

        minutes = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getMinutes());
        //hour=theForm.getHour();
        gpsLongitudeMinutes = ServletUtilities
                .preventCrossSiteScriptingAttacks(theForm.getGpsLongitudeMinutes());
        gpsLongitudeSeconds = ServletUtilities
                .preventCrossSiteScriptingAttacks(theForm.getGpsLongitudeSeconds());
        gpsLatitudeMinutes = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getGpsLatitudeMinutes());
        gpsLatitudeSeconds = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getGpsLatitudeSeconds());
        //retrieve the text data
        String text = theForm.getTheText();
        //retrieve the query string value
        String queryValue = theForm.getQueryParam();
        //retrieve the file representation
        FormFile[] file = new FormFile[4];
        file[0] = theForm.getTheFile1();
        file[1] = theForm.getTheFile2();
        file[2] = theForm.getTheFile3();
        file[3] = theForm.getTheFile4();
        //retrieve the file name
        String[] fileName = new String[4];
        try {
            fileName[0] = ServletUtilities.preventCrossSiteScriptingAttacks(file[0].getFileName());
        } catch (NullPointerException npe) {
            fileName[0] = null;
        }
        try {
            fileName[1] = ServletUtilities.preventCrossSiteScriptingAttacks(file[1].getFileName());
        } catch (NullPointerException npe) {
            fileName[1] = null;
        }
        try {
            fileName[2] = ServletUtilities.preventCrossSiteScriptingAttacks(file[2].getFileName());
        } catch (NullPointerException npe) {
            fileName[2] = null;
        }
        try {
            fileName[3] = ServletUtilities.preventCrossSiteScriptingAttacks(file[3].getFileName());
        } catch (NullPointerException npe) {
            fileName[3] = null;
        }
        //retrieve the content type
        String[] contentType = new String[4];
        try {
            contentType[0] = file[0].getContentType();
        } catch (NullPointerException npe) {
            contentType[0] = null;
        }
        try {
            contentType[1] = file[1].getContentType();
        } catch (NullPointerException npe) {
            contentType[1] = null;
        }
        try {
            contentType[2] = file[2].getContentType();
        } catch (NullPointerException npe) {
            contentType[2] = null;
        }
        try {
            contentType[3] = file[3].getContentType();
        } catch (NullPointerException npe) {
            contentType[3] = null;
        }
        boolean writeFile = theForm.getWriteFile();
        //retrieve the file size
        String[] fileSize = new String[4];
        try {
            fileSize[0] = (file[0].getFileSize() + " bytes");
        } catch (NullPointerException npe) {
            fileSize[0] = null;
        }
        try {
            fileSize[1] = (file[1].getFileSize() + " bytes");
        } catch (NullPointerException npe) {
            fileSize[1] = null;
        }
        try {
            fileSize[2] = (file[2].getFileSize() + " bytes");
        } catch (NullPointerException npe) {
            fileSize[2] = null;
        }
        try {
            fileSize[3] = (file[3].getFileSize() + " bytes");
        } catch (NullPointerException npe) {
            fileSize[3] = null;
        }
        String data = null;

        //File encountersDir = new File(getServlet().getServletContext().getRealPath("/encounters"));

        String rootWebappPath = getServlet().getServletContext().getRealPath("/");
        File webappsDir = new File(rootWebappPath).getParentFile();
        File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName());
        if (!shepherdDataDir.exists()) {
            shepherdDataDir.mkdir();
        }

        File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
        if (!encountersDir.exists()) {
            encountersDir.mkdir();
        }
        File thisEncounterDir = new File(encountersDir, uniqueID);

        boolean created = false;
        try {
            if ((!thisEncounterDir.exists()) && (!spamBot)) {
                created = thisEncounterDir.mkdir();
            }
            ;
        } catch (SecurityException sec) {
            System.out.println(
                    "Security exception thrown while trying to created the directory for a new encounter!");
        }
        //System.out.println("Created?: "+created);
        for (int iter = 0; iter < 4; iter++) {
            if ((!spamBot) && (fileName[iter] != null)) {
                try {

                    //retrieve the file data
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    InputStream stream = file[iter].getInputStream();
                    //System.out.println(writeFile);
                    if (!writeFile) {
                        //only write files out that are less than 9MB
                        if ((file[iter]
                                .getFileSize() < (CommonConfiguration.getMaxMediaSizeInMegabytes() * 1048576))
                                && (file[iter].getFileSize() > 0)) {

                            byte[] buffer = new byte[8192];
                            int bytesRead = 0;
                            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                                baos.write(buffer, 0, bytesRead);
                            }
                            data = new String(baos.toByteArray());
                        } else {
                            data = new String("The file is greater than 4MB or less than 1 byte, "
                                    + " and has not been written to stream." + " File Size: "
                                    + file[iter].getFileSize() + " bytes. This is a"
                                    + " limitation of this particular web application, hard-coded"
                                    + " in org.apache.struts.webapp.upload.UploadAction");
                        }
                    } else if ((!(file[iter].getFileName().equals(""))) && (file[iter].getFileSize() > 0)) {
                        //write the file to the file specified
                        //String writeName=file[iter].getFileName().replace('#', '_').replace('-', '_').replace('+', '_').replaceAll(" ", "_");
                        String writeName = ServletUtilities.cleanFileName(file[iter].getFileName());

                        //String writeName=URLEncoder.encode(file[iter].getFileName(), "UTF-8");
                        while (writeName.indexOf(".") != writeName.lastIndexOf(".")) {
                            writeName = writeName.replaceFirst("\\.", "_");
                        }
                        //System.out.println(writeName);
                        //additionalImageNames.add(writeName);
                        File writeMe = new File(thisEncounterDir, writeName);
                        images.add(new SinglePhotoVideo(uniqueID, writeMe));
                        OutputStream bos = new FileOutputStream(writeMe);
                        int bytesRead = 0;
                        byte[] buffer = new byte[8192];
                        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                            bos.write(buffer, 0, bytesRead);
                        }
                        bos.close();
                        data = "The file has been written to \"" + encounterNumber + "\\" + writeName + "\"";
                    }
                    //close the stream
                    stream.close();
                    baos.close();
                } catch (FileNotFoundException fnfe) {
                    System.out.println("File not found exception.\n");
                    fnfe.printStackTrace();
                    return null;
                } catch (IOException ioe) {
                    System.out.println("IO Exception.\n");
                    ioe.printStackTrace();
                    return null;
                }
            } //end if fileName[iter]!=null

        } //end for iter

        //now let's add our encounter to the database
        Encounter enc = new Encounter(day, month, year, hour, minutes, guess, location, submitterName,
                submitterEmail, images);
        enc.setComments(comments.replaceAll("\n", "<br>"));
        if (theForm.getReleaseDate() != null && theForm.getReleaseDate().length() > 0) {
            String dateStr = ServletUtilities.preventCrossSiteScriptingAttacks(theForm.getReleaseDate());
            String dateFormatPattern = CommonConfiguration.getProperty("releaseDateFormat");
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
                enc.setReleaseDate(simpleDateFormat.parse(dateStr));
            } catch (Exception e) {
                enc.addComments("<p>Reported release date was problematic: " + dateStr + "</p>");
            }
        }
        if (theForm.getBehavior() != null) {
            enc.setBehavior(behavior);
        }
        if (theForm.getLifeStage() != null) {
            enc.setLifeStage(lifeStage);
        }
        Map<String, Object> measurements = theForm.getMeasurements();
        for (String key : measurements.keySet()) {
            if (!key.endsWith("units") && !key.endsWith("samplingProtocol")) {
                String value = ((String) measurements.get(key)).trim();
                if (value.length() > 0) {
                    try {
                        Double doubleVal = Double.valueOf(value);
                        String units = (String) measurements.get(key + "units");
                        String samplingProtocol = (String) measurements.get(key + "samplingProtocol");
                        Measurement measurement = new Measurement(enc.getEncounterNumber(), key, doubleVal,
                                units, samplingProtocol);
                        enc.addMeasurement(measurement);
                    } catch (Exception ex) {
                        enc.addComments(
                                "<p>Reported measurement " + key + " was problematic: " + value + "</p>");
                    }
                }
            }
        }
        List<MetalTag> metalTags = getMetalTags(theForm);
        for (MetalTag metalTag : metalTags) {
            enc.addMetalTag(metalTag);
        }
        enc.setAcousticTag(getAcousticTag(theForm));
        enc.setSatelliteTag(getSatelliteTag(theForm));
        enc.setSex(sex);
        enc.setLivingStatus(livingStatus);

        //let's handle genus and species for taxonomy
        try {

            String genus = "";
            String specificEpithet = "";

            //now we have to break apart genus species
            StringTokenizer tokenizer = new StringTokenizer(genusSpecies, " ");
            if (tokenizer.countTokens() >= 2) {

                enc.setGenus(tokenizer.nextToken());
                enc.setSpecificEpithet(tokenizer.nextToken().replaceAll(",", "").replaceAll("_", " "));

            }
            //handle malformed Genus Species formats
            else {
                throw new Exception(
                        "The format of the submitted genusSpecies parameter did not have two tokens delimited by a space (e.g., \"Rhincodon typus\"). The submitted value was: "
                                + genusSpecies);
            }

        } catch (Exception le) {

        }

        enc.setDistinguishingScar(scars);
        int sizePeriod = 0;
        if ((measureUnits.equals("Feet"))) {

            if (!depth.equals("")) {
                try {
                    double tempDouble = (new Double(depth)).doubleValue() / 3.3;
                    String truncDepth = (new Double(tempDouble)).toString();
                    sizePeriod = truncDepth.indexOf(".");
                    truncDepth = truncDepth.substring(0, sizePeriod + 2);
                    depth = (new Double(truncDepth)).toString();
                } catch (java.lang.NumberFormatException nfe) {
                    enc.addComments("<p>Reported depth was problematic: " + depth + "</p>");
                    depth = "";
                } catch (NullPointerException npe) {
                    depth = "";
                }
            }

            if (!elevation.equals("")) {
                try {
                    double tempDouble = (new Double(elevation)).doubleValue() / 3.3;
                    String truncElev = (new Double(tempDouble)).toString();
                    //String truncElev = ((new Double(elevation)) / 3.3).toString();
                    sizePeriod = truncElev.indexOf(".");
                    truncElev = truncElev.substring(0, sizePeriod + 2);
                    elevation = (new Double(truncElev)).toString();
                } catch (java.lang.NumberFormatException nfe) {
                    enc.addComments("<p>Reported elevation was problematic: " + elevation + "</p>");
                    elevation = "";
                } catch (NullPointerException npe) {
                    elevation = "";
                }
            }
            if (!size.equals("")) {

                try {
                    double tempDouble = (new Double(size)).doubleValue() / 3.3;
                    String truncSize = (new Double(tempDouble)).toString();
                    //String truncSize = ((new Double(size)) / 3.3).toString();
                    sizePeriod = truncSize.indexOf(".");
                    truncSize = truncSize.substring(0, sizePeriod + 2);
                    size = (new Double(truncSize)).toString();
                } catch (java.lang.NumberFormatException nfe) {

                    enc.addComments("<p>Reported size was problematic: " + size + "</p>");
                    size = "";
                } catch (NullPointerException npe) {
                    size = "";
                }
            }
        }

        if (!size.equals("")) {
            try {
                enc.setSize(new Double(size));
            } catch (java.lang.NumberFormatException nfe) {

                enc.addComments("<p>Reported size was problematic: " + size + "</p>");
                size = "";
            } catch (NullPointerException npe) {
                size = "";
            }
        }

        //System.out.println("Depth in SubmitForm is:"+depth);
        if (!depth.equals("")) {
            try {
                enc.setDepth(new Double(depth));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments("<p>Reported depth was problematic: " + depth + "</p>");
                depth = "";
            } catch (NullPointerException npe) {
                depth = "";
            }
        }

        if (!elevation.equals("")) {
            try {
                enc.setMaximumElevationInMeters(new Double(elevation));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments("<p>Reported elevation was problematic: " + elevation + "</p>");
                elevation = "";
            } catch (NullPointerException npe) {
                elevation = "";
            }
        }

        //let's handle the GPS
        if (!lat.equals("") && !longitude.equals("")) {
            //enc.setGPSLatitude(lat + "&deg; " + gpsLatitudeMinutes + "\' " + gpsLatitudeSeconds + "\" " + latDirection);

            try {
                double degrees = (new Double(lat)).doubleValue();
                double position = degrees;
                /*
                if (!gpsLatitudeMinutes.equals("")) {
                  double minutes2 = ((new Double(gpsLatitudeMinutes)).doubleValue()) / 60;
                  position += minutes2;
                }
                if (!gpsLatitudeSeconds.equals("")) {
                  double seconds2 = ((new Double(gpsLatitudeSeconds)).doubleValue()) / 3600;
                  position += seconds2;
                }
                if (latDirection.toLowerCase().equals("south")) {
                  position = position * -1;
                }*/
                enc.setDWCDecimalLatitude(position);

                double degrees2 = (new Double(longitude)).doubleValue();
                double position2 = degrees2;
                enc.setDWCDecimalLongitude(position2);

            } catch (Exception e) {
                System.out.println("EncounterSetGPS: problem!");
                e.printStackTrace();
            }

        }
        //if (!(longitude.equals(""))) {
        //enc.setGPSLongitude(longitude + "&deg; " + gpsLongitudeMinutes + "\' " + gpsLongitudeSeconds + "\" " + longDirection);

        //try {

        /*
        if (!gpsLongitudeMinutes.equals("")) {
          double minutes2 = ((new Double(gpsLongitudeMinutes)).doubleValue()) / 60;
          position += minutes2;
        }
        if (!gpsLongitudeSeconds.equals("")) {
          double seconds = ((new Double(gpsLongitudeSeconds)).doubleValue()) / 3600;
          position += seconds;
        }
        if (longDirection.toLowerCase().equals("west")) {
          position = position * -1;
        }
        */

        //} catch (Exception e) {
        //  System.out.println("EncounterSetGPS: problem setting decimal longitude!");
        // e.printStackTrace();
        //}
        //}

        //if one is not set, set all to null
        /*
        if ((longitude.equals("")) || (lat.equals(""))) {
          enc.setGPSLongitude("");
          enc.setGPSLongitude("");
        //let's handle the GPS
          if (!(lat.equals(""))) {
                
                
              try {
        enc.setDWCDecimalLatitude(new Double(lat));
              }
              catch(Exception e) {
                System.out.println("EncounterSetGPS: problem setting decimal latitude!");
                e.printStackTrace();
              }
                
                
          }
          if (!(longitude.equals(""))) {
                
            try {
              enc.setDWCDecimalLongitude(new Double(longitude));
            }
            catch(Exception e) {
              System.out.println("EncounterSetGPS: problem setting decimal longitude!");
              e.printStackTrace();
            }
          }
          enc.setDWCDecimalLatitude(-9999.0);
          enc.setDWCDecimalLongitude(-9999.0);
        }
        */
        //finish the GPS

        //enc.setMeasureUnits("Meters");
        enc.setSubmitterPhone(submitterPhone);
        enc.setSubmitterAddress(submitterAddress);
        enc.setSubmitterOrganization(submitterOrganization);
        enc.setSubmitterProject(submitterProject);

        enc.setPhotographerPhone(photographerPhone);
        enc.setPhotographerAddress(photographerAddress);
        enc.setPhotographerName(photographerName);
        enc.setPhotographerEmail(photographerEmail);
        enc.addComments("<p>Submitted on " + (new java.util.Date()).toString() + " from address: "
                + request.getRemoteHost() + "</p>");
        //enc.approved = false;
        if (CommonConfiguration.getProperty("encounterState0") != null) {
            enc.setState(CommonConfiguration.getProperty("encounterState0"));
        }
        if (request.getRemoteUser() != null) {
            enc.setSubmitterID(request.getRemoteUser());
        } else if (submitterID != null) {
            enc.setSubmitterID(submitterID);
        } else {
            enc.setSubmitterID("N/A");
        }
        if (!locCode.equals("")) {
            enc.setLocationCode(locCode);
        }
        if (!country.equals("")) {
            enc.setCountry(country);
        }
        if (!informothers.equals("")) {
            enc.setInformOthers(informothers);
        }
        String guid = CommonConfiguration.getGlobalUniqueIdentifierPrefix() + uniqueID;

        //new additions for DarwinCore
        enc.setDWCGlobalUniqueIdentifier(guid);
        enc.setDWCImageURL(("http://" + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number=" + uniqueID));

        //populate DarwinCore dates
        DateTime dt = new DateTime();
        DateTimeFormatter fmt = ISODateTimeFormat.date();
        String strOutputDateTime = fmt.print(dt);
        enc.setDWCDateAdded(strOutputDateTime);
        enc.setDWCDateLastModified(strOutputDateTime);

        String newnum = "";
        if (!spamBot) {
            newnum = myShepherd.storeNewEncounter(enc, uniqueID);

            Logger log = LoggerFactory.getLogger(SubmitAction.class);
            log.info("New encounter submission: <a href=\"http://" + CommonConfiguration.getURLLocation(request)
                    + "/encounters/encounter.jsp?number=" + uniqueID + "\">" + uniqueID + "</a>");

        }

        if (newnum.equals("fail")) {
            request.setAttribute("number", "fail");
            return null;
        }

        //place the data into the request for retrieval from display.jsp
        request.setAttribute("number", Integer.toString(encounterNumber));

        //destroy the temporary file created
        if (fileName[0] != null) {
            file[0].destroy();
        }
        if (fileName[1] != null) {
            file[1].destroy();
        }
        if (fileName[2] != null) {
            file[2].destroy();
        }
        if (fileName[3] != null) {
            file[3].destroy();
        }
        file = null;

        //return a forward to display.jsp
        System.out.println("Ending data submission.");
        if (!spamBot) {
            response.sendRedirect("http://" + CommonConfiguration.getURLLocation(request)
                    + "/confirmSubmit.jsp?number=" + uniqueID);
        } else {
            response.sendRedirect("http://" + CommonConfiguration.getURLLocation(request) + "/spambot.jsp");
        }
    }

    myShepherd.closeDBTransaction();
    return null;
}

From source file:org.egov.api.adapter.UserAdapter.java

License:Open Source License

@Override
public JsonElement serialize(Citizen citizen, Type type, JsonSerializationContext context) {
    JsonObject jo = new JsonObject();
    if (citizen.getName() != null)
        jo.addProperty("name", citizen.getName());
    jo.addProperty("emailId", citizen.getEmailId());
    jo.addProperty("mobileNumber", citizen.getMobileNumber());
    jo.addProperty("userName", citizen.getUsername());
    if (citizen.getAltContactNumber() != null)
        jo.addProperty("altContactNumber", citizen.getAltContactNumber());
    if (citizen.getGender() != null)
        jo.addProperty("gender", citizen.getGender().name());
    if (citizen.getPan() != null)
        jo.addProperty("pan", citizen.getPan());
    if (citizen.getDob() != null) {
        DateTimeFormatter ft = DateTimeFormat.forPattern("yyyy-MM-dd");
        jo.addProperty("dob", ft.print(citizen.getDob().getTime()));
    }//from w  ww .j a v  a2 s.  c om
    if (citizen.getAadhaarNumber() != null)
        jo.addProperty("aadhaarNumber", citizen.getAadhaarNumber());
    if (citizen.getLocale() != null)
        jo.addProperty("preferredLanguage", citizen.getLocale());
    return jo;
}