List of usage examples for java.util Properties propertyNames
public Enumeration<?> propertyNames()
From source file:org.apache.directory.fortress.core.ldap.ApacheDsDataProvider.java
/** * Given a collection of {@link java.util.Properties}, convert to raw data name-value format and load into ldap * modification set in preparation for ldap modify. * * @param props contains {@link java.util.Properties} targeted for updating in ldap. * @param mods ldap modification set containing name-value pairs in raw ldap format. * @param attrName contains the name of the ldap attribute to be updated. * @param replace boolean variable, if set to true use {@link ModificationOperation#REPLACE_ATTRIBUTE} else {@link * ModificationOperation#ADD_ATTRIBUTE}. * @param separator contains the char value used to separate name and value in ldap raw format. *//*from w w w. j a v a 2 s. co m*/ protected void loadProperties(Properties props, List<Modification> mods, String attrName, boolean replace, char separator) { if (props != null && props.size() > 0) { if (replace) { mods.add(new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, attrName)); } for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String val = props.getProperty(key); // This LDAP attr is stored as a name-value pair separated by a ':'. mods.add(new DefaultModification(ModificationOperation.ADD_ATTRIBUTE, attrName, key + separator + val)); } } }
From source file:com.redhat.rcm.version.Cli.java
private void loadConfiguration() throws VManException { final Logger logger = LoggerFactory.getLogger(getClass()); File config = null;/* ww w .j av a 2s. c o m*/ if (configuration != null) { config = InputUtils.getFile(configuration, workspace); } if (config == null) { config = loadBootstrapConfig(); } if (config == null) { configLocation = DEFAULT_CONFIG_FILE.getAbsolutePath(); config = DEFAULT_CONFIG_FILE; } if (config != null && config.canRead()) { InputStream is = null; try { is = new FileInputStream(config); final Properties props = new Properties(); props.load(is); final StringWriter sWriter = new StringWriter(); for (final Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) { final String key = (String) e.nextElement(); sWriter.write(" "); sWriter.write(key); sWriter.write(" = "); sWriter.write(props.getProperty(key)); sWriter.write("\n"); } props.list(new PrintWriter(sWriter)); logger.info("Loading configuration from: " + config + ":\n\n" + sWriter); final File downloadsDir = VersionManagerSession.getDownloadsDir(workspace); final List<String> relocations = readListProperty(props, RELOCATIONS_PROPERTY); if (relocations != null) { relocatedCoords = readPropertiesList(relocations, downloadsDir, true); } else { relocatedCoords = new HashMap<String, String>(); } final List<String> mappingsLocations = readListProperty(props, PROPERTY_MAPPINGS_PROPERTY); if (mappingsLocations != null) { this.propertyMappings = readPropertiesList(mappingsLocations, downloadsDir, true); } else { this.propertyMappings = new HashMap<String, String>(); } if (removedPluginsList == null) { removedPlugins = readListProperty(props, REMOVED_PLUGINS_PROPERTY); } if (removedTestsList == null) { removedTests = readListProperty(props, REMOVED_TESTS_PROPERTY); } if (extensionsWhitelistList == null) { extensionsWhitelist = readListProperty(props, EXTENSIONS_WHITELIST_PROPERTY); } if (pomExcludeModules == null) { pomExcludeModules = props.getProperty(POM_EXCLUDE_MODULE_PROPERTY); } if (pomExcludePattern == null) { pomExcludePattern = props.getProperty(POM_EXCLUDE_FILE_PROPERTY); } if (modifications == null) { final List<String> lst = readListProperty(props, MODIFICATIONS); logger.info("modifications from properties: '" + join(lst, " ") + "'"); if (lst != null) { modders = modders == null ? new ArrayList<String>() : new ArrayList<String>(modders); modders.addAll(lst); } } if (bomList == null) { if (boms == null) { boms = new ArrayList<String>(); } final List<String> pBoms = readListProperty(props, BOMS_LIST_PROPERTY); if (pBoms != null) { boms.addAll(pBoms); } } if (toolchain == null) { toolchain = props.getProperty(TOOLCHAIN_PROPERTY); if (toolchain != null) { toolchain = toolchain.trim(); } } if (versionSuffix == null) { versionSuffix = props.getProperty(VERSION_SUFFIX_PROPERTY); if (versionSuffix != null) { versionSuffix = versionSuffix.trim(); } } if (versionModifier == null) { versionModifier = props.getProperty(VERSION_MODIFIER_PROPERTY); if (versionModifier != null) { versionModifier = versionModifier.trim(); } } if (remoteRepositories == null) { remoteRepositories = props.getProperty(REMOTE_REPOSITORIES_PROPERTY); if (remoteRepositories != null) { remoteRepositories = remoteRepositories.trim(); } else { remoteRepositories = props.getProperty(REMOTE_REPOSITORY_PROPERTY); if (remoteRepositories != null) { logger.warn("Using deprecated " + REMOTE_REPOSITORY_PROPERTY); remoteRepositories = remoteRepositories.trim(); } } } if (settings == null) { final String s = props.getProperty(SETTINGS_PROPERTY); if (s != null) { settings = s; } } if (localRepository == null) { final String l = props.getProperty(LOCAL_REPOSITORY_PROPERTY); if (l != null) { localRepository = new File(l); } } if (capturePom == null) { final String p = props.getProperty(CAPTURE_POM_PROPERTY); if (p != null) { capturePom = new File(p); } } if (!strict) { strict = Boolean .valueOf(props.getProperty(STRICT_MODE_PROPERTY, Boolean.toString(Boolean.FALSE))); } if (!useEffectivePoms) { useEffectivePoms = Boolean.valueOf( props.getProperty(USE_EFFECTIVE_POMS_PROPERTY, Boolean.toString(Boolean.FALSE))); } if (truststorePath == null) { truststorePath = props.getProperty(TRUSTSTORE_PATH_PROPERTY); } final Map<String, String> userProps = new HashMap<String, String>(); for (final Enumeration<?> keys = props.keys(); keys.hasMoreElements();) { final String key = (String) keys.nextElement(); if (key.startsWith(REPORT_PROPERTY_PREFIX)) { userProps.put(key.substring(REPORT_PROPERTY_PREFIX.length()), props.getProperty(key)); } } if (!userProps.isEmpty()) { if (reportProperties == null) { reportProperties = userProps; } else { userProps.putAll(reportProperties); reportProperties = userProps; } } } catch (final IOException e) { throw new VManException("Failed to load configuration from: " + config, e); } finally { closeQuietly(is); } } else { configLocation = "command-line"; } }
From source file:org.sakaibrary.osid.loader.OsidLoader.java
/** * Returns an instance of the org.osid.OsidManager of the OSID specified by the OSID * package org.osid.OsidManager interface name and the implementation package name. * The implementation class name is constructed from the SID package * Manager interface name. A configuration file name is constructed in a * similar manner and if the file exists it is loaded into the * implementation's org.osid.OsidManager's configuration. * /*from w w w . ja va 2 s . c om*/ * <p> * Example: To load an implementation of the org.osid.Filing OSID * implemented in a package "xyz", one would use: * </p> * * <p> * org.osid.filing.FilingManager fm = * (org.osid.filing.FilingManager)org.osid.OsidLoader.getManager( * </p> * * <p> * "org.osid.filing.FilingManager" , * </p> * * <p> * "xyz" , * </p> * * <p> * new org.osid.OsidContext()); * </p> * * @param osidPackageManagerName osidPackageManagerName is a fully * qualified org.osid.OsidManager interface name * @param implPackageName implPackageName is a fully qualified * implementation package name * @param context * @param additionalConfiguration * * @return org.osid.OsidManager * * @throws org.osid.OsidException An exception with one of the following * messages defined in org.osid.OsidException: {@link * org.osid.OsidException#OPERATION_FAILED OPERATION_FAILED}, * {@link org.osid.OsidException#NULL_ARGUMENT NULL_ARGUMENT}, * {@link org.osid.OsidException#VERSION_ERROR VERSION_ERROR}, * ={@link org.osid.OsidException#INTERFACE_NOT_FOUND * INTERFACE_NOT_FOUND}, ={@link * org.osid.OsidException#MANAGER_NOT_FOUND MANAGER_NOT_FOUND}, * ={@link org.osid.OsidException#MANAGER_INSTANTIATION_ERROR * MANAGER_INSTANTIATION_ERROR}, ={@link * org.osid.OsidException#ERROR_ASSIGNING_CONTEXT * ERROR_ASSIGNING_CONTEXT}, ={@link * org.osid.OsidException#ERROR_ASSIGNING_CONFIGURATION * ERROR_ASSIGNING_CONFIGURATION} */ public static org.osid.OsidManager getManager(String osidPackageManagerName, String implPackageName, org.osid.OsidContext context, java.util.Properties additionalConfiguration) throws org.osid.OsidException { try { if ((null != context) && (null != osidPackageManagerName) && (null != implPackageName)) { String osidInterfaceName = osidPackageManagerName; String className = makeClassName(osidPackageManagerName); String managerClassName = makeFullyQualifiedClassName(implPackageName, className); LOG.debug("osid interface name: " + osidInterfaceName); Class osidInterface = Class.forName(osidInterfaceName); if (null != osidInterface) { LOG.debug("osid manager class name: " + managerClassName); Class managerClass = Class.forName(managerClassName); if (null != managerClass) { if (osidInterface.isAssignableFrom(managerClass)) { org.osid.OsidManager manager = (org.osid.OsidManager) managerClass.newInstance(); if (null != manager) { try { manager.osidVersion_2_0(); } catch (Throwable ex) { throw new org.osid.OsidException(org.osid.OsidException.VERSION_ERROR); } try { manager.assignOsidContext(context); } catch (Exception ex) { throw new org.osid.OsidException( org.osid.OsidException.ERROR_ASSIGNING_CONTEXT); } try { java.util.Properties configuration = getConfiguration(manager); if (null == configuration) { configuration = new java.util.Properties(); } if (null != additionalConfiguration) { java.util.Enumeration enumer = additionalConfiguration.propertyNames(); while (enumer.hasMoreElements()) { java.io.Serializable key = (java.io.Serializable) enumer.nextElement(); if (null != key) { java.io.Serializable value = (java.io.Serializable) additionalConfiguration .get(key); if (null != value) { configuration.put(key, value); } } } } manager.assignConfiguration(configuration); LOG.debug("configuration has been assigned done."); return manager; } catch (Exception ex) { throw new org.osid.OsidException( org.osid.OsidException.ERROR_ASSIGNING_CONFIGURATION); } } throw new org.osid.OsidException(org.osid.OsidException.MANAGER_INSTANTIATION_ERROR); } throw new org.osid.OsidException(org.osid.OsidException.MANAGER_NOT_OSID_IMPLEMENTATION); } throw new org.osid.OsidException(org.osid.OsidException.MANAGER_NOT_FOUND); } throw new org.osid.OsidException(org.osid.OsidException.INTERFACE_NOT_FOUND); } throw new org.osid.OsidException(org.osid.OsidException.NULL_ARGUMENT); } catch (org.osid.OsidException oex) { LOG.error(oex.getMessage()); throw new org.osid.OsidException(oex.getMessage()); } catch (java.lang.Throwable ex) { LOG.error(ex.getMessage()); throw new org.osid.OsidException(org.osid.OsidException.OPERATION_FAILED); } }
From source file:com.janoz.usenet.searchers.impl.NewzbinConnectorImpl.java
@SuppressWarnings("unchecked") @Override/*from ww w .ja v a2s . co m*/ public synchronized List<NZB> search(String query, NewzbinCategory category, Integer minSize, Integer maxSize, Set<String> newsgroupsParam, Properties newzbinQueryPropsParam) throws SearchException { //Fill with defaults Set<String> newsgroups; if (newsgroupsParam == null) { newsgroups = this.defaultNewsgroups; } else { newsgroups = newsgroupsParam; } Properties newzbinQueryProps; if (newzbinQueryPropsParam == null) { newzbinQueryProps = this.defaultNewzbinQueryProps; } else { Properties tmpProps = new Properties(this.defaultNewzbinQueryProps); tmpProps.putAll(newzbinQueryPropsParam); newzbinQueryProps = tmpProps; } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("retention", "" + retention)); if (newsgroups != null && !newsgroups.isEmpty()) { params.add(new BasicNameValuePair("group", Util.implode(newsgroups, "+"))); } if (category != null) { params.add(new BasicNameValuePair("category", "" + category.getValue())); } if (minSize != null) { params.add(new BasicNameValuePair("u_post_larger_than", "" + minSize)); } if (maxSize != null) { params.add(new BasicNameValuePair("u_post_smaller_than", "" + maxSize)); } params.add(new BasicNameValuePair("query", query)); Enumeration<String> keys = (Enumeration<String>) newzbinQueryProps.propertyNames(); String label = null; String value = null; while (keys.hasMoreElements()) { label = keys.nextElement(); value = newzbinQueryProps.getProperty(label); if (value != null && value.trim().length() > 0) { params.add(new BasicNameValuePair(label, value)); } } HttpResponse response = null; BufferedReader br = null; try { HttpPost method = new HttpPost(constructURL("/api/reportfind/")); method.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); response = client.execute(method); if (LOG.isTraceEnabled()) { LogUtil.logResponseHeader(response); } int status = response.getStatusLine().getStatusCode(); switch (status) { case RESULT_OK: break; case RESULT_EMPTY: return Collections.emptyList(); case RESULT_UNAUTHORIZED: //Unauthorised, check username/password? LOG.error("Newzbin login failed"); throw new SearchException("Incorrect Newzbin credentials for '" + username + "' while searching."); case RESULT_PAYMENT_REQUIRED: //Payment Required, not Premium LOG.error("Payment needed"); throw new SearchException("No premium account while searching."); case RESULT_INTERNAL_SERVER_ERROR: throw new SearchException("Internal newzbin " + "server error while searching."); case RESULT_SERVICE_UNAVAILABLE: throw new SearchException("Newzbin.com currently " + "down while searching."); default: //Service Unavailable, site is currently down throw new SearchException( "Got unknown returncode " + status + " from newzbin.com while searching."); } //we got a result List<NZB> result = new ArrayList<NZB>(); InputStream is = response.getEntity().getContent(); //is = LogUtil.dumpStreamAndReOffer(is); br = new BufferedReader(new InputStreamReader(is, NEWZBIN_ENCODING)); br.readLine(); // read amount; String line; String[] fields; LazyNZB nzb; while (null != (line = br.readLine())) { fields = line.split("\t"); //REPORTID \t SIZE \t NAME nzb = new LazyNZB(Util.saveFileName(fields[2]) + ".nzb", this); nzb.setName(fields[2]); nzb.setReportId(Integer.parseInt(fields[0])); result.add(nzb); } return result; } catch (IOException e) { throw new SearchException("IO error during search.", e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOG.warn("Error while cleaning up request.", e); } } if (response != null) { try { response.getEntity().consumeContent(); } catch (IOException e) { LOG.warn("Error while cleaning up request.", e); } } } }
From source file:org.wso2.carbon.registry.jcr.RegistryNode.java
private Set getCollectionProperties(Properties propyList) { Set propNamesList = new HashSet(); Enumeration en = propyList.propertyNames(); while (en.hasMoreElements()) { String pName = en.nextElement().toString(); if ((pName != null) && (!isImplicitProperty(pName))) { propNamesList.add(pName);/* w ww .j a v a 2 s. c o m*/ } } return propNamesList; }
From source file:org.wso2.carbon.registry.jcr.RegistryNode.java
public PropertyIterator getProperties() throws RepositoryException { Set<String> propNamesList = new HashSet<String>(); Set<Property> properties = new HashSet<Property>(); Resource resource = null;/*from ww w . ja va2s . com*/ try { resource = registrySession.getUserRegistry().get(nodePath); if (resource instanceof org.wso2.carbon.registry.core.Collection) { String[] childPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren(); for (int i = 0; i < childPaths.length; i++) { Resource res = registrySession.getUserRegistry().get(childPaths[i]); if ((res instanceof ResourceImpl) && (res.getProperty("registry.jcr.property.type") != null)) { String[] temp = childPaths[i].split("/"); propNamesList.add(temp[temp.length - 1]); } } } Properties propyList = resource.getProperties(); Enumeration en = propyList.propertyNames(); while (en.hasMoreElements()) { String pName = en.nextElement().toString(); if ((pName != null) && (!isImplicitProperty(pName))) { propNamesList.add(pName); } } Iterator it = propNamesList.iterator(); while (it.hasNext()) { properties.add(getProperty(it.next().toString())); } } catch (Exception e) { String msg = "failed to resolve the path of the given node or violation of repository syntax " + this; log.debug(msg); throw new RepositoryException(msg, e); } RegistryPropertyIterator propertyIterator = new RegistryPropertyIterator(properties, this); return propertyIterator; }
From source file:org.sakaiproject.citation.impl.SakaiOsidLoader.java
/** * Returns an instance of the org.osid.OsidManager of the OSID specified by the OSID * package org.osid.OsidManager interface name and the implementation package name. * The implementation class name is constructed from the SID package * Manager interface name. A configuration file name is constructed in a * similar manner and if the file exists it is loaded into the * implementation's org.osid.OsidManager's configuration. * // w ww . j av a 2s. c om * <p> * Example: To load an implementation of the org.osid.Filing OSID * implemented in a package "xyz", one would use: * </p> * * <p> * org.osid.filing.FilingManager fm = * (org.osid.filing.FilingManager)org.osid.OsidLoader.getManager( * </p> * * <p> * "org.osid.filing.FilingManager" , * </p> * * <p> * "xyz" , * </p> * * <p> * new org.osid.OsidContext()); * </p> * * @param osidPackageManagerName osidPackageManagerName is a fully * qualified org.osid.OsidManager interface name * @param implPackageName implPackageName is a fully qualified * implementation package name * @param context * @param additionalConfiguration * * @return org.osid.OsidManager * * @throws org.osid.OsidException An exception with one of the following * messages defined in org.osid.OsidException: {@link * org.osid.OsidException#OPERATION_FAILED OPERATION_FAILED}, * {@link org.osid.OsidException#NULL_ARGUMENT NULL_ARGUMENT}, * {@link org.osid.OsidException#VERSION_ERROR VERSION_ERROR}, * ={@link org.osid.OsidException#INTERFACE_NOT_FOUND * INTERFACE_NOT_FOUND}, ={@link * org.osid.OsidException#MANAGER_NOT_FOUND MANAGER_NOT_FOUND}, * ={@link org.osid.OsidException#MANAGER_INSTANTIATION_ERROR * MANAGER_INSTANTIATION_ERROR}, ={@link * org.osid.OsidException#ERROR_ASSIGNING_CONTEXT * ERROR_ASSIGNING_CONTEXT}, ={@link * org.osid.OsidException#ERROR_ASSIGNING_CONFIGURATION * ERROR_ASSIGNING_CONFIGURATION} */ public static org.osid.OsidManager getManager(String osidPackageManagerName, String implPackageName, org.osid.OsidContext context, java.util.Properties additionalConfiguration) throws org.osid.OsidException { try { if ((null != context) && (null != osidPackageManagerName) && (null != implPackageName)) { String osidInterfaceName = osidPackageManagerName; String className = makeClassName(osidPackageManagerName); String managerClassName = makeFullyQualifiedClassName(implPackageName, className); // System.out.println("oin " + osidInterfaceName); Class osidInterface = Class.forName(osidInterfaceName); if (null != osidInterface) { // System.out.println("mcn " + managerClassName); Class managerClass = Class.forName(managerClassName); if (null != managerClass) { if (osidInterface.isAssignableFrom(managerClass)) { org.osid.OsidManager manager = (org.osid.OsidManager) managerClass.newInstance(); if (null != manager) { try { manager.osidVersion_2_0(); } catch (Throwable ex) { throw new org.osid.OsidException(org.osid.OsidException.VERSION_ERROR); } try { manager.assignOsidContext(context); } catch (Exception ex) { throw new org.osid.OsidException( org.osid.OsidException.ERROR_ASSIGNING_CONTEXT); } try { // System.out.println("man " + manager); java.util.Properties configuration = getConfiguration(manager); if (null == configuration) { configuration = new java.util.Properties(); } if (null != additionalConfiguration) { java.util.Enumeration enumer = additionalConfiguration.propertyNames(); // System.out.println("enumer " + enumer); while (enumer.hasMoreElements()) { java.io.Serializable key = (java.io.Serializable) enumer.nextElement(); // System.out.println("key "+key); if (null != key) { // System.out.println("Serializing...."); java.io.Serializable value = (java.io.Serializable) additionalConfiguration .get(key); // System.out.println("Done"); if (null != value) { configuration.put(key, value); // System.out.println("put complete"); } } } } //System.out.println("assigning..."); manager.assignConfiguration(configuration); //System.out.println("done."); return manager; } catch (Exception ex) { throw new org.osid.OsidException( org.osid.OsidException.ERROR_ASSIGNING_CONFIGURATION); } } throw new org.osid.OsidException(org.osid.OsidException.MANAGER_INSTANTIATION_ERROR); } throw new org.osid.OsidException(org.osid.OsidException.MANAGER_NOT_OSID_IMPLEMENTATION); } throw new org.osid.OsidException(org.osid.OsidException.MANAGER_NOT_FOUND); } throw new org.osid.OsidException(org.osid.OsidException.INTERFACE_NOT_FOUND); } throw new org.osid.OsidException(org.osid.OsidException.NULL_ARGUMENT); } catch (org.osid.OsidException oex) { M_log.warn("getManager() OsidException ", oex); throw new org.osid.OsidException(oex.getMessage()); } catch (java.lang.Throwable ex) { M_log.warn("getManager() Throwable ", ex); throw new org.osid.OsidException(org.osid.OsidException.OPERATION_FAILED); } }
From source file:org.openbravo.erpCommon.utility.Utility.java
/** * When updating core it is necessary to update Openbravo properties maintaining already assigned * properties. Thus properties in original file are preserved but the new ones in * Openbravo.properties.template file are added with the default value. * //from w ww.j a v a 2s .c o m * @throws IOException * @throws FileNotFoundException * @return false in case no changes where needed, true in case the merge includes some changes and * the original file is modified */ public static boolean mergeOpenbravoProperties(String originalFile, String newFile) throws FileNotFoundException, IOException { Properties origOBProperties = new Properties(); Properties newOBProperties = new Properties(); boolean modified = false; // load both files origOBProperties.load(new FileInputStream(originalFile)); newOBProperties.load(new FileInputStream(newFile)); Enumeration<?> newProps = newOBProperties.propertyNames(); while (newProps.hasMoreElements()) { String propName = (String) newProps.nextElement(); String origValue = origOBProperties.getProperty(propName); // try to get original value for new property, if it does not exist add it to original // properties with its default value if (origValue == null) { String newValue = newOBProperties.getProperty(propName); origOBProperties.setProperty(propName, newValue); modified = true; } } // save original file only in case it has modifications if (modified) { origOBProperties.store(new FileOutputStream(originalFile), "Automatically updated properties"); } return modified; }
From source file:org.ecocean.servlet.EncounterForm.java
@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); /*//from w ww . j ava 2s. 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"; } if (fv.get("social_files_id") != null) { //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); 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; } //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) { } System.out.println("about to do enc()"); Encounter enc = new Encounter(day, month, year, hour, minutes, guess, getVal(fv, "location"), getVal(fv, "submitterName"), getVal(fv, "submitterEmail"), null); boolean llSet = false; //Encounter enc = new Encounter(); //System.out.println("Submission detected date: "+enc.getDate()); String encID = enc.generateEncounterNumber(); 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 (FileItem item : formFiles) { JSONObject sp = astore.createParameters(new File(enc.subdir() + File.separator + item.getName())); sp.put("key", Util.hashDirectories(encID) + "/" + item.getName()); MediaAsset ma = new MediaAsset(astore, sp); File tmpFile = ma.localPath().toFile(); //conveniently(?) our local version to save ma.cacheLocal() from having to do anything? File tmpDir = tmpFile.getParentFile(); if (!tmpDir.exists()) tmpDir.mkdirs(); //System.out.println("attempting to write uploaded file to " + tmpFile); try { item.write(tmpFile); } catch (Exception ex) { System.out.println("Could not write " + tmpFile + ": " + ex.toString()); } if (tmpFile.exists()) { ma.addLabel("_original"); ma.copyIn(tmpFile); ma.updateMetadata(); newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma)); } else { System.out.println("failed to write file " + tmpFile); } } ///////////////////TODO social files also!!! 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); /* 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()); } 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 + "° " + 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.setSubmitterOrganization(getVal(fv, "submitterOrganization")); enc.setSubmitterProject(getVal(fv, "submitterProject")); 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: " + request.getRemoteHost() + "</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")); } if (!getVal(fv, "informothers").equals("")) { enc.setInformOthers(getVal(fv, "informothers")); } // 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(context, ServletUtilities.dataDir(context, rootDir)); enc.refreshAssetFormats(myShepherd); 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); } if (newnum.equals("fail")) { request.setAttribute("number", "fail"); return; } //return a forward to display.jsp System.out.println("Ending data submission."); if (!spamBot) { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/confirmSubmit.jsp?number=" + encID); } else { response.sendRedirect( request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/spambot.jsp"); } } //end "if (fileSuccess) myShepherd.closeDBTransaction(); //return null; }
From source file:com.enonic.cms.business.client.InternalClientImpl.java
private Map<String, String> toMap(Properties props) { HashMap<String, String> map = new HashMap<String, String>(); Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); map.put(key, props.getProperty(key)); }/*from w w w . j a v a 2 s .c o m*/ return map; }