List of usage examples for java.util Hashtable size
public synchronized int size()
From source file:org.hdiv.filter.AbstractValidatorHelper.java
/** * Check if all required parameters are received in <code>request</code>. * /*from w w w . j ava2 s .co m*/ * @param request HttpServletRequest to validate * @param state IState The restored state for this url * @param target Part of the url that represents the target action * @return True if all required parameters are received. False in otherwise. */ private boolean allRequiredParametersReceived(HttpServletRequest request, IState state, String target) { Hashtable receivedParameters = new Hashtable(state.getRequiredParams()); String currentParameter = null; Enumeration requestParameters = request.getParameterNames(); while (requestParameters.hasMoreElements()) { currentParameter = (String) requestParameters.nextElement(); if (receivedParameters.containsKey(currentParameter)) { receivedParameters.remove(currentParameter); } // If multiple parameters are received, it is possible to pass this // verification without checking all the request parameters. if (receivedParameters.size() == 0) { return true; } } if (receivedParameters.size() > 0) { this.logger.log(HDIVErrorCodes.REQUIRED_PARAMETERS, target, receivedParameters.keySet().toString(), null); return false; } return true; }
From source file:org.hdiv.filter.ValidatorHelperRequest.java
/** * Check if all required parameters are received in <code>request</code>. * /*from ww w .java2 s . c o m*/ * @param request * HttpServletRequest to validate * @param state * IState The restored state for this url * @param target * Part of the url that represents the target action * @return valid result if all required parameters are received. False in otherwise. */ private ValidatorHelperResult allRequiredParametersReceived(HttpServletRequest request, IState state, String target) { Hashtable receivedParameters = new Hashtable(state.getRequiredParams()); String currentParameter = null; Enumeration requestParameters = request.getParameterNames(); while (requestParameters.hasMoreElements()) { currentParameter = (String) requestParameters.nextElement(); if (receivedParameters.containsKey(currentParameter)) { receivedParameters.remove(currentParameter); } // If multiple parameters are received, it is possible to pass this // verification without checking all the request parameters. if (receivedParameters.size() == 0) { return ValidatorHelperResult.VALID; } } if (receivedParameters.size() > 0) { this.logger.log(HDIVErrorCodes.REQUIRED_PARAMETERS, target, receivedParameters.keySet().toString(), null); return new ValidatorHelperResult(HDIVErrorCodes.REQUIRED_PARAMETERS); } return ValidatorHelperResult.VALID; }
From source file:oscar.eform.actions.HtmlEditAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*from ww w. j a v a 2 s . com*/ HtmlEditForm fm = (HtmlEditForm) form; try { String fid = fm.getFid(); String formName = fm.getFormName(); String formSubject = fm.getFormSubject(); String formFileName = fm.getFormFileName(); String formHtml = fm.getFormHtml(); FormFile uploadFile = fm.getUploadFile(); boolean showLatestFormOnly = WebUtils.isChecked(request, "showLatestFormOnly"); boolean patientIndependent = WebUtils.isChecked(request, "patientIndependent"); String roleType = fm.getRoleType(); Hashtable errors = new Hashtable(); if (request.getParameter("uploadMarker").equals("true")) { //if uploading file String readstream = StringUtils.readFileStream(uploadFile); if (readstream.length() == 0) { errors.put("uploadError", "eform.errors.upload.failed"); } else { formHtml = org.apache.commons.lang.StringEscapeUtils.escapeJava(readstream); formFileName = uploadFile.getFileName(); } HashMap<String, Object> curht = createHashMap(fid, formName, formSubject, formFileName, formHtml, showLatestFormOnly, patientIndependent, roleType); request.setAttribute("submitted", curht); request.setAttribute("errors", errors); return (mapping.findForward("success")); } EFormBase updatedform = new EFormBase(fid, formName, formSubject, formFileName, formHtml, showLatestFormOnly, patientIndependent, roleType); //property container (bean) //validation... if ((formName == null) || (formName.length() == 0)) { errors.put("formNameMissing", "eform.errors.form_name.missing.regular"); } if ((fid.length() > 0) && (EFormUtil.formExistsInDBn(formName, fid) > 0)) { errors.put("formNameExists", "eform.errors.form_name.exists.regular"); } if ((fid.length() == 0) && (errors.size() == 0)) { fid = EFormUtil.saveEForm(formName, formSubject, formFileName, formHtml, showLatestFormOnly, patientIndependent, roleType); request.setAttribute("success", "true"); } else if (errors.size() == 0) { EFormUtil.updateEForm(updatedform); request.setAttribute("success", "true"); } HashMap<String, Object> curht = createHashMap(fid, formName, formSubject, formFileName, org.apache.commons.lang.StringEscapeUtils.escapeJava(formHtml), showLatestFormOnly, patientIndependent, roleType); request.setAttribute("submitted", curht); request.setAttribute("errors", errors); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } return (mapping.findForward("success")); }
From source file:com.jada.content.template.TemplateEngine.java
public Hashtable<String, String> updateContentComment() throws Exception { Customer customer = ContentLookupDispatchAction.getCustomer(request); if (customer == null) { return null; }//from w w w . j a v a2s . c o m String contentNaturalKey = Utility.reEncode(getCategoryParameter(request, 2)); String commentTitle = request.getParameter("commentTitle"); commentTitle = Utility.escapeStrictHTML(commentTitle); String commentLine = request.getParameter("comment"); commentLine = Utility.escapeStrictHTML(commentLine); Hashtable<String, String> attributes = new Hashtable<String, String>(); if (Format.isNullOrEmpty(commentTitle)) { attributes.put("commentTitleMessage", getLanguage("content.error.string.required")); } if (Format.isNullOrEmpty(commentLine)) { attributes.put("commentMessage", getLanguage("content.error.string.required")); } if (attributes.size() == 0) { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); Content content = (Content) ContentDAO.loadNatural(siteDomain.getSite().getSiteId(), contentNaturalKey); Comment comment = new Comment(); comment.setCommentTitle(commentTitle); comment.setComment(commentLine); comment.setCommentRating(0); comment.setActive(Constants.VALUE_YES); String custName = customer.getCustEmail(); if (custName.length() > 20) { custName = custName.substring(0, 19); } comment.setRecCreateBy(custName); comment.setRecCreateDatetime(new Date(System.currentTimeMillis())); comment.setRecUpdateBy(custName); comment.setRecUpdateDatetime(new Date(System.currentTimeMillis())); comment.setCustomer(customer); comment.setContent(content); content.getComments().add(comment); em.persist(comment); attributes.put("commentTitle", ""); attributes.put("comment", ""); } else { attributes.put("commentTitle", commentTitle); attributes.put("comment", commentLine); } return attributes; }
From source file:org.fcrepo.server.access.FedoraAccessServlet.java
/** * <p>/* ww w . jav a 2s. c o m*/ * Process Fedora Access Request. Parse and validate the servlet input * parameters and then execute the specified request. * </p> * * @param request * The servlet request. * @param response * servlet The servlet response. * @throws ServletException * If an error occurs that effects the servlet's basic operation. * @throws IOException * If an error occurrs with an input or output operation. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String PID = null; String sDefPID = null; String methodName = null; String dsID = null; Date asOfDateTime = null; Date versDateTime = null; Property[] userParms = null; boolean isGetObjectProfileRequest = false; boolean isGetDisseminationRequest = false; boolean isGetDatastreamDisseminationRequest = false; boolean xml = false; requestURI = request.getQueryString() != null ? request.getRequestURL().toString() + "?" + request.getQueryString() : request.getRequestURL().toString(); logger.info("Got request: {}", requestURI); // Parse servlet URL. // For the Fedora API-A-LITE "get" syntax, valid entries include: // // For dissemination requests: // http://host:port/fedora/get/pid/sDefPid/methodName // http://host:port/fedora/get/pid/sDefPid/methodName/timestamp // http://host:port/fedora/get/pid/sDefPid/methodName?parm=value[&parm=value] // http://host:port/fedora/get/pid/sDefPid/methodName/timestamp?parm=value[&parm=value] // // For object profile requests: // http://host:port/fedora/get/pid // http://host:port/fedora/get/pid/timestamp // // For datastream dissemination requests: // http://host:port/fedora/get/pid/dsID // http://host:port/fedora/get/pid/dsID/timestamp // // use substring to avoid an additional char array copy String[] URIArray = requestURI.substring(0, request.getRequestURL().length()).split("/"); if (URIArray.length == 6 || URIArray.length == 7) { // Request is either an ObjectProfile request or a datastream // request if (URIArray.length == 7) { // They either specified a date/time or a datastream id. if (URIArray[6].indexOf(":") == -1) { // If it doesn't contain a colon, they were after a // datastream, // so this is a DatastreamDissemination request dsID = URLDecoder.decode(URIArray[6], "UTF-8"); isGetDatastreamDisseminationRequest = true; } else { // If it DOES contain a colon, they were after a // date/time-stamped object profile try { versDateTime = DateUtility.parseDateStrict(URIArray[6]); } catch (ParseException e) { String message = "ObjectProfile Request Syntax Error: DateTime value " + "of \"" + URIArray[6] + "\" is not a valid DateTime format. " + " <br></br> The expected format for DateTime is \"" + "YYYY-MM-DDTHH:MM:SS.SSSZ\". " + " <br></br> The expected syntax for " + "ObjectProfile requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID[/dateTime] \" ." + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); /* * commented out for exception.jsp test * response.setStatus * (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); * response * .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR * , message); return; commented out for exception.jsp * test */ } asOfDateTime = versDateTime; isGetObjectProfileRequest = true; } } else { // URIArray.length==6 so this is a GetObjectProfile request isGetObjectProfileRequest = true; } } else if (URIArray.length > 7) { // Request is either dissemination request or timestamped get // datastream request methodName = URLDecoder.decode(URIArray[7], "UTF-8"); if (URIArray.length == 8) { if (URIArray[6].indexOf(":") == -1) { // If it doesn't contain a colon, they were after a // timestamped // datastream, so this is a GetDatastreamDissemination // request. dsID = URLDecoder.decode(URIArray[6], "UTF-8"); try { versDateTime = DateUtility.parseDateStrict(URIArray[7]); } catch (ParseException e) { String message = "GetDatastreamDissemination Request Syntax Error: DateTime value " + "of \"" + URIArray[7] + "\" is not a valid DateTime format. " + " <br></br> The expected format for DateTime is \"" + "YYYY-MM-DDTHH:MM:SS.SSSZ\". " + " <br></br> The expected syntax for GetDatastreamDissemination requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID/dsID[/dateTime] \" " + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); } asOfDateTime = versDateTime; isGetDatastreamDisseminationRequest = true; } else { isGetDisseminationRequest = true; } } else if (URIArray.length == 9) { try { versDateTime = DateUtility.parseDateStrict(URIArray[8]); } catch (ParseException e) { String message = "Dissemination Request Syntax Error: DateTime value " + "of \"" + URIArray[8] + "\" is not a valid DateTime format. " + " <br></br> The expected format for DateTime is \"" + "YYYY-MM-DDTHH:MM:SS.SSS\". " + " <br></br> The expected syntax for Dissemination requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID/sDefPID/methodName[/dateTime][?ParmArray] \" " + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); /* * commented out for exception.jsp test * response.setStatus(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR); * response.sendError(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR, message); return; commented * out for exception.jsp test */ } asOfDateTime = versDateTime; isGetDisseminationRequest = true; } if (URIArray.length > 9) { String message = "Dissemination Request Syntax Error: The expected " + "syntax for Dissemination requests is: \"" + URIArray[0] + "//" + URIArray[2] + "/" + URIArray[3] + "/" + URIArray[4] + "/PID/sDefPID/methodName[/dateTime][?ParmArray] \" " + " <br></br> Submitted request was: \"" + requestURI + "\" . "; logger.warn(message); throw new ServletException("from FedoraAccessServlet" + message); /* * commented out for exception.jsp test * response.setStatus(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR); * response.sendError(HttpServletResponse * .SC_INTERNAL_SERVER_ERROR, message); return; commented out * for exception.jsp test */ } } else { // Bad syntax; redirect to syntax documentation page. response.sendRedirect("/userdocs/client/browser/apialite/index.html"); return; } // Separate out servlet parameters from method parameters Hashtable<String, String> h_userParms = new Hashtable<String, String>(); for (Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) { String name = URLDecoder.decode((String) e.nextElement(), "UTF-8"); if (isGetObjectProfileRequest && name.equalsIgnoreCase("xml")) { xml = Boolean.parseBoolean(request.getParameter(name)); } else { String value = URLDecoder.decode(request.getParameter(name), "UTF-8"); h_userParms.put(name, value); } } // API-A interface requires user-supplied parameters to be of type // Property[] so create Property[] from hashtable of user parameters. int userParmCounter = 0; userParms = new Property[h_userParms.size()]; for (Enumeration<String> e = h_userParms.keys(); e.hasMoreElements();) { Property userParm = new Property(); userParm.name = e.nextElement(); userParm.value = h_userParms.get(userParm.name); userParms[userParmCounter] = userParm; userParmCounter++; } PID = URIArray[5]; String actionLabel = "Access"; try { if (isGetObjectProfileRequest) { logger.debug("Servicing getObjectProfile request (PID={}, asOfDate={})", PID, versDateTime); Context context = ReadOnlyContext.getContext(HTTP_REQUEST.REST.uri, request); getObjectProfile(context, PID, asOfDateTime, xml, request, response); logger.debug("Finished servicing getObjectProfile request"); } else if (isGetDisseminationRequest) { sDefPID = URIArray[6]; logger.debug("Servicing getDissemination request (PID={}, sDefPID={}, methodName={}, asOfDate={})", PID, sDefPID, methodName, versDateTime); Context context = ReadOnlyContext.getContext(HTTP_REQUEST.REST.uri, request); getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime, response, request); logger.debug("Finished servicing getDissemination request"); } else if (isGetDatastreamDisseminationRequest) { logger.debug("Servicing getDatastreamDissemination request " + "(PID={}, dsID={}, asOfDate={})", PID, dsID, versDateTime); Context context = ReadOnlyContext.getContext(HTTP_REQUEST.REST.uri, request); getDatastreamDissemination(context, PID, dsID, asOfDateTime, response, request); logger.debug("Finished servicing getDatastreamDissemination " + "request"); } } catch (MethodNotFoundException e) { logger.error("Method not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (DatastreamNotFoundException e) { logger.error("Datastream not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (ObjectNotFoundException e) { logger.error("Object not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (DisseminationException e) { logger.error("Dissemination failed: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (ObjectNotInLowlevelStorageException e) { logger.error("Object or datastream not found for request: " + requestURI + " (actionLabel=" + actionLabel + ")", e); throw new NotFound404Exception("", e, request, actionLabel, e.getMessage(), EMPTY_STRING_ARRAY); } catch (AuthzException ae) { logger.error("Authorization failed for request: " + requestURI + " (actionLabel=" + actionLabel + ")", ae); throw RootException.getServletException(ae, request, actionLabel, EMPTY_STRING_ARRAY); } catch (Throwable th) { logger.error("Unexpected error servicing API-A request", th); throw new InternalError500Exception("", th, request, actionLabel, "", EMPTY_STRING_ARRAY); } }
From source file:com.clustercontrol.ping.factory.RunMonitorPing.java
/** * ping???//from ww w .ja v a 2 s .c o m * <p> * <ol> * <li>fping?????RunMonitor?runMonitorInfooverride???</li> * <li>????????{@link #setMonitorInfo(String, String)}</li> * <li>?????????{@link #setJudgementInfo()}</li> * <li>??????????{@link #setCheckInfo()}</li> * <li>??????? {@link #collect(String)}</li> * <li>???????? {@link #getCheckResult(boolean)}</li> * <li>?????????{@link #getPriority(int)}</li> * <li>????{@link #notify(boolean, String, int, Date)}</li> * </ol> * * @return ??????</code> true </code> * @throws MonitorNotFound * @throws HinemosUnknown * * @see #setMonitorInfo(String, String) * @see #setJudgementInfo() * @see #setCheckInfo() * @see #collect(String) * @see #getCheckResult(boolean) * @see #getPriority(int) * @see #notify(boolean, String, int, Date) */ @Override protected boolean runMonitorInfo() throws MonitorNotFound, HinemosUnknown { m_now = HinemosTime.getDateInstance(); m_priorityMap = new HashMap<Integer, ArrayList<String>>(); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_INFO), new ArrayList<String>()); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_WARNING), new ArrayList<String>()); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_CRITICAL), new ArrayList<String>()); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_UNKNOWN), new ArrayList<String>()); List<Sample> sampleList = new ArrayList<Sample>(); // boolean run = this.setMonitorInfo(m_monitorTypeId, m_monitorId); if (!run) { // ? return true; } // setJudgementInfo(); // ?? setCheckInfo(); // ID????? ArrayList<String> facilityList = new RepositoryControllerBean().getExecTargetFacilityIdList(m_facilityId, m_monitor.getOwnerRoleId()); if (facilityList.size() == 0) return true; // ?? ArrayList<Integer> priorityList = new ArrayList<Integer>(); // ??? Sample sample = null; if (m_monitor.getCollectorFlg()) { sample = new Sample(HinemosTime.getDateInstance(), m_monitor.getMonitorId()); } //fping?false??ver2.2?????ping? if (!PingProperties.isFpingEnable()) { String facilityId = null; for (int index = 0; index < facilityList.size(); index++) { facilityId = facilityList.get(index); if (facilityId != null && !"".equals(facilityId)) { // ? boolean ret = collect(facilityId); // ?? int checkResult = getCheckResult(ret); // ?? if (m_nodeDate > m_scopeDate) { m_scopeDate = m_nodeDate; } // ?? // ?? if (!m_isMonitorJob) { notify(true, facilityId, checkResult, new Date(m_nodeDate)); } else { m_monitorRunResultInfo = new MonitorRunResultInfo(); MonitorJudgementInfo info = m_judgementInfoList.get(checkResult); if (info != null) { m_monitorRunResultInfo.setPriority(info.getPriority()); } else { m_monitorRunResultInfo.setPriority(m_failurePriority); } m_monitorRunResultInfo.setMessageOrg(makeJobOrgMessage(m_messageOrg, m_message)); m_monitorRunResultInfo.setNodeDate(m_nodeDate); } // ?? if (sample != null) { int errorCode = -1; if (ret) { errorCode = CollectedDataErrorTypeConstant.NOT_ERROR; } else { errorCode = CollectedDataErrorTypeConstant.UNKNOWN; } sample.set(facilityId, m_monitor.getItemName(), m_value, errorCode); } } } } //fping?true????ping? else { // ? // fping?????????ping??? boolean ret = collectFping(facilityList, priorityList); if (ret) { Hashtable<String, PingResult> fpingResultSet = new Hashtable<String, PingResult>(); Hashtable<String, PingResult> fpingResultSetV6 = new Hashtable<String, PingResult>(); //???? if (m_MsgErr != null) { fpingResultSet = wrapUpFping(m_MsgErr, m_runCount, 4); } if (m_MsgErrV6 != null) { m_log.debug("runMonitorInfo(): fpingResultSetV6 check"); fpingResultSetV6 = wrapUpFping(m_MsgErrV6, m_runCount, 6); } //IPv4????????IPv6????? m_log.debug("runMonitorInfo(): before fpingResultSet check"); if (fpingResultSet.size() == 0) { m_log.debug("runMonitorInfo(): after fpingResultSet check"); fpingResultSet = fpingResultSetV6; } //IPv4??????IPv6?? else if (fpingResultSetV6.size() != 0) { fpingResultSet.putAll(fpingResultSetV6); } //?????IP? Iterator<String> it = facilityList.iterator(); String targetFacility; PingResult nodeResult; String[] node; while (it.hasNext()) { //??FacilityId? targetFacility = it.next(); //???IP? node = m_Target.get(targetFacility); // ??????(IP?)?? if (node != null) { m_log.debug("runMonitorInfo(): before fpingResultSet.get()"); nodeResult = fpingResultSet.get(node[0]); if (nodeResult == null) { m_log.debug("runMonitorInfo(): after fpingResultSet.get()"); /* fping??????*/ String[] args = { m_monitorId }; String logMsg = ""; if (m_MsgErr != null) { logMsg = m_MsgErr.toString(); } if (m_MsgErrV6 != null) { logMsg += " , " + m_MsgErrV6.toString(); } AplLogger.put(PriorityConstant.TYPE_CRITICAL, HinemosModuleConstant.MONITOR_PING, MessageConstant.MESSAGE_SYS_001_MON_PNG, args, logMsg); m_log.info("Fping no response."); /* fping??????*/ sample.set(targetFacility, m_monitor.getItemName(), Double.NaN, CollectedDataErrorTypeConstant.UNKNOWN); } else { //?????????? m_lost = nodeResult.getLost(); //?????msec(long)????? m_average = (long) nodeResult.getAverage(); m_message = nodeResult.getMesseage(); m_messageOrg = nodeResult.getMesseageOrg(); m_value = m_average; if (m_log.isDebugEnabled()) { m_log.debug("runMonitorInfo() monitorId = " + m_monitorId + ", facilityId = " + targetFacility + ", average = " + nodeResult.getAverage() + ", value = " + m_value); } // ?? int checkResult; // ?????? if (m_lost == -1) { checkResult = getCheckResult(false); } else { checkResult = getCheckResult(true); } boolean collectorResult = true; if (m_lost == -1 || m_lost == 100) { collectorResult = false; } // ?? if (m_nodeDate > m_scopeDate) { m_scopeDate = m_nodeDate; } // ?? // ?? if (!m_isMonitorJob) { notify(true, targetFacility, checkResult, new Date(m_nodeDate)); } else { m_monitorRunResultInfo = new MonitorRunResultInfo(); m_monitorRunResultInfo.setPriority(checkResult); m_monitorRunResultInfo.setMessageOrg(makeJobOrgMessage(m_messageOrg, m_message)); m_monitorRunResultInfo.setNodeDate(m_nodeDate); } // ?? if (sample != null) { int errorCode = -1; if (collectorResult) { errorCode = CollectedDataErrorTypeConstant.NOT_ERROR; } else { errorCode = CollectedDataErrorTypeConstant.UNKNOWN; } sample.set(targetFacility, m_monitor.getItemName(), (double) nodeResult.getAverage(), errorCode); } } } } } } // ????? if (sample != null) { sampleList.add(sample); } if (!sampleList.isEmpty()) { CollectDataUtil.put(sampleList); } return true; }
From source file:adams.ml.Dataset.java
protected String summariseNumeric(String columnname) { Vector<Float> vf = new Vector<>(); Hashtable<Float, Boolean> ind = new Hashtable<>(); int numErrors = 0; int missing = 0; int ignored = 0; for (int i = 0; i < count(); i++) { DataRow dr = get(i);// w w w. jav a 2 s . c o m if (dr.get(columnname) == null) { missing++; continue; } dr = getSafe(i); if (dr == null) { ignored++; continue; } try { Number val = (Number) dr.get(columnname).getData(); vf.add(val.floatValue()); if (ind.get(val.floatValue()) == null) { ind.put(val.floatValue(), true); } } catch (Exception e) { try { Float pi = Float.parseFloat(dr.getAsString(columnname)); vf.add(pi); } catch (Exception e1) { numErrors++; continue; } } } double[] f = new double[vf.size()]; for (int i = 0; i < f.length; i++) { f[i] = vf.get(i); } StringBuffer ret = new StringBuffer(); ret.append("Total OK: " + vf.size() + "\n"); ret.append("Ignored Rows: " + ignored + "\n"); ret.append("Missing: " + missing + "\n"); ret.append("Errors: " + numErrors + "\n"); ret.append("Different: " + ind.size() + "\n"); double min = StatUtils.min(f); double max = StatUtils.max(f); double mean = StatUtils.mean(f); double stdev = Math.sqrt(StatUtils.variance(f)); double median = StatUtils.percentile(f, 50); ret.append("Min,Max: " + min + "," + max + "\n"); ret.append("Mean: " + mean + "\n"); ret.append("Standard Deviation: " + stdev + "\n"); ret.append("Median: " + median + "\n"); return (ret.toString()); }
From source file:ffx.ui.KeywordPanel.java
/** * <p>/* ww w . j a va 2s . c om*/ * loadActive</p> * * @param newSystem a {@link ffx.ui.FFXSystem} object. * @param newKeys a {@link java.util.Hashtable} object. * @param newKeyFile a {@link java.io.File} object. * @return a boolean. */ public boolean loadActive(FFXSystem newSystem, Hashtable<String, Keyword> newKeys, File newKeyFile) { synchronized (this) { // Store changes made to the current system (if any) first. if (currentKeys != null && KeywordComponent.isKeywordModified()) { if (currentSystem != null && currentSystem != newSystem) { storeActive(); } else { saveChanges(); } } // Clear previous values keyClear(); // No keywords to load if (newKeys == null || newKeys.size() == 0) { return false; } currentSystem = newSystem; currentKeyFile = newKeyFile; currentKeys = newKeys; fileOpen = true; /* * Keys to remove are those entries not recognized by the FFX * Keyword Editor These keys are removed from the active System's * keyword Hashtable and appended to the generic "Comments" * KeywordData instance. */ ArrayList<String> keysToRemove = new ArrayList<>(); Keyword comments = currentKeys.get("COMMENTS"); for (Keyword keyword : currentKeys.values()) { String label = keyword.getKeyword(); Vector<String> data = keyword.getEntries(); if (label.equals("COMMENTS")) { continue; } KeywordComponent tk = keywordHashMap.get(label.toUpperCase()); // If the keyword label isn't recognized, preserve the line // as a Comment if (tk == null) { keysToRemove.add(keyword.getKeyword()); if (data.isEmpty()) { comments.append(label); } else if (label.equalsIgnoreCase("MULTIPOLE")) { int count = 5; for (String entry : data) { count++; if (count > 5) { comments.append(label + " " + entry); count = 1; } else { comments.append(entry); } } } else if (label.equalsIgnoreCase("TORTORS")) { int points = 0; int count = 0; for (String entry : data) { count++; if (count > points) { String res[] = entry.split(" +"); int xres = Integer.parseInt(res[5]); int yres = Integer.parseInt(res[5]); points = xres * yres; comments.append(label + " " + entry); count = 0; } else { comments.append(entry); } } } else { for (String entry : data) { comments.append(label + " " + entry); } } continue; } // No data for this keyword (something like "verbose" that // doesn't have modifiers) if (data.isEmpty()) { tk.loadKeywordEntry(label); } // One to many data entries (something "atom" or "bond" that // can be repeated) for (String s : data) { tk.loadKeywordEntry(s); } } // Load up the Comments Vector<String> entries = comments.getEntries(); if (entries != null) { for (String s : entries) { if (s.length() > 1) { if (!groupHashMap.containsKey(s.substring(1).toUpperCase().trim())) { commentStringBuffer.append(s).append("\n"); } } else { commentStringBuffer.append(s).append("\n"); } } } // Keywords that aren't recognized have been turned into Comments for (String k : keysToRemove) { currentKeys.remove(k); } if (currentSystem != null) { currentSystem.setKeywords(currentKeys); currentSystem.setKeyFile(currentKeyFile); } loadKeywordGroup(); return true; } }
From source file:com.jada.content.template.TemplateEngine.java
public Hashtable<String, String> updateItemComment() throws Exception { Customer customer = ContentLookupDispatchAction.getCustomer(request); if (customer == null) { return null; }//from ww w . j a va2 s . c o m String itemNaturalKey = Utility.reEncode(getCategoryParameter(request, 2)); String commentTitle = request.getParameter("commentTitle"); commentTitle = Utility.escapeStrictHTML(commentTitle); String commentLine = request.getParameter("comment"); commentLine = Utility.escapeStrictHTML(commentLine); String commentRating = request.getParameter("commentRating"); Hashtable<String, String> attributes = new Hashtable<String, String>(); if (Format.isNullOrEmpty(commentTitle)) { attributes.put("commentTitleMessage", getLanguage("content.error.string.required")); } if (Format.isNullOrEmpty(commentLine)) { attributes.put("commentMessage", getLanguage("content.error.string.required")); } if (Format.isNullOrEmpty(commentRating) || commentRating.equals("0")) { attributes.put("commentRatingMessage", getLanguage("content.error.string.required")); } if (attributes.size() == 0) { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); Item item = (Item) ItemDAO.loadNatural(siteDomain.getSite().getSiteId(), itemNaturalKey); Comment comment = new Comment(); comment.setCommentTitle(commentTitle); comment.setComment(commentLine); comment.setCommentRating(Integer.valueOf(commentRating)); comment.setActive(Constants.VALUE_YES); String custName = customer.getCustEmail(); if (custName.length() > 20) { custName = custName.substring(0, 19); } comment.setRecCreateBy(custName); comment.setRecCreateDatetime(new Date(System.currentTimeMillis())); comment.setRecUpdateBy(custName); comment.setRecUpdateDatetime(new Date(System.currentTimeMillis())); comment.setCustomer(customer); comment.setItem(item); item.getComments().add(comment); em.persist(comment); attributes.put("commentTitle", ""); attributes.put("comment", ""); attributes.put("commentRating", ""); } else { attributes.put("commentTitle", commentTitle); attributes.put("comment", commentLine); attributes.put("commentRating", commentRating); } return attributes; }
From source file:io.cloudslang.content.database.services.dbconnection.DBConnectionManager.java
/** * create a new pooled datasource if total max pool size for the dbms is still * ok. total max pool size per user <= total max pool size specified for * specific db type./*from ww w . j a va 2s . c om*/ * for example, max pool size per user = 20, total max pool size for oracle * dbms is 100. only 5 datasource can be opened. * * @param aDbType one of the supported db type, for example ORACLE, NETCOOL * @param aDbUrl connection url * @param aUsername username to connect to db * @param aPassword password to connect to db * @param aDsTable is used to check if total max pool size for that dbms exceed * @return a pooled datasource * @throws SQLException */ protected DataSource createDataSource(DBType aDbType, String aDbUrl, String aUsername, String aPassword, Hashtable<String, DataSource> aDsTable) throws SQLException { DataSource retDatasource; String totalMaxPoolSizeName; switch (aDbType) { case ORACLE: totalMaxPoolSizeName = ORACLE_MAX_POOL_SIZE_NAME; break; case MSSQL: totalMaxPoolSizeName = MSSQL_MAX_POOL_SIZE_NAME; break; case MYSQL: totalMaxPoolSizeName = MYSQL_MAX_POOL_SIZE_NAME; break; case SYBASE: totalMaxPoolSizeName = SYBASE_MAX_POOL_SIZE_NAME; break; case DB2: totalMaxPoolSizeName = DB2_MAX_POOL_SIZE_NAME; break; case NETCOOL: totalMaxPoolSizeName = NETCOOL_MAX_POOL_SIZE_NAME; break; default: totalMaxPoolSizeName = CUSTOM_MAX_POOL_SIZE_NAME; break; } int totalMaxPoolSize = this.getPropIntValue(totalMaxPoolSizeName, MAX_TOTAL_POOL_SIZE_DEFAULT_VALUE); int perUserMaxPoolSize = this.getPropIntValue(PooledDataSourceProvider.MAX_POOL_SIZE_NAME, PooledDataSourceProvider.MAX_POOL_SIZE_DEFAULT_VALUE); int numDs = aDsTable.size(); int actualTotal = perUserMaxPoolSize * numDs; if (actualTotal >= totalMaxPoolSize) { throw new TotalMaxPoolSizeExceedException( "Can not create another datasource, the total max pool size exceeded. " + " Expected total max pool size = " + totalMaxPoolSize + " Actual total max pool size = " + actualTotal); } retDatasource = this.createDataSource(aDbType, aDbUrl, aUsername, aPassword); return retDatasource; }