List of usage examples for java.util Vector addElement
public synchronized void addElement(E obj)
From source file:org.apache.webdav.lib.WebdavResource.java
public Enumeration reportMethod(HttpURL httpURL, String sQuery, int depth) throws HttpException, IOException { setClient();// www . j ava 2 s . c o m // Default depth=0, type=by_name ReportMethod method = new ReportMethod(httpURL.getEscapedPath(), depth, sQuery); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); generateAdditionalHeaders(method); client.executeMethod(method); Vector results = new Vector(); Enumeration responses = method.getResponses(); while (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); //String href = (String) response.getHref(); String sResult; //= href; // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; sResult = response.toString(); /*while (responseProperties.hasMoreElements()) { Property property = (Property) responseProperties.nextElement(); sResult += "\t" + DOMUtils.getTextValue(property.getElement()); }*/ results.addElement(sResult); } return results.elements(); }
From source file:org.apache.webdav.lib.WebdavResource.java
public Enumeration reportMethod(HttpURL httpURL, Vector properties, Vector histUri, int depth) throws HttpException, IOException { setClient();//from w w w . j a va2s. co m // Default depth=0, type=by_name ReportMethod method = new ReportMethod(httpURL.getEscapedPath(), depth, properties.elements(), histUri.elements()); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); generateAdditionalHeaders(method); client.executeMethod(method); Vector results = new Vector(); Enumeration responses = method.getResponses(); while (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); String href = response.getHref(); String sResult = href; // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; Enumeration responseProperties = method.getResponseProperties(href); while (responseProperties.hasMoreElements()) { Property property = (Property) responseProperties.nextElement(); sResult += "\n" + property.getName() + ":\t" + DOMUtils.getTextValue(property.getElement()); } results.addElement(sResult); } return results.elements(); }
From source file:org.apache.webdav.lib.WebdavResource.java
/** * Execute the REPORT method.// w w w . j av a 2 s.co m */ public Enumeration reportMethod(HttpURL httpURL, int depth) throws HttpException, IOException { setClient(); // Default depth=0, type=by_name ReportMethod method = new ReportMethod(httpURL.getEscapedPath(), depth); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); generateAdditionalHeaders(method); client.executeMethod(method); Vector results = new Vector(); Enumeration responses = method.getResponses(); while (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); String href = response.getHref(); String sResult = href; // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; Enumeration responseProperties = method.getResponseProperties(href); while (responseProperties.hasMoreElements()) { Property property = (Property) responseProperties.nextElement(); sResult += "\n" + property.getName() + ":\t" + DOMUtils.getTextValue(property.getElement()); } results.addElement(sResult); } return results.elements(); }
From source file:com.duroty.application.files.manager.SearchManager.java
public SearchObj advanced(Session hsession, String repositoryName, AdvancedObj advancedObj, int page, int messagesByPage, int order, String orderType) throws FilesException { String lucenePathMessages = null; if (!defaultLucenePath.endsWith(File.separator)) { lucenePathMessages = defaultLucenePath + File.separator + repositoryName + File.separator + Constants.MAIL_LUCENE_MESSAGES; } else {//w ww . j a va2 s . co m lucenePathMessages = defaultLucenePath + repositoryName + File.separator + Constants.MAIL_LUCENE_MESSAGES; } Searcher searcher = null; SearchObj searchObj = new SearchObj(); Sort sort = null; try { Users user = getUser(hsession, repositoryName); Locale locale = new Locale(user.getUseLanguage()); TimeZone timeZone = TimeZone.getDefault(); Date now = new Date(); Calendar calendar = Calendar.getInstance(timeZone, locale); calendar.setTime(now); SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale); SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale); SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale); searcher = MailIndexer.getSearcher(lucenePathMessages); if (!StringUtils.isBlank(advancedObj.getSubject())) { advancedObj.setSubject("Files-System"); } Query query = AdvancedQueryParser.parseMessages(advancedObj, analyzer); ; /*BooleanQuery booleanQuery = new BooleanQuery(); QueryParser parser = new QueryParser(Field_attachments, analyzer); parser.setDefaultOperator(Operator.AND); Query aux1 = parser.parse("\"Message Text\""); booleanQuery.add(aux1, BooleanClause.Occur.MUST_NOT); Query aux2 = AdvancedQueryParser.parseMessages(advancedObj, analyzer); booleanQuery.add(aux2, BooleanClause.Occur.MUST); query = booleanQuery;*/ Hits hits = null; Date searchStart = new Date(); boolean reverse = true; if (orderType.equals("ASC")) { reverse = false; } else { reverse = true; } switch (order) { case ORDER_BY_SIZE: sort = new Sort(new SortField[] { new SortField(Field_size, SortField.STRING, reverse), SortField.FIELD_SCORE }); break; case ORDER_BY_DATE: sort = new Sort(new SortField[] { new SortField(Field_lastDate, SortField.STRING, reverse), SortField.FIELD_SCORE }); break; default: sort = new Sort(new SortField[] { new SortField(null, SortField.SCORE, !reverse) }); break; } int label = 0; if (advancedObj.getLabel() != null) { label = advancedObj.getLabel().getIdint(); } ChainedFilter chained = null; if (label > 0) { chained = getChainedFilter(hsession, repositoryName, label); } if (chained != null) { hits = searcher.search(query, chained, sort); } else { hits = searcher.search(query, sort); } Date searchEnd = new Date(); //time in seconds double time = ((double) (searchEnd.getTime() - searchStart.getTime())) / (double) 1000; int hitsLength = hits.length(); if (hitsLength <= 0) { return null; } int start = page * messagesByPage; int end = start + messagesByPage; if (end > 0) { end = Math.min(hitsLength, end); } else { end = hitsLength; } if (start > end) { throw new SearchException("Search index of bound. start > end"); } Vector files = new Vector(); for (int j = start; j < end; j++) { Document doc = hits.doc(j); if (doc != null) { LuceneMessage lmsg = new LuceneMessage(doc); Message message = getMessage(hsession, repositoryName, lmsg.getIdint()); if (message != null) { Set set = message.getAttachments(); if (set != null) { Iterator it = set.iterator(); while (it.hasNext()) { Attachment attachment = (Attachment) it.next(); String name = attachment.getAttName(); if (!StringUtils.isBlank(name) && !name.equals("Message Text")) { AttachmentObj obj = new AttachmentObj(); obj.setContentType(attachment.getAttContentType()); obj.setScore((int) (hits.score(j) * 100)); Date date = message.getMesDate(); if (date != null) { Calendar calendar2 = Calendar.getInstance(timeZone, locale); calendar2.setTime(date); if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) { obj.setDateStr(formatter2.format(calendar2.getTime())); } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) { obj.setDateStr(formatter1.format(calendar2.getTime())); } else { obj.setDateStr(formatter3.format(calendar2.getTime())); } } obj.setDate(date); obj.setDate(date); obj.setIdint(attachment.getAttIdint()); obj.setName(attachment.getAttName()); obj.setPart(attachment.getAttPart()); int size = attachment.getAttSize(); size /= 1024; if (size > 1024) { size /= 1024; obj.setSize(size + " MB"); } else { obj.setSize(((size > 0) ? (size + "") : "<1") + " kB"); } String extension = (String) this.extensions.get(attachment.getAttContentType()); if (StringUtils.isBlank(extension)) { extension = "generic"; } obj.setExtension(extension); if (message.isMesFlagged()) { obj.setFlagged(true); } else { obj.setFlagged(false); } if (message.getLabMeses() != null) { Iterator it2 = message.getLabMeses().iterator(); StringBuffer lab = new StringBuffer(); while (it2.hasNext()) { if (lab.length() > 0) { lab.append(", "); } LabMes labMes = (LabMes) it2.next(); lab.append(labMes.getId().getLabel().getLabName()); } if (lab.length() > 0) { obj.setLabel(lab.toString()); } else { } } obj.setBox(message.getMesBox()); obj.setMid(message.getMesName()); files.addElement(obj); } } } } } } searchObj.setHits(hitsLength); searchObj.setTime(time); searchObj.setFiles(files); } catch (Exception ex) { throw new FilesException(ex); } finally { GeneralOperations.closeHibernateSession(hsession); } return searchObj; }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
@SuppressWarnings("unchecked") protected void sequentialXMLImport(Element dbImport, String dbTable, String parentName, long parentId) { try {/*from w ww . j a v a 2s. com*/ String id = new String(); DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); List records = dbImport.selectNodes("//" + dbTable); //$NON-NLS-1$ String lowerdbTable = lowerFirstChar(dbTable); // TODO: should not assume that is the id name, use getPrimaryKeyName DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); // List ids = dbImport.selectNodes("//"+lowerdbTable+"Id");//assume this is dbs id name List ids = dbImport.selectNodes("//" + primaryKey); //$NON-NLS-1$ if (records.size() < 1) { log.debug("Cannot import. Given database type:" + dbTable //$NON-NLS-1$ + " does not exsist in import file"); //$NON-NLS-1$ } else { // loop for each record for (int k = 0; k < records.size(); k++) { // Vector collectionIds = new Vector(20); Vector<String> collectionNames = new Vector(20); // keep this id to compare against it's collection Element idElement = (Element) ids.get(k); // id = attribute.getText(); id = idElement.getStringValue(); // make the agent and the element Object agent = parentInfo.getClassObj().newInstance(); Map<String, Object> agentMap = new HashMap<String, Object>(); Element dbElement = (Element) records.get(k); Iterator i = dbElement.elementIterator(); do {// do for each element in the record Element element = (Element) i.next(); Object value = findTypeSequential(element, dbTable, parentId, parentName);// the // parent // is // itself, // just // a // dummy // variable // if(value!=null && value != "collection") if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ { agentMap.put(element.getName(), value); } // ignore many-to-many for now else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ {// RECURSE // get assoicated ids // List temp_collection_ids = // element.selectNodes("//"+dbTable+"["+id+"]/"+element.getName()+"/*");//+upperElement); List temp_collection_ids = element .selectNodes("//" + dbTable + "[" + primaryKey + " = \"" + id //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ // get collection info and still dont add it if (!temp_collection_ids.isEmpty()) { // get child dbName String childDbName = getDbName(temp_collection_ids); collectionNames.addElement(childDbName); for (int index = 0; index < temp_collection_ids.size(); index++) { collectionIds.addElement(temp_collection_ids.get(index)); } } } else // else, dont add it { // if it is an id, just ignore. otherwise print out error if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$ { log.debug("did not add " + element.getName() //$NON-NLS-1$ + " to the element " + dbTable); //$NON-NLS-1$ } } } while (i.hasNext()); // populate and save BeanUtils.populate(agent, agentMap); this.session.save(agent); // session.lock(agent, LockMode.NONE); // if there was a collection, then recurse if (!collectionIds.isEmpty()) { long newParentId = new Long(session.getIdentifier(agent).toString()).longValue(); sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId); } } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); // String err = ex.toString(); // the last par tof the string conatins the class // if(err.startsWith("org.hibernate.PropertyValueException")){ try { // try again // flush // do reference work // importTable("ReferenceWork"); // the import aagain } catch (Exception ex1) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex1); ex1.printStackTrace(); } // }else{ ex.printStackTrace(); // } } }
From source file:com.duroty.application.files.manager.SearchManager.java
/** * DOCUMENT ME!//from ww w . j a v a2 s . co m * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param token DOCUMENT ME! * @param page DOCUMENT ME! * @param messagesByPage DOCUMENT ME! * @param order DOCUMENT ME! * @param orderType DOCUMENT ME! * * @return DOCUMENT ME! * * @throws FilesException DOCUMENT ME! */ public SearchObj simple(Session hsession, String repositoryName, String token, String folderName, int label, int page, int messagesByPage, int order, String orderType) throws FilesException { String lucenePathMessages = null; if (!defaultLucenePath.endsWith(File.separator)) { lucenePathMessages = defaultLucenePath + File.separator + repositoryName + File.separator + Constants.MAIL_LUCENE_MESSAGES; } else { lucenePathMessages = defaultLucenePath + repositoryName + File.separator + Constants.MAIL_LUCENE_MESSAGES; } Searcher searcher = null; SearchObj searchObj = new SearchObj(); Sort sort = null; try { Users user = getUser(hsession, repositoryName); Locale locale = new Locale(user.getUseLanguage()); TimeZone timeZone = TimeZone.getDefault(); Date now = new Date(); Calendar calendar = Calendar.getInstance(timeZone, locale); calendar.setTime(now); SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale); SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale); SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale); searcher = MailIndexer.getSearcher(lucenePathMessages); Query query = null; if (!StringUtils.isBlank(folderName) && folderName.equals(this.folderFiles)) { BooleanQuery booleanQuery = new BooleanQuery(); QueryParser parser = new QueryParser(Field_subject, analyzer); parser.setDefaultOperator(Operator.AND); Query aux1 = parser.parse("Files-System"); booleanQuery.add(aux1, BooleanClause.Occur.MUST); Query aux2 = SimpleQueryParser.parse(token, analyzer); booleanQuery.add(aux2, BooleanClause.Occur.MUST); /*QueryParser parser2 = new QueryParser(Field_attachments, analyzer); parser2.setDefaultOperator(Operator.AND); Query aux3 = parser2.parse("Message Text"); booleanQuery.add(aux3, BooleanClause.Occur.MUST_NOT);*/ query = booleanQuery; } else { /*BooleanQuery booleanQuery = new BooleanQuery(); QueryParser parser = new QueryParser(Field_attachments, analyzer); parser.setDefaultOperator(Operator.AND); Query aux1 = parser.parse("Message Text"); booleanQuery.add(aux1, BooleanClause.Occur.MUST_NOT); Query aux2 = SimpleQueryParser.parse(token, analyzer); booleanQuery.add(aux2, BooleanClause.Occur.MUST); query = booleanQuery;*/ query = SimpleQueryParser.parse(token, analyzer); } Hits hits = null; Date searchStart = new Date(); boolean reverse = true; if (orderType.equals("ASC")) { reverse = false; } else { reverse = true; } switch (order) { case ORDER_BY_SIZE: sort = new Sort(new SortField[] { new SortField(Field_size, SortField.STRING, reverse), SortField.FIELD_SCORE }); break; case ORDER_BY_DATE: sort = new Sort(new SortField[] { new SortField(Field_lastDate, SortField.STRING, reverse), SortField.FIELD_SCORE }); break; default: sort = new Sort(new SortField[] { new SortField(null, SortField.SCORE, !reverse) }); break; } ChainedFilter chained = null; if (label > 0) { chained = getChainedFilter(hsession, repositoryName, label); } if (chained != null) { hits = searcher.search(query, chained, sort); } else { hits = searcher.search(query, sort); } Date searchEnd = new Date(); //time in seconds double time = ((double) (searchEnd.getTime() - searchStart.getTime())) / (double) 1000; int hitsLength = hits.length(); if (hitsLength <= 0) { return null; } int start = page * messagesByPage; int end = start + messagesByPage; if (end > 0) { end = Math.min(hitsLength, end); } else { end = hitsLength; } if (start > end) { throw new SearchException("Search index of bound. start > end"); } Vector files = new Vector(); for (int j = start; j < end; j++) { Document doc = hits.doc(j); if (doc != null) { LuceneMessage lmsg = new LuceneMessage(doc); Message message = getMessage(hsession, repositoryName, lmsg.getIdint()); if (message != null) { Set set = message.getAttachments(); if (set != null) { Iterator it = set.iterator(); while (it.hasNext()) { Attachment attachment = (Attachment) it.next(); String name = attachment.getAttName(); if (!StringUtils.isBlank(name) && !name.equals("Message Text")) { AttachmentObj obj = new AttachmentObj(); obj.setContentType(attachment.getAttContentType()); obj.setScore((int) (hits.score(j) * 100)); Date date = message.getMesDate(); if (date != null) { Calendar calendar2 = Calendar.getInstance(timeZone, locale); calendar2.setTime(date); if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) { obj.setDateStr(formatter2.format(calendar2.getTime())); } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) { obj.setDateStr(formatter1.format(calendar2.getTime())); } else { obj.setDateStr(formatter3.format(calendar2.getTime())); } } obj.setDate(date); obj.setDate(date); obj.setIdint(attachment.getAttIdint()); obj.setName(attachment.getAttName()); obj.setPart(attachment.getAttPart()); int size = attachment.getAttSize(); size /= 1024; if (size > 1024) { size /= 1024; obj.setSize(size + " MB"); } else { obj.setSize(((size > 0) ? (size + "") : "<1") + " kB"); } String extension = (String) this.extensions.get(attachment.getAttContentType()); if (StringUtils.isBlank(extension)) { extension = "generic"; } obj.setExtension(extension); if (message.isMesFlagged()) { obj.setFlagged(true); } else { obj.setFlagged(false); } if (message.getLabMeses() != null) { Iterator it2 = message.getLabMeses().iterator(); StringBuffer lab = new StringBuffer(); while (it2.hasNext()) { if (lab.length() > 0) { lab.append(", "); } LabMes labMes = (LabMes) it2.next(); lab.append(labMes.getId().getLabel().getLabName()); } if (lab.length() > 0) { obj.setLabel(lab.toString()); } else { } } obj.setBox(message.getMesBox()); obj.setMid(message.getMesName()); files.addElement(obj); } } } } } } searchObj.setHits(hitsLength); searchObj.setTime(time); searchObj.setFiles(files); } catch (Exception ex) { throw new FilesException(ex); } finally { GeneralOperations.closeHibernateSession(hsession); } return searchObj; }
From source file:com.zeroio.webdav.WebdavServlet.java
/** * PROPFIND Method./* w ww .j a va 2 s . c om*/ * * @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:org.apache.webdav.lib.WebdavResource.java
public Enumeration reportMethod(HttpURL httpURL, Vector properties, int depth) throws HttpException, IOException { setClient();/*from w ww .j a v a 2s. c om*/ // Default depth=0, type=by_name ReportMethod method = new ReportMethod(httpURL.getEscapedPath(), depth, properties.elements()); method.setDebug(debug); method.setFollowRedirects(this.followRedirects); generateTransactionHeader(method); generateAdditionalHeaders(method); client.executeMethod(method); /*first draft, does work anyhow Enumeration results = method.getAllResponseURLs(); return results;*/ /* Enumeration responses = method.getResponses(); ResponseEntity response = (ResponseEntity) responses.nextElement(); String href = (String) response.getHref(); Enumeration results = method.getResponseProperties(href); return results;*/ Vector results = new Vector(); Enumeration responses = method.getResponses(); while (responses.hasMoreElements()) { ResponseEntity response = (ResponseEntity) responses.nextElement(); String href = response.getHref(); String sResult = href; // Set status code for this resource. if ((thisResource == true) && (response.getStatusCode() > 0)) setStatusCode(response.getStatusCode()); thisResource = false; Enumeration responseProperties = method.getResponseProperties(href); while (responseProperties.hasMoreElements()) { Property property = (Property) responseProperties.nextElement(); sResult += "\n" + property.getName() + ":\t" + DOMUtils.getTextValue(property.getElement()); // results.addElement(DOMUtils.getTextValue(property.getElement())); } results.addElement(sResult); } return results.elements(); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * Given a message that we are replying to, or forwarding, * * @param part The part to decode./*from w w w . j av a2s . c om*/ * @param buffer The new message body text buffer. * @param dmailParts Vector for new message's attachments. * * @return The buffer being filled in with the body. * * @throws MessagingException DOCUMENT ME! * @throws IOException */ protected static StringBuffer subDecodeContent(Part part, StringBuffer buffer, Vector dmailParts, boolean chooseHtml, String breakLine) throws MessagingException, IOException { boolean attachIt = true; // decode based on content type and disposition ContentType xctype = MessageUtilities.getContentType(part); ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part); if (xctype.match("multipart/*")) { attachIt = false; Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part); int xparts = 0; try { xparts = xmulti.getCount(); } catch (MessagingException e) { attachIt = true; xparts = 0; } for (int xindex = 0; xindex < xparts; xindex++) { MessageUtilities.subDecodeContent(xmulti.getBodyPart(xindex), buffer, dmailParts, chooseHtml, breakLine); } } else if (xctype.match("message/rfc822")) { MimeMessage newMessage = new MimeMessage((Session) null, part.getInputStream()); decodeContent(newMessage, buffer, dmailParts, chooseHtml, breakLine); } else if (xctype.match("text/plain") && !chooseHtml) { if (xcdisposition.match("inline")) { attachIt = false; String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = part.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { System.out.print(ex.getMessage()); } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } MessageUtilities.decodeTextPlain(buffer, part, breakLine, xjcharset); } } else if (xctype.match("text/html") && chooseHtml) { if (xcdisposition.match("inline")) { attachIt = false; String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = part.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } MessageUtilities.decodeTextHtml(buffer, part, xjcharset); } } if (attachIt) { // UNDONE should simple single line entries be // created for other types and attachments? // // UNDONE should attachements only be created for "attachments" or all // unknown content types? if (dmailParts != null) { MailPart aux = new MailPart(); aux.setPart(part); aux.setId(dmailParts.size()); aux.setName(MessageUtilities.encodeStringToXml(MessageUtilities.getPartName(part))); aux.setContentType(xctype.getBaseType()); aux.setSize(part.getSize()); dmailParts.addElement(aux); } } return buffer; }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
@SuppressWarnings("unchecked") protected void sequentialXMLImportRecursion(Vector collectionNames, Vector collectionIds, String parentName, long parentId) { int idIndex = 0; try {//from w w w.j a va 2 s.c om // for each collection for (int z = 0; z < collectionNames.size(); z++) { // get table to work on String dbTable = collectionNames.get(z).toString(); String lowerdbTable = lowerFirstChar(dbTable); DBTableInfo info = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); String primaryKey = info.getPrimaryKeyName(); // open xml file File path = new File(importFolderPath + dbTable + ".xml"); //$NON-NLS-1$ Element dbImport = XMLHelper.readFileToDOM4J(path); DBTableInfo tableInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase()); // loop for each id that we need in this table for (int k = 0; k < collectionIds.size() && idIndex < collectionIds.size(); k++) { Vector newCollectionIds = new Vector(20); Vector newCollectionNames = new Vector(20); // the only way to get the value out of collectionIds Element temp_id = (Element) collectionIds.get(idIndex); // is this the right element to work on // if so use else; otherwise stop the loop if (temp_id.getName().equals(dbTable)) { idIndex++; String id = temp_id.getText(); // select the node // TODO shouldl not assume things are in order // Element collectingevent = // (Element)dbImport.selectSingleNode("//"+dbTable+"["+id+"]");//temp_id.getText()+"]"); Element collectingevent = (Element) dbImport.selectSingleNode("//" //$NON-NLS-1$ + dbTable + "[" + primaryKey + " = \"" + id + "\"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Iterator iter = collectingevent.elementIterator(); // make the element and the agent Map<String, Object> agentMap = new HashMap<String, Object>(); Object agent = tableInfo.getClassObj().newInstance(); do { Element element = (Element) iter.next(); Object value2 = findTypeSequential(element, dbTable, parentId, parentName); if (value2 != null && value2 != "OneToMany" && value2 != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$ { agentMap.put(element.getName(), value2); } else if (value2 == "ManyToMany") //$NON-NLS-1$ { Set<Object> parentSet = new HashSet<Object>(); Object parentObject = genericDBObject2(parentName, parentId); parentSet.add(parentObject); agentMap.put(element.getName(), parentSet); } else if (value2 == "OneToMany") //$NON-NLS-1$ { // RECURSE // get assoicated ids // TODO shouldl not assume things are in order // List temp_collection_ids = // element.selectNodes("//"+dbTable+"["+id+"]/"+element.getName()+"/*");//+upperElement); List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$ + primaryKey + " = \"" + id + "\"]/" + element.getName() //$NON-NLS-1$ //$NON-NLS-2$ + "/*"); //$NON-NLS-1$ // get collection info and still dont add it if (!temp_collection_ids.isEmpty()) { // get child dbName String childDbName = getDbName(temp_collection_ids); newCollectionNames.addElement(childDbName); for (int index = 0; index < temp_collection_ids.size(); index++) { newCollectionIds.addElement(temp_collection_ids.get(index)); } } } else { // if it is an id, just ignore. otherwise print out error if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$ { log.debug("did not add " + element.getName() //$NON-NLS-1$ + " to the element " + dbTable); //$NON-NLS-1$ } } } while (iter.hasNext()); // add to the set BeanUtils.populate(agent, agentMap); this.session.saveOrUpdate(agent); // if there was a collection, then recurse if (!newCollectionIds.isEmpty()) { long newParentId = new Long(session.getIdentifier(agent).toString()).longValue(); sequentialXMLImportRecursion(newCollectionNames, newCollectionIds, dbTable, newParentId); } } else {// stop the loop k = collectionIds.size(); } } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); // the last par tof the string conatins the class // if(err.startsWith("org.hibernate.PropertyValueException")){ try { // try again // flush // do reference work // importTable("ReferenceWork"); // the import aagain } catch (Exception ex1) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex1); ex1.printStackTrace(); } // }else{ ex.printStackTrace(); // } } }