List of usage examples for java.util LinkedList get
public E get(int index)
From source file:uk.ac.diamond.scisoft.analysis.rcp.inspector.InspectionTab.java
@Override protected void populateCombos() { Combo c = combos.get(0);//from w w w. j av a 2s .c o m c.removeAll(); c.add(CONSTANT); String name = dataset == null ? null : dataset.getName(); if (name == null || name.length() == 0) c.add(DATA); else c.add(name); c.setText(CONSTANT); if (paxes != null) { PlotAxisProperty p = paxes.get(0); p.setName(CONSTANT, false); } if (daxes != null && daxes.size() != 1) { super.populateCombos(); return; } int cSize = combos.size() - comboOffset; LinkedList<String> sAxes = getAllAxisNames(); int jmax = daxes.size(); for (int i = 0; i < cSize; i++) { c = combos.get(i + comboOffset); c.removeAll(); PlotAxisProperty p = paxes.get(i + comboOffset); String a; if (i < jmax) { a = daxes.get(i).getSelectedName(); if (!sAxes.contains(a)) { a = sAxes.getLast(); } } else { a = sAxes.getLast(); } p.clear(); int pmax = sAxes.size(); for (int j = 0; j < pmax; j++) { String n = sAxes.get(j); p.put(j, n); c.add(n); } c.setText(a); sAxes.remove(a); p.setName(a, false); p.setInSet(true); } }
From source file:com.cablelabs.sim.PCSim2.java
/** * Parses the XML Document passed into the application. * /* w w w . j av a 2s . co m*/ * @param args - the fully-qualified name of the test * script document. * @return - true if the document parsed successfully, * false otherwise. */ protected boolean parseAndStart() { //String ts = testScriptFiles.getFirst(); File f = new File(activeTestScriptFile); if (f != null) { logger.info(PC2LogCategory.Parser, subCat, "Using input document " + activeTestScriptFile); TSParser tsp = new TSParser(true); try { doc = tsp.parse(activeTestScriptFile); logPackage(); logger.info(PC2LogCategory.Parser, subCat, "Using input document " + activeTestScriptFile + " v." + doc.getVersion()); Stacks.logStackSocketInformation(); ss.setDynamicPlatformSettings(doc.getProperties()); ss.logSettings(); // Now see if we are running a test for an UE and if so // See if we should auto provision the device? ProvisioningData pd = autoProvision(doc.getName()); if (pd != null) { String macAddr = autoGenerate(pd); if (macAddr != null) { // doc.setAutoProv(pd); logger.info(PC2LogCategory.PCSim2, subCat, "Updating the global registrar's that the DUT is rebooting"); ProvListener pl = new ProvListener(pd); if (pl != null) { logger.debug(PC2LogCategory.PCSim2, subCat, "Starting the provisioning listener operation."); autoProvisioned = pl.run(); if (!autoProvisioned) { logger.error(PC2LogCategory.PCSim2, subCat, "Auto provisioning did not occur as expected, test is terminating."); provDB.clearIssuedData(macAddr); return false; } else { Properties dut = SystemSettings.getSettings(SettingConstants.DUT); String pui = dut.getProperty(SettingConstants.PUI); if (pui != null) Stacks.generateAutoRebootEvent(pui); String pui2 = dut.getProperty(SettingConstants.PUI2); if (pui2 != null) Stacks.generateAutoRebootEvent(pui2); logger.info(PC2LogCategory.PCSim2, subCat, "Test execution pausing while resetting the DUT."); Thread.sleep(5000); logger.info(PC2LogCategory.PCSim2, subCat, "Pause complete."); } } } else { logger.info(PC2LogCategory.PCSim2, subCat, "Auto generate didn't return an updated data file for provisioning."); } } else { logger.info(PC2LogCategory.PCSim2, subCat, "Auto provisioning did not return a data file for the device."); } LinkedList<FSM> fsms = doc.getFsms(); // Initialize the settings that can be overwritten from // within the document setExtensions(fsms); if (doc.getInspector()) ss.enableInspector(); for (int i = 0; i < fsms.size(); i++) { FSM fsm = fsms.get(i); PC2Models testModel = null; String modelName = fsm.getModel().getName(); if (modelName.equalsIgnoreCase("session")) { testModel = new Session(fsm); if (testModel != null) testModel.init(); try { fsm.getNetworkElements().certify(); } catch (PC2Exception e) { } } else if (modelName.equalsIgnoreCase(MsgRef.STUN_MSG_TYPE)) { testModel = new Stun(fsm); if (testModel != null) testModel.init(); //if (!fsm.getNetworkElements().certify()) // return false; } else if (modelName.equalsIgnoreCase("registrar")) { Properties dut = SystemSettings.getSettings("DUT"); String pui = dut.getProperty(SettingConstants.PUI); Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM); String destIP = platform.getProperty(SettingConstants.IP); if (pui != null) { testModel = new Registrar(fsm, pui, destIP); if (testModel != null) testModel.init(); try { fsm.getNetworkElements().certify(); } catch (PC2Exception e) { } } else return false; } if (modelName.equalsIgnoreCase("register")) { testModel = new Register(fsm); if (testModel != null) testModel.init(); try { fsm.getNetworkElements().certify(); } catch (PC2Exception e) { } } if (testModel != null) { testModel.start(); activeModels.add(testModel); } } return true; } catch (PC2XMLException pe) { String err = "\n** Parsing error in file \n " + pe.getFileName() + " at line " + pe.getLineNumber(); if (pe.getSystemId() != null) { err += ", uri " + pe.getSystemId(); } if (pe.getPublicId() != null) { err += ", public " + pe.getPublicId(); } err += "\n"; logger.fatal(PC2LogCategory.Parser, subCat, err, pe); } catch (SAXParseException spe) { String err = "\n** Parsing error in file \n " + activeTestScriptFile + " at line " + spe.getLineNumber(); if (spe.getSystemId() != null) { err += ", uri " + spe.getSystemId(); } if (spe.getPublicId() != null) { err += ", public " + spe.getPublicId(); } err += "\n"; logger.fatal(PC2LogCategory.Parser, subCat, err, spe); } catch (Exception e) { e.printStackTrace(); } } return false; }
From source file:uk.ac.diamond.scisoft.analysis.rcp.inspector.InspectionTab.java
protected void repopulateCombos(String oldName, String newName) { if (combos == null) return;/*w w w. ja v a 2 s . co m*/ // cascade through plot axes strings and indices // reduce choice each time HashMap<Integer, String> sAxes = getSelectedComboAxisNames(); if (sAxes.size() == 0) return; int cSize = combos.size() - comboOffset; int dmax = daxes.size(); String a = null; if (oldName != null && newName != null) { // only one dataset axis has changed LinkedList<String> oAxes = paxes.get(comboOffset).getNames(); // old axes if (dmax != oAxes.size()) { logger.error("First axis combo has less choice than rank of dataset"); return; } // find changed dimension LinkedList<String> cAxes = getChosenAxisNames(); // old choices Map<String, Integer> axesMap = new LinkedHashMap<String, Integer>(); Map<String, Integer> oldMap = paxes.get(comboOffset).getValue().getMap(); for (String n : oldMap.keySet()) { axesMap.put(n.equals(oldName) ? newName : n, oldMap.get(n)); } PlotAxisProperty p = null; for (int i = 0; i < cSize; i++) { Combo c = combos.get(i + comboOffset); c.removeAll(); p = paxes.get(i + comboOffset); p.clear(); String curAxis = cAxes.get(i); a = oldName.equals(curAxis) ? newName : curAxis; if (axes.length == 1) { // for 1D plots and 1D dataset table int[] shape = dataset.getShape(); for (String n : axesMap.keySet()) { Integer j = axesMap.get(n); p.put(j, n); if (shape[j] != 1) c.add(n); } } else { for (String n : axesMap.keySet()) { Integer j = axesMap.get(n); p.put(j, n); c.add(n); } } c.setText(a); axesMap.remove(a); p.setName(a, false); p.setInSet(true); } // do not need to notify plot axes listeners if (a != null && p != null) { if (p.isInSet()) { p.setName(a); } } return; } PlotAxisProperty p = paxes.get(comboOffset); Map<String, Integer> axesMap = new LinkedHashMap<String, Integer>(p.getValue().getMap()); a = p.getName(); axesMap.remove(a); for (int i = 1; i < cSize; i++) { Combo c = combos.get(i + comboOffset); p = paxes.get(i + comboOffset); a = p.getName(); c.removeAll(); p.clear(); if (a == null) { break; } if (!axesMap.containsKey(a)) { a = axesMap.keySet().iterator().next(); // attempt to get a valid name } if (axes.length == 1) { // for 1D plots and 1D dataset table int[] shape = dataset.getShape(); for (String n : axesMap.keySet()) { Integer j = axesMap.get(n); p.put(j, n); if (shape[j] != 1) c.add(n); } } else { for (String n : axesMap.keySet()) { Integer j = axesMap.get(n); p.put(j, n); c.add(n); } } c.setText(a); axesMap.remove(a); p.setName(a, false); } if (a != null) { if (p.isInSet()) { p.setName(a); } } }
From source file:org.egov.pims.service.EmployeeServiceImpl.java
public List<EmployeeView> searchEmployeeByGrouping(LinkedList<String> groupingByOrder) throws Exception { List<EmployeeView> employeeList = null; try {//from ww w. j av a2 s . co m String mainStr = "from EmployeeView ev where "; String orderByStr = ""; for (int i = 0; i < groupingByOrder.size(); i++) { if (groupingByOrder.get(i).toString().equals("FundCode")) { if (!orderByStr.equals("")) { orderByStr = orderByStr + ", "; } orderByStr = orderByStr + " ev.assignment.fundId.code"; } else if (groupingByOrder.get(i).toString().equals("FunctionCode")) { if (!orderByStr.equals("")) { orderByStr = orderByStr + ", "; } orderByStr = orderByStr + " ev.assignment.functionId.code"; } else if (groupingByOrder.get(i).toString().equals("DeptCode")) { if (!orderByStr.equals("")) { orderByStr = orderByStr + ", "; } orderByStr = orderByStr + " ev.assignment.deptId.deptCode"; } } if (!orderByStr.equals("")) { orderByStr = " order by " + orderByStr; } mainStr += " ((ev.toDate is null and ev.fromDate <= SYSDATE ) OR (ev.fromDate <= SYSDATE AND ev.toDate > SYSDATE)) and ev.assignment.isPrimary='Y' "; mainStr = mainStr + orderByStr; Query qry = null; qry = getCurrentSession().createQuery(mainStr); LOGGER.info("Query in search Employee by grouping==" + qry.toString()); employeeList = (List) qry.list(); } catch (HibernateException he) { LOGGER.error("Exception ===" + he.getMessage()); throw new ApplicationRuntimeException("Exception:" + he.getMessage(), he); } catch (Exception e) { LOGGER.error("Exception ===" + e.getMessage()); throw new ApplicationRuntimeException("Exception:" + e.getMessage(), e); } return employeeList; }
From source file:net.lightbody.bmp.proxy.jetty.http.HttpContext.java
/** Get the file classpath of the context. * This method makes a best effort to return a complete file * classpath for the context./*from w w w . j a va2 s . c om*/ * It is obtained by walking the classloader hierarchy and looking for * URLClassLoaders. The system property java.class.path is also checked for * file elements not already found in the loader hierarchy. * @return Path of files and directories for loading classes. * @exception IllegalStateException HttpContext.initClassLoader * has not been called. */ public String getFileClassPath() throws IllegalStateException { ClassLoader loader = getClassLoader(); if (loader == null) throw new IllegalStateException("Context classloader not initialized"); LinkedList paths = new LinkedList(); LinkedList loaders = new LinkedList(); // Walk the loader hierarchy while (loader != null) { loaders.add(0, loader); loader = loader.getParent(); } // Try to handle java2compliant modes loader = getClassLoader(); if (loader instanceof ContextLoader && !((ContextLoader) loader).isJava2Compliant()) { loaders.remove(loader); loaders.add(0, loader); } for (int i = 0; i < loaders.size(); i++) { loader = (ClassLoader) loaders.get(i); if (log.isDebugEnabled()) log.debug("extract paths from " + loader); if (loader instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) loader).getURLs(); for (int j = 0; urls != null && j < urls.length; j++) { try { Resource path = Resource.newResource(urls[j]); if (log.isTraceEnabled()) log.trace("path " + path); File file = path.getFile(); if (file != null) paths.add(file.getAbsolutePath()); } catch (Exception e) { LogSupport.ignore(log, e); } } } } // Add the system classpath elements from property. String jcp = System.getProperty("java.class.path"); if (jcp != null) { StringTokenizer tok = new StringTokenizer(jcp, File.pathSeparator); while (tok.hasMoreTokens()) { String path = tok.nextToken(); if (!paths.contains(path)) { if (log.isTraceEnabled()) log.trace("PATH=" + path); paths.add(path); } else if (log.isTraceEnabled()) log.trace("done=" + path); } } StringBuffer buf = new StringBuffer(); Iterator iter = paths.iterator(); while (iter.hasNext()) { if (buf.length() > 0) buf.append(File.pathSeparator); buf.append(iter.next().toString()); } if (log.isDebugEnabled()) log.debug("fileClassPath=" + buf); return buf.toString(); }
From source file:org.wso2.carbon.ui.BreadCrumbGenerator.java
/** * Generates breadcrumb html content./*www . ja va 2 s. c o m*/ * Please do not add line breaks to places where HTML content is written. * It makes debugging difficult. * @param request * @param currentPageHeader * @return String */ public HashMap<String, String> getBreadCrumbContent(HttpServletRequest request, BreadCrumbItem currentBreadcrumbItem, String jspFilePath, boolean topPage, boolean removeLastItem) { String breadcrumbCookieString = ""; //int lastIndexofSlash = jspFilePath.lastIndexOf(System.getProperty("file.separator")); //int lastIndexofSlash = jspFilePath.lastIndexOf('/'); StringBuffer content = new StringBuffer(); StringBuffer cookieContent = new StringBuffer(); HashMap<String, String> breadcrumbContents = new HashMap<String, String>(); HashMap<String, BreadCrumbItem> breadcrumbs = (HashMap<String, BreadCrumbItem>) request.getSession() .getAttribute("breadcrumbs"); String menuId = request.getParameter("item"); String region = request.getParameter("region"); String ordinalStr = request.getParameter("ordinal"); if (topPage) { //some wizards redirect to index page of the component after doing some operations. //Hence a map of region & menuId for component/index page is maintained & retrieved //by passing index page (eg: ../service-mgt/index.jsp) //This logic should run only for pages marked as toppage=true if (menuId == null && region == null) { HashMap<String, String> indexPageBreadcrumbParamMap = (HashMap<String, String>) request.getSession() .getAttribute("index-page-breadcrumb-param-map"); //eg: indexPageBreadcrumbParamMap contains ../service-mgt/index.jsp : region1,services_list_menu pattern if (indexPageBreadcrumbParamMap != null && !(indexPageBreadcrumbParamMap.isEmpty())) { String params = indexPageBreadcrumbParamMap.get(jspFilePath); if (params != null) { region = params.substring(0, params.indexOf(',')); menuId = params.substring(params.indexOf(',') + 1); } } } } if (menuId != null && region != null) { String key = region.trim() + "-" + menuId.trim(); HashMap<String, String> breadcrumbMap = (HashMap<String, String>) request.getSession() .getAttribute(region + "menu-id-breadcrumb-map"); String breadCrumb = ""; if (breadcrumbMap != null && !(breadcrumbMap.isEmpty())) { breadCrumb = breadcrumbMap.get(key); } if (breadCrumb != null) { content.append("<table cellspacing=\"0\"><tr>"); Locale locale = CarbonUIUtil.getLocaleFromSession(request); String homeText = CarbonUIUtil.geti18nString("component.home", "org.wso2.carbon.i18n.Resources", locale); content.append("<td class=\"breadcrumb-link\"><a href=\"" + CarbonUIUtil.getHomePage() + "\">" + homeText + "</a></td>"); cookieContent.append(breadCrumb); cookieContent.append("#"); generateBreadcrumbForMenuPath(content, breadcrumbs, breadCrumb, true); } } else { HashMap<String, List<BreadCrumbItem>> links = (HashMap<String, List<BreadCrumbItem>>) request .getSession().getAttribute("page-breadcrumbs"); //call came within a page. Retrieve the breadcrumb cookie Cookie[] cookies = request.getCookies(); for (int a = 0; a < cookies.length; a++) { Cookie cookie = cookies[a]; if ("current-breadcrumb".equals(cookie.getName())) { breadcrumbCookieString = cookie.getValue(); //bringing back the , breadcrumbCookieString = breadcrumbCookieString.replace("%2C", ","); //bringing back the # breadcrumbCookieString = breadcrumbCookieString.replace("%23", "#"); if (log.isDebugEnabled()) { log.debug("cookie :" + cookie.getName() + " : " + breadcrumbCookieString); } } } if (links != null) { if (log.isDebugEnabled()) { log.debug("size of page-breadcrumbs is : " + links.size()); } content.append("<table cellspacing=\"0\"><tr>"); Locale locale = CarbonUIUtil.getLocaleFromSession(request); String homeText = CarbonUIUtil.geti18nString("component.home", "org.wso2.carbon.i18n.Resources", locale); content.append("<td class=\"breadcrumb-link\"><a href=\"" + CarbonUIUtil.getHomePage() + "\">" + homeText + "</a></td>"); String menuBreadcrumbs = ""; if (breadcrumbCookieString.indexOf('#') > -1) { menuBreadcrumbs = breadcrumbCookieString.substring(0, breadcrumbCookieString.indexOf('#')); } cookieContent.append(menuBreadcrumbs); cookieContent.append("#"); generateBreadcrumbForMenuPath(content, breadcrumbs, menuBreadcrumbs, false); int clickedBreadcrumbLocation = 0; if (ordinalStr != null) { //only clicking on already made page breadcrumb link will send this via request parameter try { clickedBreadcrumbLocation = Integer.parseInt(ordinalStr); } catch (NumberFormatException e) { // Do nothing log.warn("Found String for breadcrumb ordinal"); } } String pageBreadcrumbs = ""; if (breadcrumbCookieString.indexOf('#') > -1) { pageBreadcrumbs = breadcrumbCookieString.substring(breadcrumbCookieString.indexOf('#') + 1); } StringTokenizer st2 = new StringTokenizer(pageBreadcrumbs, "*"); String[] tokens = new String[st2.countTokens()]; int count = 0; String previousToken = ""; while (st2.hasMoreTokens()) { String currentToken = st2.nextToken(); //To avoid page refresh create breadcrumbs if (!currentToken.equals(previousToken)) { previousToken = currentToken; tokens[count] = currentToken; count++; } } //jspSubContext should be the same across all the breadcrumbs //(cookie is updated everytime a page is loaded) List<BreadCrumbItem> breadcrumbItems = null; // if(tokens != null && tokens.length > 0){ //String token = tokens[0]; //String jspSubContext = token.substring(0, token.indexOf('+')); //breadcrumbItems = links.get("../"+jspSubContext); // } LinkedList<String> tokenJSPFileOrder = new LinkedList<String>(); LinkedList<String> jspFileSubContextOrder = new LinkedList<String>(); HashMap<String, String> jspFileSubContextMap = new HashMap<String, String>(); for (int a = 0; a < tokens.length; a++) { String token = tokens[a]; if (token != null) { String jspFileName = token.substring(token.indexOf('+') + 1); String jspSubContext = token.substring(0, token.indexOf('+')); jspFileSubContextMap.put(jspFileName, jspSubContext); tokenJSPFileOrder.add(jspFileName); jspFileSubContextOrder.add(jspSubContext + "^" + jspFileName); } } if (clickedBreadcrumbLocation > 0) { int tokenCount = tokenJSPFileOrder.size(); while (tokenCount > clickedBreadcrumbLocation) { String lastItem = tokenJSPFileOrder.getLast(); if (log.isDebugEnabled()) { log.debug("Removing breacrumbItem : " + lastItem); } tokenJSPFileOrder.removeLast(); jspFileSubContextOrder.removeLast(); tokenCount = tokenJSPFileOrder.size(); } } boolean lastBreadcrumbItemAvailable = false; if (clickedBreadcrumbLocation == 0) { String tmp = getSubContextFromUri(currentBreadcrumbItem.getLink()) + "+" + currentBreadcrumbItem.getId(); if (!previousToken.equals(tmp)) { //To prevent page refresh lastBreadcrumbItemAvailable = true; } } if (tokenJSPFileOrder != null) { //found breadcrumb items for given sub context for (int i = 0; i < jspFileSubContextOrder.size(); i++) { String token = tokenJSPFileOrder.get(i); //String jspFileName = token.substring(token.indexOf('+')+1); //String jspSubContext = jspFileSubContextMap.get(jspFileName); String fileContextToken = jspFileSubContextOrder.get(i); String jspFileName = fileContextToken.substring(fileContextToken.indexOf('^') + 1); String jspSubContext = fileContextToken.substring(0, fileContextToken.indexOf('^')); if (jspSubContext != null) { breadcrumbItems = links.get("../" + jspSubContext); } if (breadcrumbItems != null) { int bcSize = breadcrumbItems.size(); for (int a = 0; a < bcSize; a++) { BreadCrumbItem tmp = breadcrumbItems.get(a); if (tmp.getId().equals(jspFileName)) { if (tmp.getLink().startsWith("#")) { content.append("<td class=\"breadcrumb-link\"> > " + tmp.getConvertedText() + "</td>"); } else { //if((a+1) == bcSize){ //if((a+1) == bcSize && clickedBreadcrumbLocation > 0){ if ((((a + 1) == bcSize) && !(lastBreadcrumbItemAvailable)) || removeLastItem) { content.append("<td class=\"breadcrumb-link\"> > " + tmp.getConvertedText() + "</td>"); } else { content.append("<td class=\"breadcrumb-link\"> > <a href=\"" + appendOrdinal(tmp.getLink(), i + 1) + "\">" + tmp.getConvertedText() + "</a></td>"); } } cookieContent.append(getSubContextFromUri(tmp.getLink()) + "+" + token + "*"); } } } } } //add last breadcrumb item if (lastBreadcrumbItemAvailable && !(removeLastItem)) { String tmp = getSubContextFromUri(currentBreadcrumbItem.getLink()) + "+" + currentBreadcrumbItem.getId(); cookieContent.append(tmp); cookieContent.append("*"); content.append("<td class=\"breadcrumb-link\"> > " + currentBreadcrumbItem.getConvertedText() + "</td>"); } content.append("</tr></table>"); } } breadcrumbContents.put("html-content", content.toString()); String finalCookieContent = cookieContent.toString(); if (removeLastItem && breadcrumbCookieString != null && breadcrumbCookieString.trim().length() > 0) { finalCookieContent = breadcrumbCookieString; } breadcrumbContents.put("cookie-content", finalCookieContent); return breadcrumbContents; }
From source file:es.bsc.servicess.ide.editors.ImplementationFormPage.java
/** * Get the label of a list of service elements * @param selectedList selected service element * @return Array of element labels/*w w w . j av a 2 s. com*/ */ protected String[] getElementsNames(LinkedList<ServiceElement> selectedList) { String[] elements = new String[selectedList.size()]; for (int i = 0; i < selectedList.size(); i++) { elements[i] = selectedList.get(i).getLabel(); } return elements; }
From source file:org.openscience.cdk.applications.taverna.weka.classification.EvaluateClassificationResultsAsPDFActivity.java
@Override public void work() throws Exception { // Get input//from ww w .j a v a 2s . co m String[] options = ((String) this.getConfiguration() .getAdditionalProperty(CDKTavernaConstants.PROPERTY_SCATTER_PLOT_OPTIONS)).split(";"); List<File> modelFiles = this.getInputAsFileList(this.INPUT_PORTS[0]); List<Instances> trainDatasets = this.getInputAsList(this.INPUT_PORTS[1], Instances.class); List<Instances> testDatasets = null; if (options[0].equals("" + TEST_TRAININGSET_PORT)) { testDatasets = this.getInputAsList(this.INPUT_PORTS[2], Instances.class); } String directory = modelFiles.get(0).getParent(); // Do work ChartTool chartTool = new ChartTool(); WekaTools tools = new WekaTools(); ArrayList<String> resultFiles = new ArrayList<String>(); DefaultCategoryDataset meanClassificationChartset = new DefaultCategoryDataset(); int fileIndex = 0; while (!modelFiles.isEmpty()) { fileIndex++; List<Object> chartObjects = new LinkedList<Object>(); LinkedList<Double> trainPercentage = new LinkedList<Double>(); LinkedList<Double> testPercentage = new LinkedList<Double>(); for (int j = 0; j < trainDatasets.size(); j++) { File modelFile = modelFiles.remove(0); Classifier classifier = (Classifier) SerializationHelper.read(modelFile.getPath()); DefaultCategoryDataset chartDataset = new DefaultCategoryDataset(); String summary = ""; Instances trainset = trainDatasets.get(j); Instances tempset = Filter.useFilter(trainset, tools.getIDRemover(trainset)); Evaluation trainsetEval = new Evaluation(tempset); trainsetEval.evaluateModel(classifier, tempset); String setname = "Training set (" + String.format("%.2f", trainsetEval.pctCorrect()) + "%)"; this.createDataset(trainset, classifier, chartDataset, trainPercentage, setname); summary += "Training set:\n\n"; summary += trainsetEval.toSummaryString(true); double ratio = 100; if (testDatasets != null) { Instances testset = testDatasets.get(j); tempset = Filter.useFilter(testset, tools.getIDRemover(testset)); Evaluation testEval = new Evaluation(trainset); testEval.evaluateModel(classifier, tempset); setname = "Test set (" + String.format("%.2f", testEval.pctCorrect()) + "%)"; this.createDataset(testset, classifier, chartDataset, testPercentage, setname); summary += "\nTest set:\n\n"; summary += testEval.toSummaryString(true); ratio = trainset.numInstances() / (double) (trainset.numInstances() + testset.numInstances()) * 100; } String header = classifier.getClass().getSimpleName() + "\n Training set ratio: " + String.format("%.2f", ratio) + "\n" + modelFile.getName(); chartObjects.add(chartTool.createBarChart(header, "Class", "Correct classified (%)", chartDataset)); chartObjects.add(summary); } DefaultCategoryDataset percentageChartSet = new DefaultCategoryDataset(); double mean = 0; for (int i = 0; i < trainPercentage.size(); i++) { percentageChartSet.addValue(trainPercentage.get(i), "Training Set", "" + (i + 1)); mean += trainPercentage.get(i); } mean /= trainPercentage.size(); meanClassificationChartset.addValue(mean, "Training Set", "" + fileIndex); mean = 0; for (int i = 0; i < testPercentage.size(); i++) { percentageChartSet.addValue(testPercentage.get(i), "Test Set", "" + (i + 1)); mean += testPercentage.get(i); } mean /= testPercentage.size(); meanClassificationChartset.addValue(mean, "Test Set", "" + fileIndex); chartObjects.add(chartTool.createLineChart("Overall Percentages", "Index", "Correct Classified (%)", percentageChartSet, false, true)); File file = FileNameGenerator.getNewFile(directory, ".pdf", "ScatterPlot"); chartTool.writeChartAsPDF(file, chartObjects); resultFiles.add(file.getPath()); } JFreeChart meanChart = chartTool.createLineChart("Overall Percentages", "Model Index", "Correct Classified (%)", meanClassificationChartset, false, true); File file = FileNameGenerator.getNewFile(directory, ".pdf", "ScatterPlot"); chartTool.writeChartAsPDF(file, Collections.singletonList((Object) meanChart)); resultFiles.add(file.getPath()); // Set output this.setOutputAsStringList(resultFiles, this.OUTPUT_PORTS[0]); }
From source file:com.sun.portal.rssportlet.SettingsHandler.java
/** * Initialize the <code>RssPortletBean</code>. * * This is called after the bean has been set into this handler. *//*from w w w. j av a 2 s . c o m*/ private void initSettingsBean() { PortletSession psession = getPortletRequest().getPortletSession(); //mandatory feeds mandate_feeds = (String[]) psession.getAttribute(MANDATE_FEEDS); //organizational feeds role_feeds = (String[]) psession.getAttribute(ROLE_FEEDS); if (role_feeds == null) { Map userInfo = (Map) portletRequest.getAttribute(PortletRequest.USER_INFO); String organizationalStatus = (String) userInfo.get("userRole"); String userRoleFeed = null; if ("Student".equalsIgnoreCase(organizationalStatus)) { userRoleFeed = STUDENT_FEEDS; } else if ("GradStudent".equalsIgnoreCase(organizationalStatus)) { userRoleFeed = GRAD_STUDENT_FEEDS; } else if ("Employee:Staff".equalsIgnoreCase(organizationalStatus)) { userRoleFeed = STAFF_FEEDS; } else if ("Employee:Faculty".equalsIgnoreCase(organizationalStatus)) { userRoleFeed = FACULTY_FEEDS; } else if ("Guest".equalsIgnoreCase(organizationalStatus)) { userRoleFeed = GUEST_FEEDS; } else { userRoleFeed = GUEST_FEEDS; } role_feeds = (String[]) psession.getAttribute(userRoleFeed); psession.setAttribute(ROLE_FEEDS, role_feeds); } //these are the feeds pushed at discrete time levels in the application //the level (horizon) of feeds that are pushed to the user and //seen by the user are tracked in user pref. attribute default_feeds_level default_feeds = (List) psession.getAttribute(DEFAULT_FEEDS); String[] sessionDefaultFeeds = null; if (null != default_feeds && default_feeds.size() != 0) { int default_feeds_level = 1; //every user gets some pushed feeds String feedLevel = (String) psession.getAttribute(SessionKeys.DEFAULT_FEEDS_LEVEL); if (null != feedLevel) { try { default_feeds_level = Integer.parseInt(feedLevel); } catch (NumberFormatException nfe) { default_feeds_level = 1; } } else { default_feeds_level = getIntPreference(PrefKeys.DEFAULT_FEEDS_LEVEL, 1); //stote in session and pref. psession.setAttribute(SessionKeys.DEFAULT_FEEDS_LEVEL, String.valueOf(default_feeds.size())); } sessionDefaultFeeds = (String[]) psession.getAttribute(SESSION_DEFAULT_FEEDS); if (null != sessionDefaultFeeds && sessionDefaultFeeds.length != 0) { sessionDefaultFeeds = new String[] {}; Iterator it = default_feeds.listIterator(); int counter = 1; int newDefaultFeeds = 0; while (it.hasNext()) { if (counter >= default_feeds_level) { String[] defaultFeeds = (String[]) it.next(); for (int i = 0; i < defaultFeeds.length; i++) { sessionDefaultFeeds[newDefaultFeeds] = defaultFeeds[i]; newDefaultFeeds++; } } counter++; } psession.setAttribute(SESSION_DEFAULT_FEEDS, sessionDefaultFeeds); } } //user selected feeds LinkedList feeds = new LinkedList( Arrays.asList(getPortletPreferences().getValues(PrefKeys.USER_FEEDS, new String[] {}))); feeds = stripDelimiter(feeds); //add mandatory+role feeds to feeds list if (null != role_feeds) { if (log.isDebugEnabled()) { log.debug("SetHandler feed role_feeds.length***********" + role_feeds.length); } for (int i = 0; i < role_feeds.length; i++) { feeds.add(i, role_feeds[i]); } } if (null != mandate_feeds) { if (log.isDebugEnabled()) { log.debug("SetHandler feed mandate_feeds.length***********" + mandate_feeds.length); } for (int i = 0; i < mandate_feeds.length; i++) { feeds.add(i, mandate_feeds[i]); } } if (null != sessionDefaultFeeds && sessionDefaultFeeds.length != 0) { if (log.isDebugEnabled()) { log.debug("SetHandler feed mandate_feeds.length***********" + sessionDefaultFeeds.length); } for (int i = 0; i < sessionDefaultFeeds.length; i++) { feeds.add(i, sessionDefaultFeeds[i]); } } if (log.isDebugEnabled()) { Iterator it = feeds.listIterator(); while (it.hasNext()) { log.debug("SettingsHandler feed LinkedList***********" + (String) it.next()); } } getSettingsBean().setFeeds(feeds); int maxAge = getIntPreference(PrefKeys.MAX_AGE, 72); getSettingsBean().setMaxAge(maxAge); int cacheTimeout = getIntPreference(PrefKeys.CACHE_TIMEOUT, 3600); getSettingsBean().setCacheTimeout(cacheTimeout); int maxDescriptionLength = getIntPreference(PrefKeys.MAX_DESCRIPTION_LENGTH, 512); getSettingsBean().setMaxDescriptionLength(maxDescriptionLength); boolean newWindow = getBooleanPreference(PrefKeys.NEWWIN, false); getSettingsBean().setNewWindow(newWindow); boolean disableMaxAge = getBooleanPreference(PrefKeys.DISABLE_MAX_AGE, false); getSettingsBean().setDisableMaxAge(disableMaxAge); int maxEntries = getIntPreference(PrefKeys.MAX_ENTRIES, 5); getSettingsBean().setMaxEntries(maxEntries); if (feeds != null && feeds.size() != 0) { String startFeed = getPortletPreferences().getValue(PrefKeys.START_FEED, (String) feeds.get(0)); System.out.println("SettingsHandler PrefKeys.START_FEED ***********" + startFeed); if (startFeed != null) { startFeed = stripDelimiter(startFeed); } getSettingsBean().setStartFeed(startFeed); } initSelectedFeed(); getSettingsBean().setLocale(getPortletRequest().getLocale()); //set feed titles if (feeds != null && feeds.size() != 0) { setFeedTitleList(feeds); } }
From source file:com.commander4j.thread.InboundMessageThread.java
public void run() { logger.debug("InboundMessageThread running"); Boolean dbconnected = false;/*from w ww .j av a2 s .c om*/ if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) { dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID); } else { dbconnected = true; } if (dbconnected) { JDBInterfaceLog il = new JDBInterfaceLog(getHostID(), getSessionID()); JeMail mail = new JeMail(getHostID(), getSessionID()); JDBInterface inter = new JDBInterface(getHostID(), getSessionID()); IncommingMaterialDefinition imd = new IncommingMaterialDefinition(getHostID(), getSessionID()); IncommingProcessOrderStatusChange iposc = new IncommingProcessOrderStatusChange(getHostID(), getSessionID()); IncommingProductionDeclarationConfirmation ipd = new IncommingProductionDeclarationConfirmation( getHostID(), getSessionID()); IncommingProcessOrder ipo = new IncommingProcessOrder(getHostID(), getSessionID()); IncommingLocation ilocn = new IncommingLocation(getHostID(), getSessionID()); IncommingPalletStatusChange ipsc = new IncommingPalletStatusChange(getHostID(), getSessionID()); IncommingPalletMove ipmv = new IncommingPalletMove(getHostID(), getSessionID()); IncommingBatchStatusChange bsc = new IncommingBatchStatusChange(getHostID(), getSessionID()); IncommingJourney ij = new IncommingJourney(getHostID(), getSessionID()); IncommingInspectionResult iirslt = new IncommingInspectionResult(getHostID(), getSessionID()); IncommingDespatchConfirmation idc = new IncommingDespatchConfirmation(getHostID(), getSessionID()); IncommingQMInspectionRequest iireq = new IncommingQMInspectionRequest(getHostID(), getSessionID()); IncommingMaterialAutoMove imam = new IncommingMaterialAutoMove(getHostID(), getSessionID()); GenericMessageHeader gmh = new GenericMessageHeader(); LinkedList<String> filenames = new LinkedList<String>(); BasicFileAttributes attrs; while (true) { com.commander4j.util.JWait.milliSec(100); if (allDone) { if (dbconnected) { Common.hostList.getHost(hostID).disconnect(getSessionID()); } return; } if (InboundMessageCollectionThread.recoveringFiles == false) { dir = new File(inputPath); chld = dir.listFiles((FileFilter) FileFileFilter.FILE); if (chld == null) { allDone = true; } else { Arrays.sort(chld, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR); filenames.clear(); for (int i = 0; (i < chld.length) & (i < maxfiles); i++) { fileName = chld[i].getName(); try { attrs = Files.readAttributes(chld[i].getAbsoluteFile().toPath(), BasicFileAttributes.class); if (attrs.size() > 0) { if (fileName.endsWith(".xml")) { filenames.addFirst(fileName); com.commander4j.util.JWait.milliSec(50); } } else { try { chld[i].delete(); } catch (Exception ex) { } } } catch (IOException e) { } } if (filenames.size() > 0) { logger.debug("Begin processing " + String.valueOf(filenames.size()) + " files."); for (int i = filenames.size() - 1; i >= 0; i--) { if (allDone) { if (dbconnected) { Common.hostList.getHost(hostID).disconnect(getSessionID()); } return; } fromFile = filenames.get(i); try { logger.debug("<--- START OF PROCESSING " + fromFile + " ---->"); logger.debug("Reading message header : " + inputPath + fromFile); if (gmh.readAddressInfo(inputPath + fromFile, getSessionID()) == true) { messageProcessedOK = true; errorMessage = ""; if (gmh.getInterfaceType().length() == 0) { messageProcessedOK = false; errorMessage = "Unrecognised Commander4j XML message format in file " + fromFile; logger.debug(errorMessage); String datetime = ""; datetime = JUtility .getISOTimeStampStringFormat(JUtility.getSQLDateTime()); gmh.setMessageDate(datetime); gmh.setInterfaceDirection("Unknown"); gmh.setMessageInformation(fromFile); gmh.setInterfaceType("Unknown"); gmh.setMessageRef("Unknown"); } else { if (gmh.getInterfaceDirection().equals("Input") == false) { messageProcessedOK = false; errorMessage = "Inbound message ignored - Interface Direction = " + gmh.getInterfaceDirection(); } else { String interfaceType = gmh.getInterfaceType(); logger.debug("Processing " + interfaceType + " started."); if (interfaceType.equals("Despatch Confirmation") == true) { messageProcessedOK = idc.processMessage(gmh); errorMessage = idc.getErrorMessage(); } if (interfaceType.equals("Material Definition") == true) { messageProcessedOK = imd.processMessage(gmh); errorMessage = imd.getErrorMessage(); } if (interfaceType.equals("Process Order") == true) { messageProcessedOK = ipo.processMessage(gmh); errorMessage = ipo.getErrorMessage(); } if (interfaceType.equals("Location") == true) { messageProcessedOK = ilocn.processMessage(gmh); errorMessage = ilocn.getErrorMessage(); } if (interfaceType.equals("Pallet Status Change") == true) { messageProcessedOK = ipsc.processMessage(gmh); errorMessage = ipsc.getErrorMessage(); } if (interfaceType.equals("Pallet Move") == true) { messageProcessedOK = ipmv.processMessage(gmh); errorMessage = ipmv.getErrorMessage(); } if (interfaceType.equals("Batch Status Change") == true) { messageProcessedOK = bsc.processMessage(gmh); errorMessage = bsc.getErrorMessage(); } if (interfaceType.equals("Journey Definition") == true) { messageProcessedOK = ij.processMessage(gmh); errorMessage = ij.getErrorMessage(); } if (interfaceType.equals("Process Order Status Change") == true) { messageProcessedOK = iposc.processMessage(gmh); errorMessage = iposc.getErrorMessage(); } if (interfaceType.equals("Production Declaration") == true) { messageProcessedOK = ipd.processMessage(gmh); errorMessage = ipd.getErrorMessage(); } if (interfaceType.equals("QM Inspection Request") == true) { messageProcessedOK = iireq.processMessage(gmh); errorMessage = iireq.getErrorMessage(); } if (interfaceType.equals("QM Inspection Result") == true) { messageProcessedOK = iirslt.processMessage(gmh); errorMessage = iirslt.getErrorMessage(); } if (interfaceType.equals("Material Auto Move") == true) { messageProcessedOK = imam.processMessage(gmh); errorMessage = imam.getErrorMessage(); } GenericMessageHeader.updateStats("Input", interfaceType, messageProcessedOK.toString()); logger.debug("Processing " + interfaceType + " finished."); } } logger.debug( " === RESULT " + messageProcessedOK.toString() + " ==="); if (messageProcessedOK) { il.write(gmh, GenericMessageHeader.msgStatusSuccess, "Processed OK", "DB Update", fromFile); reader.deleteFile(backupPath + gmh.getInterfaceType() + File.separator + fromFile); reader.move_FileToDirectory(inputPath + fromFile, backupPath + gmh.getInterfaceType(), true); } else { il.write(gmh, GenericMessageHeader.msgStatusError, errorMessage, "DB Update", fromFile); if (inter.getInterfaceProperties(gmh.getInterfaceType(), "Input") == true) { if (inter.getEmailError() == true) { String emailaddresses = inter.getEmailAddresses(); StringConverter stringConverter = new StringConverter(); ArrayConverter arrayConverter = new ArrayConverter( String[].class, stringConverter); arrayConverter.setDelimiter(';'); arrayConverter.setAllowedChars(new char[] { '@', '_' }); String[] emailList = (String[]) arrayConverter .convert(String[].class, emailaddresses); if (emailList.length > 0) { String siteName = Common.hostList.getHost(getHostID()) .getSiteDescription(); String attachedFilename = Common.base_dir + java.io.File.separator + inputPath + fromFile; logger.debug("Attaching file " + Common.base_dir + java.io.File.separator + inputPath + fromFile); mail.postMail(emailList, "Error Processing Incoming " + gmh.getInterfaceType() + " for [" + siteName + "] on " + JUtility.getClientName(), errorMessage, fromFile, attachedFilename); com.commander4j.util.JWait.milliSec(2000); } } } reader.deleteFile( errorPath + gmh.getInterfaceType() + File.separator + fromFile); reader.move_FileToDirectory(inputPath + fromFile, errorPath + gmh.getInterfaceType(), true); } } logger.debug("<--- END OF PROCESSING " + fromFile + " ---->"); } catch (Exception e) { e.printStackTrace(); } } } } } } } }