List of usage examples for java.util Vector contains
public boolean contains(Object o)
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try {/* w w w .jav a 2s . c o m*/ LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; }
From source file:imapi.OnlineDatabaseActions.java
private int readJsonUriVals(InputStream inputStream, Vector<String> uriVals) { try {//from w w w. j a v a 2s . co m JsonReader rdr = new JsonReader(new InputStreamReader(inputStream)); JsonParser parser = new JsonParser(); JsonElement jElement = parser.parse(rdr); if (jElement.isJsonObject() == false) { showContentsOfInputStream(inputStream); return ApiConstants.IMAPIFailCode; } // read head/vars from json in order to get the names of the // select clause in the order that they were declared. // Store in headVarNames vector Vector<String> headVarNames = new Vector<String>(); JsonObject jRootObject = jElement.getAsJsonObject(); JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray(); Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator(); while (jVarsIter.hasNext()) { JsonElement jVarElement = jVarsIter.next(); if (jVarElement.isJsonPrimitive()) { headVarNames.add(jVarElement.getAsString()); } } if (jRootObject.has("results") == false || jRootObject.get("results").getAsJsonObject().has("bindings") == false) { return ApiConstants.IMAPIFailCode; } // loop over all json bindings JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings") .getAsJsonArray(); Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator(); while (jBindingsIter.hasNext()) { // of the binding String uri = ""; JsonElement jBindingElement = jBindingsIter.next(); if (jBindingElement.isJsonObject() == false) { continue; } JsonObject jBindingObject = jBindingElement.getAsJsonObject(); for (int k = 0; k < headVarNames.size(); k++) { String currentPropertyName = headVarNames.get(k); if (jBindingObject.has(currentPropertyName)) { JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject(); String valStr = ""; if (jObj.has("value")) { valStr = jObj.get("value").getAsString(); } if (k == 0) { uri = valStr; } } } if (uri.length() > 0 && uriVals.contains(uri) == false) { uriVals.add(uri); } // end of asking for all predicates of select clause head/vars names } // edn of while llop that iters across all bindings } catch (Exception ex) { Utilities.handleException(ex); return ApiConstants.IMAPIFailCode; } return ApiConstants.IMAPISuccessCode; }
From source file:org.alfresco.repo.transfer.AlienProcessorImpl.java
public void beforeDeleteAlien(NodeRef deletedNodeRef, ChildAssociationRef oldAssoc) { log.debug("before delete node - need to check for alien invaders"); List<String> stuff = (List<String>) nodeService.getProperty(deletedNodeRef, TransferModel.PROP_INVADED_BY); if (stuff == null) return;// w ww .j ava 2 s .c o m Vector<String> exInvaders = new Vector<String>(stuff); /** * some fudge to get this to run after the node has been moved. */ ChildAssociationRef currentAssoc; if (oldAssoc != null) { currentAssoc = oldAssoc; } else { currentAssoc = nodeService.getPrimaryParent(deletedNodeRef); } while (currentAssoc != null && exInvaders != null && exInvaders.size() > 0) { NodeRef parentNodeRef = currentAssoc.getParentRef(); NodeRef currentNodeRef; if (currentAssoc == oldAssoc) { currentNodeRef = deletedNodeRef; } else { currentNodeRef = currentAssoc.getChildRef(); } /** * Does the parent have alien invaders ? */ if (nodeService.hasAspect(parentNodeRef, TransferModel.ASPECT_ALIEN)) { log.debug("parent node is invaded by aliens"); /** * Remove the parent's origin from the list of exInvaders since the parent also invades. */ String parentRepoId; if (nodeService.hasAspect(parentNodeRef, TransferModel.ASPECT_TRANSFERRED)) { parentRepoId = (String) nodeService.getProperty(parentNodeRef, TransferModel.PROP_FROM_REPOSITORY_ID); } else { parentRepoId = descriptorService.getCurrentRepositoryDescriptor().getId(); } exInvaders.remove(parentRepoId); /** * For each invader of the deletedNode */ Iterator<String> i = exInvaders.listIterator(); while (i.hasNext()) { String exInvader = i.next(); log.debug("Checking exInvader:" + exInvader); /** * Check the siblings of this node to see whether there are any other alien nodes for this invader. */ //List<ChildAssociationRef> refs = nodeService.getChildAssocs(parentNodeRef); List<ChildAssociationRef> refs = nodeService.getChildAssocsByPropertyValue(parentNodeRef, TransferModel.PROP_INVADED_BY, exInvader); for (ChildAssociationRef ref : refs) { NodeRef childRef = ref.getChildRef(); List<String> invadedBy = (List<String>) nodeService.getProperty(childRef, TransferModel.PROP_INVADED_BY); if (childRef.equals(currentNodeRef)) { // do nothing - this is the node we are working with. } else { if (invadedBy != null && invadedBy.contains(exInvader)) { // There is a sibling so remove this from the list of ex invaders. log.debug("yes there is a sibling so it remains an invader"); i.remove(); break; } } } // for each child assoc } // for each invader log.debug("end of checking siblings"); if (exInvaders.size() > 0) { log.debug("removing invaders from parent node:" + parentNodeRef); List<String> parentInvaders = (List<String>) nodeService.getProperty(parentNodeRef, TransferModel.PROP_INVADED_BY); final List<String> newInvaders = new ArrayList<String>(10); for (String invader : parentInvaders) { if (exInvaders.contains(invader)) { log.debug("removing invader:" + invader); } else { newInvaders.add(invader); } } final NodeRef oldAlien = parentNodeRef; /** * Parent may be locked or not be editable by the current user * turn off auditing and lock service for this transaction and * run as admin. */ RunAsWork<Void> actionRunAs = new RunAsWork<Void>() { public Void doWork() throws Exception { behaviourFilter.disableBehaviour(oldAlien, ContentModel.ASPECT_AUDITABLE); behaviourFilter.disableBehaviour(oldAlien, ContentModel.ASPECT_LOCKABLE); if (newInvaders.size() > 0) { nodeService.setProperty(oldAlien, TransferModel.PROP_INVADED_BY, (Serializable) newInvaders); } else { log.debug("parent node is no longer alien nodeRef" + oldAlien); nodeService.removeAspect(oldAlien, TransferModel.ASPECT_ALIEN); } return null; } }; AuthenticationUtil.runAs(actionRunAs, AuthenticationUtil.getSystemUserName()); } /** * Now step up to the parent's parent */ currentAssoc = nodeService.getPrimaryParent(parentNodeRef); } else { log.debug("parent is not an alien node"); currentAssoc = null; } } // end of while }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Adapts a given questionnaire form before being administered to a requesting user in a given community context. * For adaptation purposes, questionnaire authors can make use of a set of author tags, which are replaced by this method. * The syntax for author tags is ${AT}. The following values for AT are supported: * <ul>//from www. j a v a2s . c om * <li>USER.ID - identifier of requesting user</li> * <li>USER.NAME - login name of requesting user</li> * <li>USER.MAIL - email address of requesting user</li> * <li>COMMUNITY.ID - identifier of community, in whose context questionnaire form is requested</li> * <li>SURVEY.ID - identifier of survey, in whose context questionnaire form is requested </li> * <li>SURVEY.NAME - name of survey, in whose context questionnaire form is requested </li> * <li>SURVEY.DESCRIPTION - description of survey, in whose context questionnaire form is requested </li> * <li>SURVEY.RESOURCE - resource under consideration in survey, in whose context questionnaire form is requested </li> * <li>SURVEY.START - ISO-8601 compliant UTC start time of survey, in whose context questionnaire form is requested </li> * <li>SURVEY.END - ISO-8601 compliant UTC end time of survey, in whose context questionnaire form is requested </li> * <li>SURVEY.OWNER - owner of survey </li> * <li>SURVEY.ORGANIZATION - organization owner of survey belongs to </li> * <li>SURVEY.LOGO - logo to be shown in survey header, e.g. organization logo </li> * </ul> * * @param originalFormXml * @param survey * @param user * @param community * @return */ private String adaptForm(String originalFormXml, JSONObject survey, UserAgent user, GroupAgent community) { // detect all tags used by questionnaire author throughout the form // and replace them by the respective values. Pattern p = Pattern.compile("\\$\\{([^\\}])+\\}"); Matcher m = p.matcher(originalFormXml); String adaptedform = new String(originalFormXml); // replace any occurring author tags within questionnaire form Vector<String> foundTags = new Vector<String>(); while (m.find()) { String tag = m.group().substring(2, m.group().length() - 1); String value = null; if (!foundTags.contains(tag)) { if (tag.startsWith("USER")) { if (tag.endsWith("ID")) { value = "" + user.getId(); } else if (tag.endsWith("NAME")) { value = user.getLoginName(); } else if (tag.endsWith("MAIL")) { value = user.getEmail(); } } else if (tag.startsWith("COMMUNITY")) { if (tag.endsWith("ID")) { if (community != null) { value = "" + community.getId(); } else { value = "(no community context)"; } } } else if (tag.startsWith("SURVEY.")) { if (tag.endsWith("ID")) { value = (String) (survey.get("id") + ""); } else if (tag.endsWith("NAME")) { value = (String) survey.get("name"); } else if (tag.endsWith("DESCRIPTION")) { value = (String) survey.get("description"); } else if (tag.endsWith("RESOURCE")) { String id = (String) survey.get("resource"); HttpResponse r = getClientMetadata(id); if (r.getStatus() == 200) { JSONObject meta = (JSONObject) JSONValue.parse(r.getResult()); value = (String) meta.get("name"); } else { value = id; } //JSONObject res = (JSONObject) survey.get("resource"); //String res_name = (String) res.get("name"); //value = res_name; } else if (tag.endsWith("START")) { value = (String) survey.get("start"); } else if (tag.endsWith("END")) { value = (String) survey.get("end"); } else if (tag.endsWith("OWNER")) { value = (String) survey.get("owner"); } else if (tag.endsWith("ORGANIZATION")) { value = (String) survey.get("organization"); } else if (tag.endsWith("LOGO")) { value = (String) survey.get("logo"); } } //TODO: add more author tags, if necessary. if (value != null) { adaptedform = adaptedform.replaceAll("\\$\\{" + tag + "\\}", value); //System.out.println("Resolved questionnaire author tag: "+tag); foundTags.add(tag); } else { System.err.println("Warning: could not resolve questionnaire author tag '" + tag + "'"); } } } /* // add a welcome information page to be displayed before any questionnaire content provided by the // questionnaire author is presented. String introPageName = "Welcome"; String introPageInstructions = "First of all welcome and thank you for your participation in our survey '"+svin[1]+"'."+svin[2]+ "Within this survey you will now be asked to fill in questionnaire '"+quin[1]+"' regarding community "+g.getName()+". "+quin[2]+" On the following "+quin[3]+" pages you will be asked to answer "+(Integer.parseInt(quin[5]) + Integer.parseInt(quin[6]) +Integer.parseInt(quin[7]))+" questions in total."+ "In "+quin[5]+" questions you will be asked to decide between two alternatives (yes/no or the like). Another "+quin[6]+" questions will ask you to provide an ordinal scale ranking regarding certain properties of service "+ed.getName()+". "+ "Another "+quin[7]+" questions will ask you to enter informal text (e.g. for personal comments). You can decide for yourself, if you want to answer or skip each individual question. However, please try to answer as many questions as possible. "+ "If you do not understand a particular question you are advised to skip it. Let's go for it!"; String introPageXml = "\n<qu:Page name=\""+introPageName+"\" xsi:type=\"qu:InformationPageType\">\n <qu:Instructions>"+introPageInstructions+"</qu:Instructions>\n</qu:Page>\n"; adaptedform = adaptedform.replaceFirst("<qu:Page",introPageXml+"<qu:Page"); */ return adaptedform; }
From source file:Admin_Thesaurus.ImportData.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (SystemIsLockedForAdministrativeJobs(request, response)) { return;/*from ww w . j a v a2 s.com*/ } String basePath = request.getSession().getServletContext().getRealPath(""); // ---------------------- LOCK SYSTEM ---------------------- ConfigDBadmin config = new ConfigDBadmin(basePath); DBAdminUtilities dbAdminUtils = new DBAdminUtilities(); dbAdminUtils.LockSystemForAdministrativeJobs(config); response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); ServletContext context = session.getServletContext(); SessionWrapperClass sessionInstance = new SessionWrapperClass(); init(request, response, sessionInstance); PrintWriter out = response.getWriter(); OutputStreamWriter logFileWriter = null; try { // check for previous logon but because of ajax usage respond with Session Invalidate str UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser"); if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) { out.println("Session Invalidate"); response.sendRedirect("Index"); return; } //tools Utilities u = new Utilities(); DBGeneral dbGen = new DBGeneral(); DBImportData dbImport = new DBImportData(); DBMergeThesauri dbMerge = new DBMergeThesauri(); StringObject translatedMsgObj = new StringObject(""); Vector<String> thesauriNames = new Vector<String>(); CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config); StringObject resultObj = new StringObject(""); String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus; //Parameters String xmlFilePath = request.getParameter("importXMLfilename"); //String importSchemaName = request.getParameter("schematype"); String importSchemaName = ConstantParameters.xmlschematype_THEMAS; String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME"); String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport String importHierarchyName = u .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName")); String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml"); String language = context.getInitParameter("LocaleLanguage"); String country = context.getInitParameter("LocaleCountry"); String WebAppUsersFileName = request.getSession().getServletContext() .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath); String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName); String logFileNamePath = logPath; String webAppSaveResults_Folder = Parameters.Save_Results_Folder; String pathToSaveScriptingAndLocale = context .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml"); Locale targetLocale = new Locale(language, country); if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null)) || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) { UpDownFiles fup = new UpDownFiles(); String[] formData = new String[10]; FileItem[] dom = fup.prepareToUpBinary(request, formData); //Hashtable initParams = UpDownFiles.uploadParams; if (dom[0] != null) { String filename = xmlFilePath; ///String caption = (String) initParams.get("caption"); filename = filename.substring(filename.lastIndexOf(File.separator) + 1); String fileType = filename.substring(filename.lastIndexOf(".") + 1); String userFileName = filename.substring(0, filename.lastIndexOf(".")); filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType; String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename; xmlFilePath = fullPath; if (fup.writeBinary(dom[0], fullPath)) { //mode = 1; } else { //mode = -1; } } else { //mode = -1; } } QClass Q = new QClass(); TMSAPIClass TA = new TMSAPIClass(); IntegerObject sis_session = new IntegerObject(); IntegerObject tms_session = new IntegerObject(); //open connection and start transaction if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null, true) == QClass.APIFail) { Utils.StaticClass .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName()); return; } dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session); if (importMethodChoice.equals("thesaurusImport")) { //Format Name Of import Thesaurus importThesaurusName = importThesaurusName.trim(); importThesaurusName = importThesaurusName.replaceAll(" ", "_"); importThesaurusName = importThesaurusName.toUpperCase(); if (thesauriNames.contains(importThesaurusName)) { resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure", new String[] { importThesaurusName })); //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus."); Vector<String> allHierarchies = new Vector<String>(); Vector<String> allGuideTerms = new Vector<String>(); dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session, allHierarchies, allGuideTerms); //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); //Q.TEST_abort_transaction(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); StringBuffer xml = new StringBuffer(); xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI)); xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms, targetLocale)); xml.append(getXMLMiddle(thesauriNames, u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null) + resultObj.getValue(), importMethodChoice)); xml.append(u.getXMLUserInfo(SessionUserInfo)); xml.append(u.getXMLEnd()); u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl"); // ---------------------- UNLOCK SYSTEM ---------------------- dbAdminUtils.UnlockSystemForAdministrativeJobs(); return; } } else if (importMethodChoice.equals("bulkImport")) { importThesaurusName = SessionUserInfo.selectedThesaurus; if (thesauriNames.contains(importThesaurusName) == false) { //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml"); //StringObject resultMessageObj = new StringObject(); StringObject resultMessageObj_2 = new StringObject(); //Vector<String> errorArgs = new Vector<String>(); resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist", new String[] { importThesaurusName })); //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists."); Vector<String> allHierarchies = new Vector<String>(); Vector<String> allGuideTerms = new Vector<String>(); dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session, allHierarchies, allGuideTerms); //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); //Q.TEST_abort_transaction(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); StringBuffer xml = new StringBuffer(); xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI)); xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms, targetLocale)); resultMessageObj_2 .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null)); xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(), importMethodChoice)); //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice)); xml.append(u.getXMLUserInfo(SessionUserInfo)); xml.append(u.getXMLEnd()); u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl"); // ---------------------- UNLOCK SYSTEM ---------------------- dbAdminUtils.UnlockSystemForAdministrativeJobs(); return; } } //end query and close connection Q.free_all_sets(); Q.TEST_end_query(); dbGen.CloseDBConnection(Q, null, sis_session, null, false); Utils.StaticClass.closeDb(); StringObject DBbackupFileNameCreated = new StringObject(""); long startTime = Utilities.startTimer(); String time = Utilities.GetNow(); String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time; logFileNamePath += "/" + Filename + ".xml"; try { OutputStream fout = new FileOutputStream(logFileNamePath); OutputStream bout = new BufferedOutputStream(fout); logFileWriter = new OutputStreamWriter(bout, "UTF-8"); logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n" //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n"); logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\"" + Parameters.PrimaryLang.toLowerCase() + "\">\r\n"); logFileWriter.append("<title>" + u.translateFromMessagesXML("root/ImportData/ReportTitle", new String[] { importThesaurusName, time }) + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale + "</pathToSaveScriptingAndLocale>\r\n"); //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n"); Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time + " LogFile for data import in thesaurus: " + importThesaurusName + "."); } catch (Exception exc) { Utils.StaticClass.webAppSystemOutPrintln( Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage()); Utils.StaticClass.handleException(exc); } if (importMethodChoice.equals("thesaurusImport")) { if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale, pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName, "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated, resultObj, logFileWriter) == false) { abortActions(request, sessionInstance, context, targetLocale, common_utils, initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj, out); return; } } else if (importMethodChoice.equals("bulkImport")) { /* //open connection and start Transaction if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail) { Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName()); return; } */ if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale, pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName, "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated, resultObj, logFileWriter) == false) { abortActions(request, sessionInstance, context, targetLocale, common_utils, initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj, out); return; } } commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName, out, Filename.concat(".html")); //ReportSuccessMessage logFileWriter .append("\r\n<creationInfo>" + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage", new String[] { importThesaurusName, xmlFilePath, ((Utilities.stopTimer(startTime)) / 60) + "" }) + "</creationInfo>\r\n"); if (logFileWriter != null) { logFileWriter.append("</page>"); logFileWriter.flush(); logFileWriter.close(); } //Now XSL should be found and java xsl transformation should be performed String XSL = context.getRealPath("/" + webAppSaveResults_Folder) + "/ImportCopyMergeThesaurus_Report.xsl"; u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html")); } catch (Exception e) { Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet " + getServletName() + ". Message:" + e.getMessage()); Utils.StaticClass.handleException(e); if (logFileWriter != null) { logFileWriter.append("</page>"); logFileWriter.flush(); logFileWriter.close(); } } finally { out.flush(); out.close(); sessionInstance.writeBackToSession(session); } }
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try {/* w w w . ja v a 2 s .c o m*/ // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; }
From source file:org.kchine.r.server.DirectJNI.java
static Integer guessNewDevice(int[] snapshot) throws RemoteException { Vector<Integer> devicesVectorBefore = new Vector<Integer>(); for (int i = 0; i < snapshot.length; ++i) devicesVectorBefore.add(snapshot[i]); int[] devicesNow = snapshotDevices(); for (int i = 0; i < devicesNow.length; ++i) if (!devicesVectorBefore.contains(devicesNow[i])) { return devicesNow[i]; }//from w w w. j a v a 2s .c o m return null; }
From source file:com.zeroio.webdav.WebdavServlet.java
/** * PROPFIND Method.// w ww . j a v a2 s . c o m * * @param context Description of the Parameter * @throws ServletException Description of the Exception * @throws IOException Description of the Exception */ protected void doPropfind(ActionContext context) throws ServletException, IOException { String path = getRelativePath(context.getRequest()); //fix for windows clients if (path.equals("/files")) { path = ""; } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN); return; } if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) { //Fix for MACOSX finder. Do not allow requests for files starting with a period return; } //System.out.println("METHOD PROPFIND....PATH: " + path); // Properties which are to be displayed. Vector properties = null; // Propfind depth by default 1 for performance reasons int depth = 1; // Propfind type int type = FIND_ALL_PROP; String depthStr = context.getRequest().getHeader("Depth"); if (depthStr == null) { depth = INFINITY; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = INFINITY; } } /* * Read the request xml and determine all the properties */ Node propNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (Exception e) { // Most likely there was no content : we use the defaults. // TODO : Enhance that ! //e.printStackTrace(System.out); } if (type == FIND_BY_PROPERTY) { properties = new Vector(); if (!properties.contains("creationdate")) { //If the request did not contain creationdate property then add this to requested properties //to make the information available for clients properties.addElement("creationdate"); } NodeList childList = propNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring(nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } // Properties have been determined // Retrieve the resources Connection db = null; boolean exists = true; boolean status = true; Object current = null; Object child = null; ModuleContext resources = null; SystemStatus thisSystem = null; StringBuffer xmlsb = new StringBuffer(); try { db = this.getConnection(context); resources = getCFSResources(db, context); if (resources == null) { context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } thisSystem = this.getSystemStatus(context); current = resources.lookup(thisSystem, db, path); if (current instanceof ModuleContext) { //System.out.println( ((ModuleContext) current).toString()); } } catch (NamingException e) { //e.printStackTrace(System.out); exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = (String) lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS); context.getResponse().setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING); parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type, properties); generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); //e.printStackTrace(System.out); return; } } } } } catch (SQLException e) { e.printStackTrace(System.out); context.getResponse().sendError(CFS_SQLERROR, e.getMessage()); status = false; } finally { this.freeConnection(db, context); } if (!status) { return; } if (!exists) { context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS); context.getResponse().setContentType("text/xml; charset=UTF-8"); // Create multistatus object ////System.out.println("Creating Multistatus Object"); XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING); //System.out.println("Depth: " + depth); if (depth == 0) { parseProperties(context, resources, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack stack = new Stack(); stack.push(path); // Stack of the objects one level below Stack stackBelow = new Stack(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = (String) stack.pop(); try { if (!currentPath.equals(path)) { //object at url currentPath not yet looked up. so perform lookup at url currentPath child = resources.lookup(currentPath); parseProperties(context, resources, generatedXML, currentPath, type, properties); } } catch (NamingException e) { e.printStackTrace(System.out); continue; } if (!status) { return; } if ((current instanceof ModuleContext) && depth > 0) { // Get a list of all the resources at the current path and store them // in the stack try { NamingEnumeration enum1 = ((ModuleContext) current).list(""); int count = 0; while (enum1.hasMoreElements()) { NameClassPair ncPair = (NameClassPair) enum1.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) { newPath += "/"; } newPath += ncPair.getName(); //System.out.println("STACKING CHILD: " + newPath); stackBelow.push(newPath); count++; } if (currentPath.equals(path) && count == 0) { // This directory does not have any files or folders. //System.out.println("DIRECTORY HAS NO FILES OR FOLDERS..."); parseProperties(context, resources, generatedXML, properties); } } catch (NamingException e) { //e.printStackTrace(System.out); context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that collection String lockPath = currentPath; if (lockPath.endsWith("/")) { lockPath = lockPath.substring(0, lockPath.length() - 1); } Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = (String) lockNullResourcesList.nextElement(); System.out.println("Lock null path: " + lockNullPath); parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack(); } xmlsb.append(generatedXML.toString()); //System.out.println("xml : " + generatedXML.toString()); generatedXML.sendData(); } } Iterator locks = lockNullResources.keySet().iterator(); while (locks.hasNext()) { String lockpath = (String) locks.next(); //System.out.println("LOCK PATH: " + lockpath); } generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING); xmlsb.append(generatedXML.toString()); generatedXML.sendData(); //System.out.println("xml: " + xmlsb.toString()); }
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); long ms = System.currentTimeMillis(), delay = 0; String action = "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab);//from w w w . j av a 2 s . c o m HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); //Set keyset = hmap.keySet(); //Iterator it = keyset.iterator(); Iterator it = hmap.entrySet().iterator(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; ms_all = System.currentTimeMillis(); while (it.hasNext()) { ms_categorization = System.currentTimeMillis(); //String rel_rela = (String) it.next(); // _logger.debug("rel_rela: " + rel_rela); Entry thisEntry = (Entry) it.next(); String rel_rela = (String) thisEntry.getKey(); if (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); String rela = (String) u.elementAt(1); String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; /* * if (parent_asso_vec.contains(rel)) category = "Child"; else * if (child_asso_vec.contains(rel)) category = "Parent"; else * if (bt_vec.contains(rel)) category = "Narrower"; else if * (nt_vec.contains(rel)) category = "Broader"; */ else if (sibling_asso_vec.contains(rel)) category = "Sibling"; ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization); //Object obj = hmap.get(rel_rela); Object obj = thisEntry.getValue(); if (obj != null) { Vector v = (Vector) obj; // For each related concept: for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = (AssociatedConcept) v.elementAt(i); EntityDescription ed = ac.getEntityDescription(); Entity c = ac.getReferencedEntry(); if (!hset.contains(c.getEntityCode())) { hset.add(c.getEntityCode()); // Find the highest ranked atom data ms_find_highest_rank_atom = System.currentTimeMillis(); String t = findRepresentativeTerm(c, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); t = t + "|" + c.getEntityCode() + "|" + rela + "|" + category; // _logger.debug(t); w.add(t); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && category.compareTo("RO") != 0) { if (rel_hset.contains(c.getEntityCode())) { rel_hset.add(c.getEntityCode()); } } if (category.compareTo("Child") == 0 && category.compareTo("CHD") != 0) { if (hasSubtype_hset.contains(c.getEntityCode())) { hasSubtype_hset.add(c.getEntityCode()); } } } } } } } Vector u = new Vector(); // Remove redundant RO relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("RO") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } // Remove redundant CHD relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("CHD") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } ms_all_delay = System.currentTimeMillis() - ms_all; action = "categorizing relationships into six categories"; Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay); DBG.debugDetails(ms_categorization_delay, action, "getNeighborhoodSynonyms"); action = "finding highest ranked atoms"; Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay; action = "removing redundant RO relationships"; Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay); DBG.debugDetails(ms_remove_RO_delay, action, "getNeighborhoodSynonyms"); // Initial sort (refer to sortSynonymData method for sorting by a // specific column) long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); DBG.debugDetails("Max Return", NCImBrowserProperties.get_maxToReturn()); return u; }
From source file:kenh.xscript.elements.Call.java
@Override public int invoke() throws UnsupportedScriptException { logger.info(getInfo());/*from w w w .ja va 2 s . com*/ this.getEnvironment().removeVariable(Return.VARIABLE_RETURN); // clear {return} // 1) find Method Map<String, Element> methods = this.getEnvironment().getMethods(); String name = getAttribute(ATTRIBUTE_METHOD_NAME); if (StringUtils.isBlank(name)) { UnsupportedScriptException ex = new UnsupportedScriptException(this, "The method name is empty."); throw ex; } try { name = (String) this.getEnvironment().parse(name); } catch (Exception e) { throw new UnsupportedScriptException(this, e); } String var = getAttribute(ATTRIBUTE_RETURN_NAME); if (StringUtils.isNotBlank(var)) { try { var = StringUtils.trimToNull((String) this.getEnvironment().parse(var)); } catch (Exception e) { throw new UnsupportedScriptException(this, e); } } Element e = methods.get(name); if (e == null || !(e instanceof Method)) { UnsupportedScriptException ex = new UnsupportedScriptException(this, "Could't find the method to invoke. [" + name + "]"); throw ex; } // 2) handle the Method's parameter Method m = (Method) e; String[][] parameters = m.getParameters(); Map<String, Object> new_vars = new LinkedHashMap(); List<String> new_cons = new LinkedList(); Vector parameterCallback = new Vector(); for (String[] parameter : parameters) { String paraName = StringUtils.trimToEmpty(parameter[0]); if (StringUtils.isBlank(paraName)) continue; boolean required = false; Object defaultValue = null; if (parameter.length > 1) { for (int i = 1; i < parameter.length; i++) { String modi = StringUtils.trimToEmpty(parameter[i]); if (modi.equals(Method.MODI_FINAL)) { new_cons.add(paraName); } if (modi.equals(Method.MODI_REQUIRED)) { required = true; } if ((modi.startsWith(Method.MODI_DEFAULT + "(") && modi.endsWith(")"))) { String defaultValue_ = StringUtils.substringAfter(modi, Method.MODI_DEFAULT + "("); defaultValue_ = StringUtils.substringBeforeLast(defaultValue_, ")"); try { defaultValue = this.getEnvironment().parse(defaultValue_); } catch (UnsupportedExpressionException e_) { UnsupportedScriptException ex = new UnsupportedScriptException(this, e_); throw ex; } } } } String paraValue = this.getAttribute(paraName); Object paraObj = null; if (paraValue == null) { if (required) { UnsupportedScriptException ex = new UnsupportedScriptException(this, "Missing parameter. [" + paraName + "]"); throw ex; } else { if (defaultValue != null) { new_vars.put(paraName, defaultValue); } } } else { try { paraObj = this.getEnvironment().parse(paraValue); new_vars.put(paraName, paraObj); if (paraObj instanceof kenh.expl.Callback) { parameterCallback.add(paraObj); } } catch (UnsupportedExpressionException ex) { throw new UnsupportedScriptException(this, ex); } } } if (this.getAttributes().size() > new_vars.size() + (this.getAttributes().containsKey(ATTRIBUTE_RETURN_NAME) ? 2 : 1)) { java.util.Set<String> keys = this.getAttributes().keySet(); String additional = ""; for (String key : keys) { if (key.equals(ATTRIBUTE_METHOD_NAME)) continue; if (key.equals(ATTRIBUTE_RETURN_NAME)) continue; if (new_vars.containsKey(key)) continue; additional = additional + key + ", "; } UnsupportedScriptException ex = new UnsupportedScriptException(this, "Unknown parameter. [" + StringUtils.substringBeforeLast(additional, ",") + "]"); throw ex; } // 3) remove non-public variable in Environment. save Method's parameter in Environment. List<String> publics = this.getEnvironment().getPublics(); List<String> constant = this.getEnvironment().getContants(); Map<String, Object> keep_vars = new LinkedHashMap(); List<String> keep_cons = new LinkedList(); List<String> keep_pubs = new LinkedList(); java.util.Set<String> keys = this.getEnvironment().getVariables().keySet(); for (String key : keys) { if (!publics.contains(key)) { keep_vars.put(key, this.getEnvironment().getVariable(key)); if (constant.contains(key)) keep_cons.add(key); } } keys = keep_vars.keySet(); for (String key : keys) { if (constant.contains(key)) constant.remove(key); this.getEnvironment().removeVariable(key, false); } // public variable in Environment have the same name with Method's parameter for (String[] parameter : parameters) { String key = StringUtils.trimToEmpty(parameter[0]); if (this.getEnvironment().containsVariable(key)) { if (constant.contains(key)) { constant.remove(key); keep_cons.add(key); } publics.remove(key); keep_pubs.add(key); keep_vars.put(key, this.getEnvironment().removeVariable(key, false)); } this.getEnvironment().setVariable(key, new_vars.get(key)); if (new_cons.contains(key)) constant.add(key); } // 4)invoke the Method's child elements. int r = m.processChildren(); if (r != RETURN && r != NONE) { if (r == EXCEPTION) { Object ex = this.getEnvironment().getVariable(Constant.VARIABLE_EXCEPTION); if (ex instanceof Exception) { if (ex instanceof UnsupportedScriptException) { throw (UnsupportedScriptException) ex; } else { UnsupportedScriptException ex_ = new UnsupportedScriptException(this, (Exception) ex); throw ex_; } } } UnsupportedScriptException ex = new UnsupportedScriptException(this, "Unsupported value is returned. [" + r + "]"); throw ex; } Object returnObj = null; if (StringUtils.isNotBlank(var)) { if (r == RETURN) { returnObj = this.getEnvironment().getVariable(Return.VARIABLE_RETURN); } else { UnsupportedScriptException ex = new UnsupportedScriptException(this, "The method does not have return value. [" + name + "]"); throw ex; } } // 5) remove non-public variable from Environment. restore original variables List<String> remove_vars = new LinkedList(); keys = this.getEnvironment().getVariables().keySet(); for (String key : keys) { if (!publics.contains(key)) { remove_vars.add(key); } } for (String key : remove_vars) { if (constant.contains(key)) constant.remove(key); Object obj = this.getEnvironment().getVariable(key); if (parameterCallback.contains(obj)) { this.getEnvironment().removeVariable(key, false); } else { this.getEnvironment().removeVariable(key); } } keys = keep_vars.keySet(); for (String key : keys) { if (!constant.contains(key)) { if (!this.getEnvironment().containsVariable(key)) this.getEnvironment().setVariable(key, keep_vars.get(key)); } if (keep_cons.contains(key)) constant.add(key); if (keep_pubs.contains(key)) publics.add(key); } // 6) store {return} if (returnObj != null) { this.saveVariable(var, returnObj, null); } return NONE; }