List of usage examples for java.util Properties get
@Override
public Object get(Object key)
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 v a2 s. 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.processor.NodeRefBasedPropertyProcessor.java
/** * Harvests 1) objects 2) closed tasks after date x *//* w w w .ja va 2 s . 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.jaspersoft.jasperserver.war.xmla.XmlaRepositoryImpl.java
private Properties getMondrianConnectionProperties(MondrianServer server, DatabaseInfo databaseInfo, CatalogInfo catalogInfo, String roleName, Properties props) throws SQLException { //Get current session id String currentSessionId = getCurrentUserSessionId(); //Generated cached key based on authorized session id, datasource, catalog name and tenant id. String cacheKey = currentSessionId + "_" + databaseInfo.name + "_" + catalogInfo.name + "_" + catalogInfo.tenantId;//from ww w .j av a2s. c om Map<String, Object> connectProperties = new HashMap<String, Object>(); connectProperties.putAll(databaseInfo.properties); connectProperties.put("DataSourceInfo", catalogInfo.connectString); synchronized (this.olapConnectionPropertiesCache) { cleanExpired(this.olapConnectionPropertiesCache); Properties properties; if (olapConnectionPropertiesCache.get(cacheKey) != null) { properties = olapConnectionPropertiesCache.get(cacheKey).getValue(); } else { properties = xmlaContentFinder.getMondrianConnectionProperties(connectProperties, roleName); olapConnectionPropertiesCache.put(cacheKey, new CacheElement<Properties>(properties)); } // Save the server for the duration of the call to 'getConnection'. final LockBox.Entry entry = JsMondrianServerRegistry.INSTANCE.getLockBox().register(server); properties.setProperty(RolapConnectionProperties.Instance.name(), entry.getMoniker()); // Make sure we load the Mondrian driver into the ClassLoader. try { ClassResolver.INSTANCE.forName(MondrianOlap4jDriver.class.getName(), true); } catch (ClassNotFoundException e) { throw new OlapException("Cannot find mondrian olap4j driver."); } if (props != null && props.containsKey(XmlaHandler.JDBC_LOCALE)) { properties.put(XmlaHandler.JDBC_LOCALE, props.get(XmlaHandler.JDBC_LOCALE)); } return properties; } }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
/** * Load a new configuration from URL configURL * * @param configURL/*from ww w .j a va 2 s. c om*/ */ public void loadConfigURL(String configURL) { Reject.ifBlank(configURL, "configURL"); try { // load the configuration from the url ... Properties props = ConfigurationLoader.loadPreConfiguration(configURL.trim()); ConfigurationLoader.merge(props, getController()); String networkID = (String) props.get(ConfigurationEntry.NETWORK_ID.getConfigKey()); String name = (String) props.get(ConfigurationEntry.SERVER_NAME.getConfigKey()); String host = (String) props.get(ConfigurationEntry.SERVER_HOST.getConfigKey()); String nodeId = (String) props.get(ConfigurationEntry.SERVER_NODEID.getConfigKey()); String tunnelURL = (String) props.get(ConfigurationEntry.SERVER_HTTP_TUNNEL_RPC_URL.getConfigKey()); String webURL = (String) props.get(ConfigurationEntry.SERVER_WEB_URL.getConfigKey()); logInfo("Loaded " + props.size() + " from " + configURL + " network ID: " + networkID); if (StringUtils.isBlank(host)) { throw new IOException("Hostname not found"); } String oldNetworkID = getController().getMySelf().getInfo().networkId; if (StringUtils.isNotBlank(networkID)) { getController().getMySelf().getInfo().networkId = networkID; } else { getController().getMySelf().getInfo().networkId = ConfigurationEntry.NETWORK_ID.getDefaultValue(); } String newNetworkID = getController().getMySelf().getInfo().networkId; boolean networkIDChanged = !Util.equals(oldNetworkID, newNetworkID); if (networkIDChanged) { getController().getNodeManager().shutdown(); } init(getController(), name, host, nodeId, allowServerChange, updateConfig); // Store in config setServerWebURLInConfig(webURL); setServerHTTPTunnelURLInConfig(tunnelURL); setServerInConfig(getServer().getInfo()); ConfigurationEntry.NETWORK_ID.setValue(getController(), newNetworkID); ConfigurationEntry.CONFIG_URL.setValue(getController(), configURL); getController().saveConfig(); if (networkIDChanged) { // Restart nodemanager getController().getNodeManager().start(); } connectHostingServers(); } catch (Exception e) { logWarning("Could not load connection infos from " + configURL + ": " + e.getMessage()); } }
From source file:org.ohmage.jee.listener.ConfigurationFileImport.java
/** * Find the log file, if it exists, and add its properties to the system * properties./*from w ww. j a v a2 s. co m*/ */ @Override public void contextInitialized(ServletContextEvent event) { // An empty Properties object that will be populated with the default // configuration. Properties defaultProperties = new Properties(); File defaultConfiguration = new File(event.getServletContext().getRealPath("/") + CONFIG_FILE_DEFAULT); try { defaultProperties.load(new FileReader(defaultConfiguration)); } // The default properties file didn't exist, which is alarming. catch (FileNotFoundException e) { LOGGER.log(Level.WARNING, "The default properties file is missing: " + defaultConfiguration.getAbsolutePath(), e); } // There was an error reading the default properties file. catch (IOException e) { LOGGER.log(Level.WARNING, "There was an error reading the default properties " + "file: " + defaultConfiguration.getAbsolutePath(), e); } // Get a handler for the properties file based on the operating system. File propertiesFile; if (System.getProperty("os.name").contains("Windows")) { propertiesFile = new File(CONFIG_FILE_DEFAULT_WINDOWS); } else { propertiesFile = new File(CONFIG_FILE_DEFAULT_POSIX); } // Attempts to retrieve the custom configuration file and store it. Properties customProperties = new Properties(); try { customProperties.load(new FileReader(propertiesFile)); LOGGER.log(Level.INFO, "The properties file was imported: " + propertiesFile.getAbsolutePath()); } // The properties file didn't exist, which is fine. catch (FileNotFoundException e) { LOGGER.log(Level.INFO, "The properties file does not exist: " + propertiesFile.getAbsolutePath()); } // There was a problem reading the properties. catch (IOException e) { LOGGER.log(Level.WARNING, "There was an error reading the properties file: " + propertiesFile.getAbsolutePath(), e); } // Set the properties files. PROPERTIES_ARRAY[0] = defaultProperties; PROPERTIES_ARRAY[1] = customProperties; // Create a merged properties and save it. for (Object key : defaultProperties.keySet()) { PROPERTIES.put(key, defaultProperties.get(key)); } for (Object key : customProperties.keySet()) { PROPERTIES.put(key, customProperties.get(key)); } }
From source file:com.athena.peacock.agent.netty.PeacockClientHandler.java
@Override public void run() { try {// w w w .j av a2 s . c o m StringStreamConsumer consumer = null; Commandline commandLine = null; int returnCode = 0; Properties properties = null; SoftwareInfoMessage msg = new SoftwareInfoMessage(MessageType.SOFTWARE_INFO); msg.setAgentId(IOUtils .toString(new File(PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY)).toURI())); SoftwareInfo softwareInfo = null; // ======================= // 1. JBOSS EWS(HTTPD) // ======================= try { commandLine = new Commandline(); commandLine.setExecutable("sh"); commandLine.createArg().setLine("chkhttpd.sh"); logger.debug("Start Software(httpd) info gathering..."); logger.debug("~]$ {}\n", commandLine.toString()); consumer = new CommandLineUtils.StringStreamConsumer(); returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { properties = new Properties(); properties.load(new StringReader(consumer.getOutput())); int count = Integer.parseInt((String) properties.get("COUNT")); String apacheHome = (String) properties.get("APACHE_HOME"); String serverHome = (String) properties.get("SERVER_HOME"); String startCmd = (String) properties.get("START_CMD"); String stopCmd = (String) properties.get("STOP_CMD"); for (int i = 1; i <= count; i++) { softwareInfo = new SoftwareInfo(); softwareInfo.setName("httpd"); if (apacheHome != null && apacheHome.split(",")[i].indexOf("2.1") >= 0) { softwareInfo.setVersion("2.2.26"); } else { softwareInfo.setVersion("2.2.22"); } softwareInfo.getInstallLocations().add(apacheHome.split(",")[i]); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/bin"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/conf"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/log"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/run"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/www"); softwareInfo.setStartWorkingDir(""); softwareInfo.setStartCommand( startCmd.split(",")[i].substring(0, startCmd.split(",")[i].indexOf(" "))); softwareInfo.setStartArgs( startCmd.split(",")[i].substring(startCmd.split(",")[i].indexOf(" ") + 1)); softwareInfo.setStopWorkingDir(""); softwareInfo.setStopCommand( stopCmd.split(",")[i].substring(0, stopCmd.split(",")[i].indexOf(" "))); softwareInfo.setStopArgs( stopCmd.split(",")[i].substring(stopCmd.split(",")[i].indexOf(" ") + 1)); String configFile = null; ConfigInfo configInfo = null; String[] configKeys = new String[] { "HTTPD_CONF", "HTTPD_INFO_CONF", "SSL_CONF", "URIWORKERMAP", "WORKERS" }; for (String configKey : configKeys) { if ((configFile = (String) properties.get(configKey)) != null) { // ,,,,, ? split size 0 ? ? ? . configFile = configFile + " "; if (configFile.split(",").length > 0 && configFile.split(",")[i].indexOf("/") >= 0) { commandLine = new Commandline(); commandLine.setExecutable("cat"); commandLine.createArg().setLine(configFile.split(",")[i]); consumer = new CommandLineUtils.StringStreamConsumer(); returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { configInfo = new ConfigInfo(); configInfo.setConfigFileLocation(configFile.split(",")[i].substring(0, configFile.split(",")[i].lastIndexOf("/"))); configInfo.setConfigFileName(configFile.split(",")[i] .substring(configFile.split(",")[i].lastIndexOf("/") + 1, configFile.split(",")[i].length()) .trim()); configInfo.setConfigFileContents(consumer.getOutput().substring(0, consumer.getOutput().length() - 1)); softwareInfo.getConfigInfoList().add(configInfo); } } } } msg.getSoftwareInfoList().add(softwareInfo); } logger.debug("End Software(httpd) info gathering..."); } } catch (Exception e1) { // ignore after logging logger.error("Unhandled Exception has occurred. ", e1); } // ======================= // 2. JBOSS EWS(TOMCAT) // ======================= try { commandLine = new Commandline(); commandLine.setExecutable("sh"); commandLine.createArg().setLine("chkews.sh"); logger.debug("Start Software(tomcat) info gathering..."); logger.debug("~]$ {}\n", commandLine.toString()); consumer = new CommandLineUtils.StringStreamConsumer(); returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { properties = new Properties(); properties.load(new StringReader(consumer.getOutput())); int count = Integer.parseInt((String) properties.get("COUNT")); String version = (String) properties.get("VERSION"); String catalinaHome = (String) properties.get("CATALINA_HOME"); String serverHome = (String) properties.get("SERVER_HOME"); String startCmd = (String) properties.get("START_CMD"); String stopCmd = (String) properties.get("STOP_CMD"); for (int i = 1; i <= count; i++) { softwareInfo = new SoftwareInfo(); softwareInfo.setName("tomcat"); if (version != null && version.split(",")[i].indexOf("7") >= 0) { softwareInfo.setVersion("7.0.54"); } else { softwareInfo.setVersion("6.0.41"); } softwareInfo.getInstallLocations().add(catalinaHome.split(",")[i].substring(0, catalinaHome.split(",")[i].lastIndexOf("/"))); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/apps"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/bin"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/Servers"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/svrlogs"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/wily"); softwareInfo.setStartWorkingDir(""); softwareInfo.setStartCommand( startCmd.split(",")[i].substring(0, startCmd.split(",")[i].indexOf(" "))); softwareInfo.setStartArgs( startCmd.split(",")[i].substring(startCmd.split(",")[i].indexOf(" ") + 1)); softwareInfo.setStopWorkingDir(""); softwareInfo.setStopCommand( stopCmd.split(",")[i].substring(0, stopCmd.split(",")[i].indexOf(" "))); softwareInfo.setStopArgs( stopCmd.split(",")[i].substring(stopCmd.split(",")[i].indexOf(" ") + 1)); String configFile = null; ConfigInfo configInfo = null; String[] configKeys = new String[] { "ENV_SH", "SERVER_XML", "CONTEXT_XML" }; for (String configKey : configKeys) { if ((configFile = (String) properties.get(configKey)) != null) { // ,,,,, ? split size 0 ? ? ? . configFile = configFile + " "; if (configFile.split(",").length > 0 && configFile.split(",")[i].indexOf("/") >= 0) { commandLine = new Commandline(); commandLine.setExecutable("cat"); commandLine.createArg().setLine(configFile.split(",")[i]); consumer = new CommandLineUtils.StringStreamConsumer(); returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { configInfo = new ConfigInfo(); configInfo.setConfigFileLocation(configFile.split(",")[i].substring(0, configFile.split(",")[i].lastIndexOf("/"))); configInfo.setConfigFileName(configFile.split(",")[i] .substring(configFile.split(",")[i].lastIndexOf("/") + 1, configFile.split(",")[i].length()) .trim()); configInfo.setConfigFileContents(consumer.getOutput().substring(0, consumer.getOutput().length() - 1)); softwareInfo.getConfigInfoList().add(configInfo); } } } } msg.getSoftwareInfoList().add(softwareInfo); } logger.debug("End Software(tomcat) info gathering..."); } } catch (Exception e1) { // ignore after logging logger.error("Unhandled Exception has occurred. ", e1); } // ======================= // 3. JBOSS EAP // ======================= try { commandLine = new Commandline(); commandLine.setExecutable("sh"); commandLine.createArg().setLine("chkeap.sh"); logger.debug("Start Software(eap) info gathering..."); logger.debug("~]$ {}\n", commandLine.toString()); consumer = new CommandLineUtils.StringStreamConsumer(); returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { properties = new Properties(); properties.load(new StringReader(consumer.getOutput())); int count = Integer.parseInt((String) properties.get("COUNT")); String version = (String) properties.get("VERSION"); String jbossHome = (String) properties.get("JBOSS_HOME"); String serverHome = (String) properties.get("SERVER_HOME"); String startCmd = (String) properties.get("START_CMD"); String stopCmd = (String) properties.get("STOP_CMD"); for (int i = 1; i <= count; i++) { softwareInfo = new SoftwareInfo(); softwareInfo.setName("eap"); if (version != null && version.split(",")[i].indexOf("5.2") >= 0) { softwareInfo.setVersion("5.2.0"); } else { softwareInfo.setVersion("5.1.2"); } softwareInfo.getInstallLocations().add(jbossHome.split(",")[i]); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/apps"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/Servers"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/svrlogs"); softwareInfo.getInstallLocations().add(serverHome.split(",")[i] + "/wily"); softwareInfo.setStartWorkingDir(""); softwareInfo.setStartCommand( startCmd.split(",")[i].substring(0, startCmd.split(",")[i].indexOf(" "))); softwareInfo.setStartArgs( startCmd.split(",")[i].substring(startCmd.split(",")[i].indexOf(" ") + 1)); softwareInfo.setStopWorkingDir(""); softwareInfo.setStopCommand( stopCmd.split(",")[i].substring(0, stopCmd.split(",")[i].indexOf(" "))); softwareInfo.setStopArgs( stopCmd.split(",")[i].substring(stopCmd.split(",")[i].indexOf(" ") + 1)); String configFile = null; ConfigInfo configInfo = null; String[] configKeys = new String[] { "ENV_SH", "DS_XML", "LOGIN_CONFIG_XML" }; for (String configKey : configKeys) { if ((configFile = (String) properties.get(configKey)) != null) { // ,,,,, ? split size 0 ? ? ? . configFile = configFile + " "; if (configFile.split(",").length > 0 && configFile.split(",")[i].indexOf("/") >= 0) { commandLine = new Commandline(); commandLine.setExecutable("cat"); commandLine.createArg().setLine(configFile.split(",")[i]); consumer = new CommandLineUtils.StringStreamConsumer(); returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { configInfo = new ConfigInfo(); configInfo.setConfigFileLocation(configFile.split(",")[i].substring(0, configFile.split(",")[i].lastIndexOf("/"))); configInfo.setConfigFileName(configFile.split(",")[i] .substring(configFile.split(",")[i].lastIndexOf("/") + 1, configFile.split(",")[i].length()) .trim()); configInfo.setConfigFileContents(consumer.getOutput().substring(0, consumer.getOutput().length() - 1)); softwareInfo.getConfigInfoList().add(configInfo); } } } } msg.getSoftwareInfoList().add(softwareInfo); } logger.debug("End Software(eap) info gathering..."); } } catch (Exception e1) { // ignore after logging logger.error("Unhandled Exception has occurred. ", e1); } if (msg.getSoftwareInfoList().size() > 0) { ctx.writeAndFlush(new PeacockDatagram<SoftwareInfoMessage>(msg)); } } catch (Exception e) { logger.error("Unhandled Exception has occurred. ", e); } }
From source file:edu.ku.brc.af.ui.forms.ViewFactory.java
/** * Creates an ImageDisplay control,/*from w w w .ja va 2s. c o m*/ * @param cellField FormCellField info * @param isViewMode indicates whether in Edit or View mode * @param isRequired whether the field is required or not * @return the control */ protected static UIPluginable createPlugin(final MultiView parent, final FormValidator validator, final FormCellField cellField, final boolean isViewMode, final boolean isRequired) { String pluginName = cellField.getProperty("name"); if (StringUtils.isEmpty(pluginName)) { String msg = "Creating plugin and the name property was missing. [" + cellField.getName() + "]"; log.error(msg); FormDevHelper.appendFormDevError(msg); return null; } // We should refactor the plugin manager. Class<?> pluginClass = TaskMgr.getUIPluginClassForName(pluginName); if (pluginClass != null && UIPluginable.class.isAssignableFrom(pluginClass)) { try { // instantiate the plugin object UIPluginable uiPlugin = pluginClass.asSubclass(UIPluginable.class).newInstance(); uiPlugin.setCellName(cellField.getName()); Properties props = (Properties) cellField.getProperties().clone(); //log.debug(cellField.getName()); if (uiPlugin instanceof WebLinkButton) { //if (StringUtils.isNotEmpty((String)props.get("weblink"))) { DBTableInfo tInfo = DBTableIdMgr.getInstance() .getByClassName(parent.getView().getClassName()); if (tInfo != null) { //log.debug(cellField.getName()); DBFieldInfo fInfo = tInfo.getFieldByName(cellField.getName()); if (fInfo != null) { //log.debug(fInfo.getFormatStr() + " weblink: "+fInfo.getWebLinkName()); if (StringUtils.isEmpty((String) props.get("weblink")) && StringUtils.isNotEmpty(fInfo.getWebLinkName())) { props.put("weblink", fInfo.getWebLinkName()); } } } } } // This needs to be done before the initialize. if (uiPlugin instanceof UIValidatable) { ((UIValidatable) uiPlugin).setRequired(isRequired); } // initialize the plugin object uiPlugin.initialize(props, isViewMode); // get the UI component provided by the plugin object JComponent pluginUI = uiPlugin.getUIComponent(); // check for another required interface (GetSetValueIFace) if (!(uiPlugin instanceof GetSetValueIFace)) { FormDevHelper.appendFormDevError("Plugin of class [" + pluginClass.getName() + "] doesn't implement the GetSetValueIFace!"); return null; } if (validator != null) { DataChangeNotifier dcn = validator.hookupComponent(pluginUI, cellField.getIdent(), parseValidationType(cellField.getValidationType()), cellField.getValidationRule(), false); uiPlugin.addChangeListener(dcn); } return uiPlugin; } catch (Exception ex) { log.error(ex); ex.printStackTrace(); FormDevHelper.appendFormDevError(ex); } } log.error("Couldn't find plugin by name[" + pluginName + "]"); return null; }