List of usage examples for java.util Properties keys
@Override
public Enumeration<Object> keys()
From source file:bboss.org.apache.velocity.runtime.RuntimeInstance.java
/** * Add all the properties in props to the RuntimeInstance properties *//*from w ww . ja v a 2s .co m*/ public void setProperties(Properties props) { Enumeration en = props.keys(); while (en.hasMoreElements()) { String key = en.nextElement().toString(); setProperty(key, props.get(key)); } }
From source file:er.extensions.foundation.ERXProperties.java
/** * Returns all of the properties in the system mapped to their evaluated values, sorted by key. * /* w w w .j av a 2 s .c om*/ * @param properties * @param protectValues if <code>true</code>, keys with the word "password" in them will have their values removed * @return all of the properties in the system mapped to their evaluated values, sorted by key */ public static Map<String, String> propertiesMap(Properties properties, boolean protectValues) { Map<String, String> props = new TreeMap<String, String>(); for (Enumeration e = properties.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (protectValues && key.toLowerCase().contains("password")) { props.put(key, "<deleted for log>"); } else { props.put(key, String.valueOf(properties.getProperty(key))); } } return props; }
From source file:org.apache.synapse.Axis2SynapseController.java
/** * {@inheritDoc}/*from w w w . j a v a 2s . com*/ */ public SynapseConfiguration createSynapseConfiguration() { String synapseXMLLocation = serverConfigurationInformation.getSynapseXMLLocation(); Properties properties = SynapsePropertiesLoader.loadSynapseProperties(); if (serverConfigurationInformation.getResolveRoot() != null) { properties.put(SynapseConstants.RESOLVE_ROOT, serverConfigurationInformation.getResolveRoot()); } if (serverConfigurationInformation.getSynapseHome() != null) { properties.put(SynapseConstants.SYNAPSE_HOME, serverConfigurationInformation.getSynapseHome()); } if (synapseXMLLocation != null) { synapseConfiguration = SynapseConfigurationBuilder.getConfiguration(synapseXMLLocation, properties); } else { log.warn("System property or init-parameter '" + SynapseConstants.SYNAPSE_XML + "' is not specified. Using default configuration.."); synapseConfiguration = SynapseConfigurationBuilder.getDefaultConfiguration(); } Enumeration keys = properties.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); synapseConfiguration.setProperty(key, properties.getProperty(key)); } // Set the Axis2 ConfigurationContext to the SynapseConfiguration synapseConfiguration.setAxisConfiguration(configurationContext.getAxisConfiguration()); MessageContextCreatorForAxis2.setSynConfig(synapseConfiguration); // set the Synapse configuration into the Axis2 configuration Parameter synapseConfigurationParameter = new Parameter(SynapseConstants.SYNAPSE_CONFIG, synapseConfiguration); try { configurationContext.getAxisConfiguration().addParameter(synapseConfigurationParameter); } catch (AxisFault e) { handleFatal("Could not set parameters '" + SynapseConstants.SYNAPSE_CONFIG + "' to the Axis2 configuration : " + e.getMessage(), e); } addServerIPAndHostEntries(); return synapseConfiguration; }
From source file:org.globus.workspace.cloud.client.AllArgs.java
public void intakeProperties(Properties props, String sourceName, String sourcePath) throws ParameterProblem { this.print.dbg("\nAll properties in " + sourceName + " file:\n"); final Enumeration e = props.keys(); while (e.hasMoreElements()) { final String key = (String) e.nextElement(); String val = props.getProperty(key); this.print.dbg(" KEY : " + key); if (key.equals("vws.repository.s3key") || key.equals("vws.repository.s3id")) { val = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; }/*ww w . j a v a2 s . co m*/ this.print.dbg(" VALUE: " + val); this.print.dbg(" "); } this.print.flush(); // null checks: don't use if option already set. This is how the config // precedence is implemented with strings. With booleans and numbers // a matching "isConfigured" variable exists for each option. // // Config precedence reminder: cmdline > user props > default props if (this.factoryHostPort == null) { this.factoryHostPort = CloudClientUtil.getProp(props, Props.KEY_FACTORY_HOSTPORT); this.gotProp(Props.KEY_FACTORY_HOSTPORT, this.factoryHostPort, sourceName); } if (this.factoryID == null) { this.factoryID = CloudClientUtil.getProp(props, Props.KEY_FACTORY_IDENTITY); this.gotProp(Props.KEY_FACTORY_IDENTITY, this.factoryID, sourceName); } if (this.xferCanonicalID == null) { this.xferCanonicalID = CloudClientUtil.getProp(props, Props.KEY_CANONICAL_ID); this.gotProp(Props.KEY_CANONICAL_ID, this.xferCanonicalID, sourceName); } if (this.xferS3AllowSelfSigned == null) { this.xferS3AllowSelfSigned = CloudClientUtil.getProp(props, Props.KEY_S3_ALLOW_SELF_SIGNED); this.gotProp(Props.KEY_S3_ALLOW_SELF_SIGNED, this.xferS3AllowSelfSigned, sourceName); } if (this.xferS3Https == null) { this.xferS3Https = CloudClientUtil.getProp(props, Props.KEY_S3_HTTPS); this.gotProp(Props.KEY_S3_HTTPS, this.xferS3Https, sourceName); } if (this.xferS3ID == null) { this.xferS3ID = CloudClientUtil.getProp(props, Props.KEY_S3_ID); this.gotProp(Props.KEY_S3_ID, this.xferS3ID, sourceName); } if (this.xferS3Key == null) { this.xferS3Key = CloudClientUtil.getProp(props, Props.KEY_S3_KEY); // don't want keys all over the debug logs in the history directory this.gotProp(Props.KEY_S3_KEY, "[REDACTED]", sourceName); } if (this.xferS3BaseKey == null) { this.xferS3BaseKey = CloudClientUtil.getProp(props, Props.KEY_S3_BASEKEY); this.gotProp(Props.KEY_S3_BASEKEY, this.xferS3BaseKey, sourceName); } if (this.s3Bucket == null) { this.s3Bucket = CloudClientUtil.getProp(props, Props.KEY_S3_BUCKET); this.gotProp(Props.KEY_S3_BUCKET, this.s3Bucket, sourceName); } if (this.xferHostPort == null) { this.xferHostPort = CloudClientUtil.getProp(props, Props.KEY_XFER_HOSTPORT); this.gotProp(Props.KEY_XFER_HOSTPORT, this.xferHostPort, sourceName); } if (this.xferType == null) { this.xferType = CloudClientUtil.getProp(props, Props.KEY_XFER_TYPE); this.gotProp(Props.KEY_XFER_TYPE, this.xferType, sourceName); } if (this.gridftpID == null) { this.gridftpID = CloudClientUtil.getProp(props, Props.KEY_GRIDFTP_IDENTITY); this.gotProp(Props.KEY_GRIDFTP_IDENTITY, this.gridftpID, sourceName); } if (!this.memoryConfigured) { final String mem = CloudClientUtil.getProp(props, Props.KEY_MEMORY_REQ); if (mem != null) { this.memory = Integer.parseInt(mem); if (this.memory < 1) { throw new ParameterProblem("Configured memory (" + mem + ") is invalid (less than one)"); } this.memoryConfigured = true; this.gotProp(Props.KEY_MEMORY_REQ, Integer.toString(this.memory), sourceName); } } if (!this.coresConfigured) { final String corenum = CloudClientUtil.getProp(props, Props.KEY_CORES_REQ); if (corenum != null) { this.cores = Integer.parseInt(corenum); if (this.cores < 1) { throw new ParameterProblem("Configured cores (" + corenum + ") is invalid (less than one)"); } this.coresConfigured = true; this.gotProp(Props.KEY_CORES_REQ, Integer.toString(this.cores), sourceName); } } if (this.sshfile == null) { this.sshfile = CloudClientUtil.getProp(props, Props.KEY_SSHFILE); this.gotProp(Props.KEY_SSHFILE, this.sshfile, sourceName); } if (this.ssh_hostsfile == null) { this.ssh_hostsfile = CloudClientUtil.getProp(props, Props.KEY_SSH_KNOWN_HOSTS); this.gotProp(Props.KEY_SSH_KNOWN_HOSTS, this.ssh_hostsfile, sourceName); } if (this.targetBaseDirectory == null) { this.targetBaseDirectory = CloudClientUtil.getProp(props, Props.KEY_TARGET_BASEDIR); this.gotProp(Props.KEY_TARGET_BASEDIR, this.targetBaseDirectory, sourceName); } if (this.caHash == null) { this.caHash = CloudClientUtil.getProp(props, Props.KEY_CAHASH); this.gotProp(Props.KEY_CAHASH, this.caHash, sourceName); } if (!this.pollMsConfigured) { final String msString = CloudClientUtil.getProp(props, Props.KEY_POLL_INTERVAL); if (msString != null) { this.pollMs = Integer.parseInt(msString); this.pollMsConfigured = true; } } if (!this.useNotificationsConfigured) { final String bull = CloudClientUtil.getProp(props, Props.KEY_USE_NOTIFICATIONS); if (bull != null) { final Boolean setting = Boolean.valueOf(bull); this.useNotifications = setting.booleanValue(); this.useNotificationsConfigured = true; this.gotProp(Props.KEY_USE_NOTIFICATIONS, setting.toString(), sourceName); } } if (!this.propagationKeepPortConfigured) { final String bull = CloudClientUtil.getProp(props, Props.KEY_PROPAGATION_KEEPPORT); if (bull != null) { final Boolean setting = Boolean.valueOf(bull); this.propagationKeepPort = setting.booleanValue(); this.propagationKeepPortConfigured = true; this.gotProp(Props.KEY_PROPAGATION_KEEPPORT, setting.toString(), sourceName); } } if (this.propagationScheme == null) { final String scheme = CloudClientUtil.getProp(props, Props.KEY_PROPAGATION_SCHEME); if (scheme != null) { this.propagationScheme = scheme; this.gotProp(Props.KEY_PROPAGATION_SCHEME, scheme, sourceName); } } if (!this.timeoutMinutesConfigured) { final String timeoutString = CloudClientUtil.getProp(props, Props.KEY_XFER_TIMEOUT); if (timeoutString != null) { final double hours = Double.parseDouble(timeoutString); final double minutesDouble = hours * 60; this.print.dbg("Timeout minutes from properties: " + minutesDouble); // intentional loss of precision this.timeoutMinutes = (int) minutesDouble; this.print.dbg("Timeout minutes used: " + this.timeoutMinutes); this.timeoutMinutesConfigured = true; this.gotProp(Props.KEY_XFER_TIMEOUT, Integer.toString(this.timeoutMinutes), sourceName); } } if (this.nimbusCertFile == null) { final String key = Props.KEY_NIMBUS_CERT; final String val = CloudClientUtil.getProp(props, key); if (val != null) { final String path = resolvePathProperty(key, val, sourcePath); this.nimbusCertFile = path; this.gotProp(key, path, sourceName); } } if (this.nimbusKeyFile == null) { final String key = Props.KEY_NIMBUS_KEY; final String val = CloudClientUtil.getProp(props, key); if (val != null) { final String path = resolvePathProperty(key, val, sourcePath); this.nimbusKeyFile = path; this.gotProp(key, path, sourceName); } } // ---- if (this.metadata_association == null) { final String key = Props.KEY_METADATA_ASSOCIATION; final String val = CloudClientUtil.getProp(props, key); this.metadata_association = val; this.gotProp(key, val, sourceName); } if (this.metadata_cpuType == null) { final String key = Props.KEY_METADATA_CPUTYPE; final String val = CloudClientUtil.getProp(props, key); this.metadata_cpuType = val; this.gotProp(key, val, sourceName); } if (this.metadata_fileName == null) { final String key = Props.KEY_METADATA_FILENAME; final String val = CloudClientUtil.getProp(props, key); this.metadata_fileName = val; this.gotProp(key, val, sourceName); } if (this.metadata_mountAs == null) { final String key = Props.KEY_METADATA_MOUNTAS; final String val = CloudClientUtil.getProp(props, key); this.metadata_mountAs = val; this.gotProp(key, val, sourceName); } if (this.metadata_nicName == null) { final String key = Props.KEY_METADATA_NICNAME; final String val = CloudClientUtil.getProp(props, key); this.metadata_nicName = val; this.gotProp(key, val, sourceName); } if (this.metadata_vmmType == null) { final String key = Props.KEY_METADATA_VMMTYPE; final String val = CloudClientUtil.getProp(props, key); this.metadata_vmmType = val; this.gotProp(key, val, sourceName); } if (this.metadata_vmmVersion == null) { final String key = Props.KEY_METADATA_VMMVERSION; final String val = CloudClientUtil.getProp(props, key); this.metadata_vmmVersion = val; this.gotProp(key, val, sourceName); } if (this.deploymentRequest_fileName == null) { final String key = Props.KEY_DEPREQ_FILENAME; final String val = CloudClientUtil.getProp(props, key); this.deploymentRequest_fileName = val; this.gotProp(key, val, sourceName); } // ---- if (this.brokerPublicNicPrefix == null) { final String key = Props.KEY_BROKER_PUB; final String val = CloudClientUtil.getProp(props, key); this.brokerPublicNicPrefix = val; this.gotProp(key, val, sourceName); } if (this.brokerLocalNicPrefix == null) { final String key = Props.KEY_BROKER_LOCAL; final String val = CloudClientUtil.getProp(props, key); this.brokerLocalNicPrefix = val; this.gotProp(key, val, sourceName); } if (this.brokerURL == null) { final String key = Props.KEY_BROKER_URL; final String val = CloudClientUtil.getProp(props, key); this.brokerURL = val; this.gotProp(key, val, sourceName); } if (this.brokerID == null) { final String key = Props.KEY_BROKER_IDENTITY; final String val = CloudClientUtil.getProp(props, key); this.brokerID = val; this.gotProp(key, val, sourceName); } }
From source file:org.apache.jmeter.JMeter.java
@Override public String[][] getIconMappings() { final String defaultIconProp = "org/apache/jmeter/images/icon.properties"; //$NON-NLS-1$ final String iconSize = JMeterUtils.getPropDefault(TREE_ICON_SIZE, DEFAULT_TREE_ICON_SIZE); String iconProp = JMeterUtils.getPropDefault("jmeter.icons", defaultIconProp);//$NON-NLS-1$ Properties p = JMeterUtils.loadProperties(iconProp); if (p == null && !iconProp.equals(defaultIconProp)) { log.info(iconProp + " not found - using " + defaultIconProp); iconProp = defaultIconProp;// w w w .ja va 2 s . c o m p = JMeterUtils.loadProperties(iconProp); } if (p == null) { log.info(iconProp + " not found - using inbuilt icon set"); return DEFAULT_ICONS; } log.info("Loaded icon properties from " + iconProp); String[][] iconlist = new String[p.size()][3]; Enumeration<?> pe = p.keys(); int i = 0; while (pe.hasMoreElements()) { String key = (String) pe.nextElement(); String[] icons = JOrphanUtils.split(p.getProperty(key), " ");//$NON-NLS-1$ iconlist[i][0] = key; iconlist[i][1] = icons[0].replace(KEY_SIZE, iconSize); if (icons.length > 1) { iconlist[i][2] = icons[1].replace(KEY_SIZE, iconSize); } i++; } return iconlist; }
From source file:org.alfresco.reporting.processor.NodeRefBasedPropertyProcessor.java
/** * Harvests 1) objects 2) closed tasks after date x *///from w ww. j av a 2s . c o m public void havestNodes(final NodeRef harvestDefinition) { /* * for each store:stores for each table:tables while continue search * continue = search.size>0 for each result:resultset if isVersioned * addAllOlderVersionsToQueue(result) addToQueue(result) processQueue() * // end while continue // end for each table // end for each store */ logger.info("harvest run start..."); ; try { final ArrayList<StoreRef> storeList = getStoreRefList(); final Properties queries = getTableQueries(harvestDefinition); final String language = reportingHelper.getSearchLanguage(harvestDefinition); // Make sure there is a connection dbhb.openReportingConnection(); Enumeration<Object> keys = queries.keys(); String fullQuery; // is the actual query appending orderby // node-dbid, and lastmodifued clause // Cycle all Lucene queries while (keys.hasMoreElements()) { String tableName = (String) keys.nextElement(); String query = (String) queries.get(tableName); tableName = dbhb.fixTableColumnName(tableName); if (logger.isDebugEnabled()) logger.debug("harvest: preparing table =" + tableName); // get a clean iterator to cycle all stores Iterator<StoreRef> storeIterator = storeList.iterator(); Date lastModified = null; boolean archiveAllowed = false; // prevent having two threads doing the same if (!dbhb.tableIsRunning(tableName)) { String nowFormattedDate = getNowAsFormattedString(); String timestamp = ""; // old school all-in-one harvesting if (!getBatchTimestampEnabled()) { dbhb.setLastTimestampStatusRunning(tableName); timestamp = dbhb.getLastTimestamp(tableName); } // else, see 5 lines below dbhb.createEmptyTables(tableName); int maxItems = getMaxLoopSize(); while (storeIterator.hasNext()) { StoreRef storeRef = storeIterator.next(); // mew insight, limit the number of loops, treat // mechanism with more care if (getBatchTimestampEnabled()) { dbhb.setLastTimestampStatusRunning( tableName + "_" + storeRef.getProtocol().substring(0, 1)); timestamp = dbhb .getLastTimestamp(tableName + "_" + storeRef.getProtocol().substring(0, 1)); } if (logger.isDebugEnabled()) logger.debug("harvest: StoreRef=" + storeRef.getProtocol() + ", archiveAllowed=" + archiveAllowed); // (re)set some essential process markers. // These are local to the run-per-storeRef long startDbId = 0; // the original database id of // the noderef long loopcount = 0; // count the number of // harvesting loops. Should be // <=2 for initial harvesting // agaist factory repo boolean letsContinue = true; // break if we process the archive before the // workspace is done... if (storeRef.getProtocol().equals(StoreRef.PROTOCOL_ARCHIVE) && !archiveAllowed) { letsContinue = false; } if (logger.isDebugEnabled()) logger.debug("harvest: before while, letsContinue=" + letsContinue); while (letsContinue) { loopcount++; // hasEverRun is needed to determine if an // update of lastModifiedTimestamp has occured // ever in a batch, or never. boolean hasEverRun = false; if (logger.isInfoEnabled()) { logger.info("++ Loop number: " + loopcount + ", tablename: " + tableName + ", archive: " + archiveAllowed); } if (getBatchTimestampEnabled()) { // default = // true nowFormattedDate = getNowAsFormattedString(); } fullQuery = query + queryClauseTimestamp(language, timestamp, storeRef.getProtocol()) + queryClauseOrderBy(language, startDbId, storeRef.getProtocol()); if (logger.isDebugEnabled()) { logger.debug("harvest: StoreProtocol = " + storeRef.getProtocol() + ", archive: " + archiveAllowed + "\nfullQuery = " + fullQuery); } SearchParameters sp = new SearchParameters(); sp.setLanguage(language); sp.addStore(storeRef); sp.setQuery(fullQuery); // sp.addSort(getOrderBy(language), true); if (maxItems > 0) { sp.setMaxItems(maxItems); } if (logger.isDebugEnabled()) { logger.debug("Searchparameter query: " + sp.getQuery()); } ResultSet results = getSearchService().query(sp); if (logger.isDebugEnabled()) logger.debug("harvest: prepare flipping: archiveAllowed=" + archiveAllowed + ", length=" + results.length()); // allow harvesting the archive if the workspace // has been done! // workspace is done if there are no more search // results if (results.length() == 0 && !archiveAllowed) { if (logger.isDebugEnabled()) logger.debug("harvest: flipping to archiveAllowed=true"); archiveAllowed = true; } letsContinue = stillContinueHarvesting(loopcount, results.length()); logger.debug("harvest: loopcount= " + loopcount + "\n" + "harvest: resultsize = " + results.length() + "\n" + "harvest: letsContinue = " + letsContinue + "\n" + "harvest: archiveAllow = " + archiveAllowed + "\n" + "harvest: tablename = " + tableName); SimpleDateFormat sdf = getSimpleDateFormat(); if (letsContinue) { Iterator<ResultSetRow> resultsIterator = results.iterator(); while (resultsIterator.hasNext()) { try { // be tolerant for non-existing // nodes... happens to hurt // leaving status=Running NodeRef result = resultsIterator.next().getNodeRef(); logger.debug("harvest noderef " + result); if (!storeRef.getProtocol().equalsIgnoreCase("archive")) { if (getNodeService().hasAspect(result, ContentModel.ASPECT_VERSIONABLE) // versionService.isVersioned(result) && versionService.getVersionHistory(result).getAllVersions() .size() > 1) { VersionHistory vh = versionService.getVersionHistory(result); Iterator<Version> vhi = vh.getAllVersions().iterator(); String latestVersionLabel = (String) nodeService.getProperty( vh.getHeadVersion().getVersionedNodeRef(), ContentModel.PROP_VERSION_LABEL); // Date latestDate = // (Date)nodeService.getProperty(result, // ContentModel.PROP_MODIFIED); while (vhi.hasNext()) { Version version = vhi.next(); String currentVersionLabel = version.getVersionLabel(); // Date versionDate = // version.getFrozenModifiedDate(); // logger.debug("comparing: // " + // currentVersionLabel + // "/" + // latestVersionLabel // );//+ " and " + // sdf.format(versionDate) // +"/"+ // sdf.format(latestDate)); if (!currentVersionLabel.equals(latestVersionLabel)) { if (logger.isInfoEnabled()) logger.info( "harvest: Adding Version " + currentVersionLabel + " " + version.getFrozenStateNodeRef() + " - " + result.toString()); // version.getVersionedNodeRef()); addToQueue(version.getFrozenStateNodeRef(), result); } else { if (logger.isDebugEnabled()) logger.info("Ignoring version " + currentVersionLabel); } // end ifelse } // end while } // id if // hasAspect(versionable) } // end exclude Archive // all versions should be post-fixed // with their head version workspace // ref if (!result.toString().startsWith("version")) { if (logger.isDebugEnabled()) logger.debug("harvest: " + " adding NodeRef " + result); addToQueue(result); } } catch (Exception e) { // ignore, we need to buffer for // non-existing nodes... logger.info("NodeRef appears broken: " + e.getMessage()); logger.info(" " + e.getStackTrace()); } } // end resultsIterator try { // process the current queue Properties props = processQueueDefinition(tableName); if (logger.isDebugEnabled()) logger.debug("harvest: queueDef done, setting tableDefinition"); setTableDefinition(tableName, props); if (logger.isDebugEnabled()) logger.debug("harvest: tableDef done. Processing queue Values"); processQueueValues(tableName); // prep the queue for the next run resetQueue(); if (results.length() > 0) { // prepare the dbid for the next run startDbId = Long.parseLong(String.valueOf(getNodeService().getProperty( results.getNodeRef(results.length() - 1), ContentModel.PROP_NODE_DBID))); lastModified = (Date) getNodeService().getProperty( results.getNodeRef(results.length() - 1), ContentModel.PROP_MODIFIED); if (logger.isDebugEnabled()) { logger.debug("harvest: StoreProtocol = " + storeRef.getProtocol()); logger.debug("harvest: New start DBID=" + startDbId); logger.debug("harvest: New lastModified=" + lastModified); } } } catch (Exception e) { logger.info("harvest: something wrong with the noderef, skipping"); } if ((results.length() > 0) && getBatchTimestampEnabled() && (lastModified != null)) { if (logger.isDebugEnabled()) logger.debug("Setting Batch-based timestamp: " + getDateAsFormattedString(lastModified)); dbhb.setLastTimestamp(tableName + "_" + storeRef.getProtocol().substring(0, 1), getDateAsFormattedString(lastModified)); hasEverRun = true; } } // end if(letsContinue) if ((!letsContinue) && (results.length() == 0)) { // register lastruntimestamp anyway if (hasEverRun) { dbhb.setAllStatusesDoneForTable(); } else { dbhb.setLastTimestampAndStatusDone( tableName + "_" + storeRef.getProtocol().substring(0, 1), nowFormattedDate); } } letsContinue = stillContinueHarvesting(loopcount, results.length()); } // end while letsContinue } // end storeProtocol if (getBatchTimestampEnabled()) { // dbhb.setLastTimestamp(tableName, // getDateAsFormattedString(lastModified)); if (lastModified != null) { if (logger.isDebugEnabled()) logger.debug("Setting Batch-based status to done"); dbhb.setAllStatusesDoneForTable(); } } else { if (logger.isDebugEnabled()) logger.debug("Setting end-last-run-based timestamp"); dbhb.setLastTimestampAndStatusDone(tableName, nowFormattedDate); } // startDbId=0; } // end if tableIsRunning else { if (logger.isDebugEnabled()) logger.debug("harvest: table is running; leaving..."); } } // end while keys } catch (Exception e) { // e.printStackTrace(); logger.info("Fatality: " + e); } finally { // make sure we gently close the connection dbhb.closeReportingConnection(); } logger.info("harvest run done..."); }
From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java
/** * Processes requests from the client for both HTTP <code>GET</code> * and <code>POST</code> methods. * * @param request servlet request/*from w w w. j a va2s.c o m*/ * @param response servlet response */ protected void processRequest(String requestType, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String responseFormat = response_format_prop; // flags that the user has not set the response format boolean defaultResponseFormat = response_format_prop.equals("XML") ? true : false; ServiceOperationInterface service = null; String callbackFunction = null; log.info(">> Start processRequest(" + requestType + ") at " + new Date()); try { ServletContext context = getServletContext(); String scriptName = request.getParameter(PARAM_SCRIPTNAME1); // look for "service=xxxx" String contextPath = ""; /* If the service parameter is not specified then use the URL to get the service name... */ if (scriptName == null) { scriptName = request.getPathInfo(); contextPath = request.getContextPath(); /* //Put this in for debugging... System.out.println("****** -> pathInfo [" + request.getPathInfo() + "]"); System.out.println("****** -> pathTranslated [" + request.getPathTranslated() + "]"); System.out.println("****** -> contextPath [" + request.getContextPath() + "]"); System.out.println("****** -> localAddr [" + request.getLocalAddr() + "]"); System.out.println("****** -> localName [" + request.getLocalName() + "]"); System.out.println("****** -> requestURI [" + request.getRequestURI() + "]");//***** System.out.println("****** -> servletPath [" + request.getServletPath() + "]"); */ if (scriptName == null) { scriptName = "UNSPECIFIED_SERVICE"; } } /* See if the URI is mapped to another service... */ ServiceMapping serviceMapping; serviceMapping = serviceMapper.getURIMapping(""/*contextPath*/, scriptName, requestType); if (serviceMapping != null) { log.info("Redirect URI to [" + serviceMapping.getServiceName() + "]"); scriptName = serviceMapping.getServiceName(); /* If the URI has been mapped then see if the "Accept" header specifies the return type required... */ String accept = request.getHeader("Accept"); if (accept.indexOf("text/xml") != -1) { responseFormat = "XML"; defaultResponseFormat = false; } if (accept.indexOf("text/json") != -1) { responseFormat = "JSON"; defaultResponseFormat = false; } } if (scriptName.startsWith("/")) { scriptName = scriptName.substring(1, scriptName.length()); } /** * If "log" service invoked then process it... */ if (scriptName.equals("log")) { returnHTMLLog(response); return; } /** * If "health" service invoked then process it... */ if (scriptName.equals("health")) { returnHealth(response); return; } /* Check for the flag to return XML or JSON objects... */ if (request.getParameter(PARAM_RETURNXML) != null) { println(">> Servlet will return XML object."); responseFormat = "XML"; defaultResponseFormat = false; } else if (request.getParameter(PARAM_RETURNJSON) != null) { println(">> Servlet will return XML object."); responseFormat = "JSON"; defaultResponseFormat = false; } else if (request.getParameter(PARAM_RETURNRAW) != null) { println(">> Servlet will return raw text object."); responseFormat = "RAW"; defaultResponseFormat = false; } /* Check for the callback function parameter... */ callbackFunction = request.getParameter(PARAM_CALLBACK); /** * Check to see if the client wants a "Service Mapping Description" (SMD) for the 'service'... */ if (request.getParameter(PARAM_SMD) != null) { log.info("Client wants SMD for [" + scriptName + "]"); try { ServicePool pool = null; Map availableServices = null; ServiceMappingDescription smd = null; ServiceScriptPool serviceScriptPool = null; String serviceScriptName = null; String returnString = null; pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL); availableServices = pool.getAvailableServices(); smd = new ServiceMappingDescription(request.getRequestURL().toString(), request.getRequestURL().toString() + "?smd", null); for (Iterator it = availableServices.values().iterator(); it.hasNext();) { serviceScriptPool = (ServiceScriptPool) it.next(); serviceScriptName = serviceScriptPool.getPoolName(); /** * If the service script name begins with the passed in script name then add it to the * service mapping description... */ log.debug("scriptName = [" + scriptName + "], serviceScriptName = [" + serviceScriptName + "]"); if (scriptName.equals("") || serviceScriptName.startsWith(scriptName + "/") || serviceScriptName.equals(scriptName)) { smd.addOperation(serviceScriptName); service = serviceScriptPool.getService(); smd.setOperationDescription(service.getScriptDescription()); smd.setOperationTransport(service.getHTTPMethods()); smd.setOperationEnvelope("URL"); smd.setOperationContentType(service.getResponseFormat()); smd.setOperationParameters(serviceScriptPool.getServiceParameters()); smd.setOperationReturns(serviceScriptPool.getServiceReturns()); } } returnString = smd.getSMDJSONString(); writeResponse(returnString, "JSONRAW", callbackFunction, response); } catch (Exception ex) { log.error("Exception getting SMD: " + ex.toString()); ex.printStackTrace(); } return; } /** * Get the service and run it... */ println(">> Client wants to invoke the service [" + scriptName + "]"); try { service = getServiceScript(scriptName); } catch (Exception ex) { errorResponse(response, "Could not get an instance of the service [" + scriptName + "]: " + ex.toString(), responseFormat, callbackFunction); return; } if (service == null) { errorResponse(response, "Service [" + scriptName + "] not found.", responseFormat, callbackFunction); return; } /** * If the script exists in the toaster pool then invoke it */ println(">> Checking login required"); try { if (service.getLoginRequired().equals("true")) { HttpSession session = request.getSession(false); Object loggedIn = null; if (session != null) { loggedIn = session.getAttribute(ATTRIB_LOGGED_IN); } log.trace("**** SESSION = " + session); log.trace("**** Logged In = " + loggedIn); if (session == null || loggedIn == null || loggedIn.equals("true") == false) { errorResponse(response, "The service " + scriptName + " requires you to be logged in to run it.", responseFormat, callbackFunction); freeServiceScript(service); return; } /* Check that the logged in user is authorised to run the service... */ String validUsers; String[] validUsersArray; String user; String loggedInUser; boolean validUser; validUsers = service.getValidUsers(); validUsersArray = validUsers.split("[,]"); loggedInUser = (String) session.getAttribute(ATTRIB_LOGGED_IN_USER); validUser = false; for (int idx = 0; idx < validUsersArray.length; idx++) { user = validUsersArray[idx].trim(); if (user.equals("*")) { validUser = true; break; } if (user.equals(loggedInUser)) { validUser = true; break; } } if (validUser == false) { log.error("The user [" + loggedInUser + "] is not authorised to invoke the service [" + scriptName + "]"); errorResponse(response, "You are not authorised to invoke the service [" + scriptName + "]", responseFormat, callbackFunction); freeServiceScript(service); return; } } } catch (Exception ex) { errorResponse(response, "Could not check if login required for this service. " + ex.toString(), responseFormat, callbackFunction); return; } boolean scriptInputSet = false; /* * Go through the set of parameters passed to us and set them up in the service instance... */ for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) { String parameterName = (String) e.nextElement(); if (parameterName.equals(PARAM_SCRIPTNAME1) == true || parameterName.equals(PARAM_SCRIPTNAME2) == true || parameterName.equals(PARAM_RETURNXML) == true || parameterName.equals(PARAM_RETURNJSON) == true || parameterName.equals(PARAM_CALLBACK) == true) { continue; } String parameterValue = (String) request.getParameter(parameterName); if (parameterName.equals(PARAM_INPUTXML) == true) { service.setInputXML(parameterValue); scriptInputSet = true; continue; } if (parameterName.equals(PARAM_INPUTJSON) == true) { try { // The input object is a JSON object... so convert it into XML... JSONObject json = new JSONObject(parameterValue); service.setInputXML(XML.toString(json)); scriptInputSet = true; println("JSON converted to \n" + XML.toString(json)); } catch (JSONException ex) { errorResponse(response, "Could not create JSON object." + ex.toString() + ". " + ex.getStackTrace(), responseFormat, callbackFunction); freeServiceScript(service); return; } continue; } /* Any leftover parameters are query parameters. */ println("Query Parameter found... Setting " + parameterName + " to " + parameterValue); service.setParameter(parameterName, parameterValue); } // End of parameters for loop /* If there is content in the request then, unless we have already set it, this is the input to the script... */ if (requestType.equals("POST") && scriptInputSet == false) { try { BufferedReader reader = request.getReader(); StringBuffer buf = new StringBuffer(); String line; String postData; while ((line = reader.readLine()) != null) { buf.append(line); } postData = buf.toString(); log.debug("POST DATA: " + postData); if (postData.startsWith("<")) { service.setInputXML(postData); scriptInputSet = true; } else { try { // The input object is a JSON object... so convert it into XML... JSONObject json = new JSONObject(postData); service.setInputXML(XML.toString(json)); scriptInputSet = true; log.debug("POST JSON converted to \n" + XML.toString(json)); } catch (JSONException ex) { errorResponse(response, "Could not convert POSTed JSON object." + ex.toString() + ". " + ex.getStackTrace(), responseFormat, callbackFunction); freeServiceScript(service); return; } } } catch (Exception ex) { log.warn("Exception getting posted data: " + ex.toString()); errorResponse(response, "Could not convert posted data.", responseFormat, callbackFunction); freeServiceScript(service); return; } } /* If the service name has been redirected then set any parameters that where embedded in the URI... */ if (serviceMapping != null) { Properties serviceParameters = serviceMapping.getParameters(); String paramName; String paramValue; for (Enumeration<Object> en = serviceParameters.keys(); en.hasMoreElements();) { paramName = (String) en.nextElement(); paramValue = (String) serviceParameters.get(paramName); service.setParameter(paramName, paramValue); } } String serviceResultString = null; /** * Run the service script... */ service.setSessionRequest(request); service.setSessionResponse(response); service.setCallbackFunction(callbackFunction); /* Check if the service has a predefined output format... */ /* If the user has specified a format then that is used.. */ String operationResponseFormat; operationResponseFormat = service.getResponseFormat(); if (defaultResponseFormat == true && operationResponseFormat != null && operationResponseFormat.equals("") == false) { responseFormat = operationResponseFormat; } service.setInvokeResponseFormat(responseFormat); /* If this is a priviledged operation then pass in a reference to the servlet... */ String priviledgedOperation = service.getPriviledged(); if (priviledgedOperation.compareToIgnoreCase("true") == 0 || priviledgedOperation.compareToIgnoreCase("yes") == 0 || priviledgedOperation.compareToIgnoreCase("y") == 0) { service.setPriviledgedHelper(this); } serviceResultString = service.invokeOperation(); if (serviceResultString == null) { errorResponse(response, "Error invoking the operation.<br><b>" + service.getScriptMessage() + "</b>", responseFormat, callbackFunction); freeServiceScript(service); return; } /* Return the results... */ if (serviceResultString != null && serviceResultString.equals("") == false) { writeResponse(serviceResultString, responseFormat, callbackFunction, response); } println(">> Service script executed successfully."); /* Free the service instance... */ freeServiceScript(service); } catch (Exception ex) { errorResponse(response, "Exception processing request: " + ex.toString(), responseFormat, callbackFunction); ex.printStackTrace(); try { freeServiceScript(service); } catch (Exception x) { log.warn("Exception freeing a service instance: " + x.toString()); } return; } println(">> Finished processRequest() at " + new Date()); }
From source file:org.alfresco.reporting.script.AlfrescoReporting.java
/** * Given the input string, replace all namespaces where possible. * @param namespace//from w ww.ja v a 2s .co m * @return string whith replaced full namespaces into short namespace definitions */ private String replaceNameSpaces(String namespace) { // use regular expressions to do a global replace of the full namespace into the short version. Properties p = getNameSpaces(); Enumeration keys = p.keys(); while (keys.hasMoreElements()) { String into = (String) keys.nextElement(); String from = p.getProperty(into); namespace = namespace.replace(from, into); } namespace = namespace.replace("-", "_"); return namespace; }
From source file:org.nuxeo.launcher.NuxeoLauncher.java
/** * @throws PackageException/* w w w .j ava 2s . com*/ * @throws IOException * @since 5.6 */ protected boolean showConfig() throws IOException, PackageException { InstanceInfo nxInstance = new InstanceInfo(); log.info("***** Nuxeo instance configuration *****"); nxInstance.NUXEO_CONF = configurationGenerator.getNuxeoConf().getPath(); log.info("NUXEO_CONF: " + nxInstance.NUXEO_CONF); nxInstance.NUXEO_HOME = configurationGenerator.getNuxeoHome().getPath(); log.info("NUXEO_HOME: " + nxInstance.NUXEO_HOME); // CLID try { nxInstance.clid = getConnectBroker().getCLID(); log.info("Instance CLID: " + nxInstance.clid); } catch (NoCLID e) { // leave nxInstance.clid unset } catch (Exception e) { // something went wrong in the NuxeoConnectClient initialization errorValue = EXIT_CODE_UNAUTHORIZED; log.error("Could not initialize NuxeoConnectClient", e); return false; } // distribution.properties DistributionInfo nxDistrib; File distFile = new File(configurationGenerator.getConfigDir(), "distribution.properties"); if (!distFile.exists()) { // fallback in the file in templates distFile = new File(configurationGenerator.getNuxeoHome(), "templates"); distFile = new File(distFile, "common"); distFile = new File(distFile, "config"); distFile = new File(distFile, "distribution.properties"); } try { nxDistrib = new DistributionInfo(distFile); } catch (IOException e) { nxDistrib = new DistributionInfo(); } nxInstance.distribution = nxDistrib; log.info("** Distribution"); log.info("- name: " + nxDistrib.name); log.info("- server: " + nxDistrib.server); log.info("- version: " + nxDistrib.version); log.info("- date: " + nxDistrib.date); log.info("- packaging: " + nxDistrib.packaging); // packages List<LocalPackage> pkgs = getConnectBroker().getPkgList(); log.info("** Packages:"); List<String> pkgTemplates = new ArrayList<String>(); for (LocalPackage pkg : pkgs) { nxInstance.packages.add(new PackageInfo(pkg)); log.info(String.format("- %s (version: %s - id: %s - state: %s)", pkg.getName(), pkg.getVersion(), pkg.getId(), PackageState.getByValue(pkg.getState()).getLabel())); // store template(s) added by this package try { File installFile = pkg.getInstallFile(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(installFile); NodeList nodes = dom.getDocumentElement().getElementsByTagName("config"); for (int i = 0; i < nodes.getLength(); i++) { Element node = (Element) nodes.item(i); if (node.hasAttribute("addtemplate")) { pkgTemplates.add(node.getAttribute("addtemplate")); } } } catch (Exception e) { log.warn("Could not parse install file for " + pkg.getName(), e); } } // nuxeo.conf ConfigurationInfo nxConfig = new ConfigurationInfo(); nxConfig.dbtemplate = configurationGenerator.extractDatabaseTemplateName(); log.info("** Templates:"); log.info("Database template: " + nxConfig.dbtemplate); String userTemplates = configurationGenerator.getUserTemplates(); StringTokenizer st = new StringTokenizer(userTemplates, ","); while (st.hasMoreTokens()) { String template = st.nextToken(); if (template.equals(nxConfig.dbtemplate)) { continue; } if (pkgTemplates.contains(template)) { nxConfig.pkgtemplates.add(template); log.info("Package template: " + template); } else { File testBase = new File(configurationGenerator.getNuxeoHome(), ConfigurationGenerator.TEMPLATES + File.separator + template); if (testBase.exists()) { nxConfig.basetemplates.add(template); log.info("Base template: " + template); } else { nxConfig.usertemplates.add(template); log.info("User template: " + template); } } } log.info("** Settings from nuxeo.conf:"); Properties userConfig = configurationGenerator.getUserConfig(); @SuppressWarnings("rawtypes") Enumeration nxConfEnum = userConfig.keys(); while (nxConfEnum.hasMoreElements()) { String key = (String) nxConfEnum.nextElement(); String value = userConfig.getProperty(key); if (key.equals("JAVA_OPTS")) { value = getJavaOptsProperty(); } KeyValueInfo kv = new KeyValueInfo(key, value); nxConfig.keyvals.add(kv); if (!key.contains("password") && !key.equals(ConfigurationGenerator.PARAM_STATUS_KEY)) { log.info(key + "=" + value); } else { log.info(key + "=********"); } } nxInstance.config = nxConfig; log.info("****************************************"); printInstanceXMLOutput(nxInstance); return true; }
From source file:org.alfresco.reporting.script.AlfrescoReporting.java
/** * Validate if the unique sum of properties exists in the table definition. * Update the table definition if columns are not yet defined * @param props unique set of columns and their type * @throws SQLException//from w ww. java 2s . c o m */ private void setTableDefinition(Properties props, String tableName) throws SQLException { logger.debug("Enter setTableDefinition tableName=" + tableName); // get the existing table definition Connection conn = dbhb.getConnection(); conn.setAutoCommit(true); Statement stmt = conn.createStatement(); Properties tableDesc = dbhb.getTableDescription(stmt, tableName); // check if our properties are defined or not Enumeration keys = props.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String type = props.getProperty(key, "-"); if ((!"-".equals(type)) && ((!"".equals(type))) && (!tableDesc.containsKey(key))) { if (logger.isDebugEnabled()) logger.debug("Adding column: " + key + "=" + type); dbhb.extendTable(stmt, tableName, key, type); } else { if (logger.isDebugEnabled()) logger.debug("DEFINITION Column " + key + " already exists."); } // end if else } // end while logger.debug("Exit setTableDefinition"); }