List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:shiec.secondBlock.RegisterGenerator.java
/** * Generate XML data out of request InputStream. * @throws SAXException //from w ww .j a va 2 s .co m */ public void generate() throws IOException, SAXException, ProcessingException { System.out.println("getting in..."); SAXParser parser = null; int len = 0; String contentType; Request request = ObjectModelHelper.getRequest(this.objectModel); try { contentType = request.getContentType(); if (contentType == null) { contentType = parameters.getParameter("defaultContentType", null); if (getLogger().isDebugEnabled()) { getLogger().debug("no Content-Type header - using contentType parameter: " + contentType); } if (contentType == null) { throw new IOException("Both Content-Type header and defaultContentType parameter are not set"); } } InputSource source; if (contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("multipart/form-data")) { String parameter = parameters.getParameter(FORM_NAME, null); if (parameter == null) { throw new ProcessingException("StreamGenerator expects a sitemap parameter called '" + FORM_NAME + "' for handling form data"); } Object xmlObject = request.get(parameter); Reader xmlReader; if (xmlObject instanceof String) { xmlReader = new StringReader((String) xmlObject); } else if (xmlObject instanceof Part) { xmlReader = new InputStreamReader(((Part) xmlObject).getInputStream()); } else { throw new ProcessingException( "Unknown request object encountered named " + parameter + " : " + xmlObject); } source = new InputSource(xmlReader); } else if (contentType.startsWith("text/plain") || contentType.startsWith("text/xml") || contentType.startsWith("application/xhtml+xml") || contentType.startsWith("application/xml")) { HttpServletRequest httpRequest = (HttpServletRequest) objectModel .get(HttpEnvironment.HTTP_REQUEST_OBJECT); if (httpRequest == null) { throw new ProcessingException("This feature is only available in an http environment."); } len = request.getContentLength(); if (len <= 0) { throw new IOException("getContentLen() == 0"); } PostInputStream anStream = new PostInputStream(httpRequest.getInputStream(), len); source = new InputSource(anStream); } else { throw new IOException("Unexpected getContentType(): " + request.getContentType()); } if (getLogger().isDebugEnabled()) { getLogger().debug("Processing stream ContentType=" + contentType + " ContentLength=" + len); } String charset = getCharacterEncoding(request, contentType); if (charset != null) { source.setEncoding(charset); } String path = "D:/Java/kepler/workspace/secondBlock/src/main/resources/COB-INF/database/"; //String path = "../database/"; File file = new File(path + "description.xml"); if (!file.exists()) { try { file.createNewFile(); System.out.println("creating new description file..."); } catch (IOException e) { e.printStackTrace(); } } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(source); String fileName = "";//the name of the description file. Get from the description. NodeList nodeList = doc.getElementsByTagName("spec"); Node root = nodeList.item(0); fileName = ((Element) root).getAttribute("name"); File newFile = new File(path + fileName + ".xml"); if (!newFile.exists()) { DOMSource src = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StreamResult result = new StreamResult(file); transformer.transform(src, result); System.out.println("Transforming..."); FileUtils.copyFile(file, newFile); file.delete(); String changePath = "D:/Java/kepler/workspace/secondBlock/src/main/resources/COB-INF/demo/"; File changeFile = new File(changePath + "deviceList.xml"); System.out.println("Reading file..."); DocumentBuilderFactory changeFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder changeBuilder = changeFactory.newDocumentBuilder(); Document changeDoc = changeBuilder.parse(changeFile); Element toAdd = changeDoc.createElement("Device"); toAdd.setAttribute("id", fileName); Element var = changeDoc.createElement("Name"); var.setTextContent(fileName); toAdd.appendChild(var); changeDoc.getFirstChild().appendChild(toAdd); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transform = tFactory.newTransformer(); //transform.setOutputProperty(OutputKeys.INDENT,"yes"); DOMSource domSource = new DOMSource(changeDoc); StreamResult domResult = new StreamResult(new FileOutputStream(changeFile)); transform.transform(domSource, domResult); } } catch (IOException e) { getLogger().error("StreamGenerator.generate()", e); throw new ResourceNotFoundException("StreamGenerator could not find resource", e); } catch (SAXException e) { getLogger().error("StreamGenerator.generate()", e); throw (e); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } catch (TransformerConfigurationException e1) { e1.printStackTrace(); } catch (TransformerException e1) { e1.printStackTrace(); } finally { this.manager.release(parser); } }
From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java
/** * Transforms the given <code>xml</code> section from KFS3 format to KFS6 * format./* www . j av a 2 s . c om*/ * * @param xml * {@link String} of the XML to transform * @return {@link String} of the transformed XML * @throws Exception * Any {@link Exception}s encountered will be rethrown. */ private String transformSection(String xml, String docid) throws Exception { String rawXml = xml; String maintenanceAction = StringUtils.substringBetween(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">", "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = upgradeBONotes(xml, docid); if (classNameRuleMap == null) { setRuleMaps(); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document; try { document = db.parse(new InputSource(new StringReader(xml))); } catch (SAXParseException ex) { String eol = System.getProperty("line.separator"); String exMsg = "Failed in db.parse(new InputSource(new StringReader(xml))) where xml=" + xml + eol + "of maintenanceAction = " + maintenanceAction + eol + "contained in rawXml = " + rawXml; throw new SAXParseException(exMsg, null, ex); } for (Node childNode = document.getFirstChild(); childNode != null;) { Node nextChild = childNode.getNextSibling(); transformClassNode(document, childNode); // Also Transform first level Children which have class attribute NodeList children = childNode.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node child = children.item(n); if ((child != null) && (child.getNodeType() == Node.ELEMENT_NODE) && (child.hasAttributes())) { NamedNodeMap childAttributes = child.getAttributes(); if (childAttributes.item(0).getNodeName() == "class") { String childClassName = childAttributes.item(0).getNodeValue(); if (classPropertyRuleMap.containsKey(childClassName)) { Map<String, String> propertyMappings = classPropertyRuleMap.get(childClassName); NodeList nestedChildren = child.getChildNodes(); for (int i = 0; i < nestedChildren.getLength() - 1; i++) { Node property = nestedChildren.item(i); String propertyName = property.getNodeName(); if ((property.getNodeType() == Node.ELEMENT_NODE) && (propertyMappings != null) && (propertyMappings.containsKey(propertyName))) { String newPropertyName = propertyMappings.get(propertyName); if (StringUtils.isNotBlank(newPropertyName)) { document.renameNode(property, null, newPropertyName); propertyName = newPropertyName; } else { // If there is no replacement name then the element needs to be removed child.removeChild(property); } } } } } } } childNode = nextChild; } /* * the default logic that traverses over the document tree doesn't * handle classes that are in an @class attribute, so we deal with those * individually. */ migratePersonObjects(document); migrateKualiCodeBaseObjects(document); migrateAccountExtensionObjects(document); migrateClassAsAttribute(document); removeAutoIncrementSetElements(document); removeReconcilerGroup(document); catchMissedTypedArrayListElements(document); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer trans = transFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); trans.transform(source, result); /* * (?m) puts the regex into multiline mode: * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern. * html#MULTILINE So the effect of this statement is * "remove any empty lines" */ xml = writer.toString().replaceAll("(?m)^\\s+\\n", ""); xml = xml + "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">" + maintenanceAction + "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"; // replace classnames not updated so far that were captured by smoke test below // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("active defined-in=\"" + className + "\"")) { LOGGER.info("Replacing active defined-in= attribute: " + className + " with: " + classNameRuleMap.get(className) + " at docid= " + docid); xml = xml.replace("active defined-in=\"" + className + "\"", "active defined-in=\"" + classNameRuleMap.get(className) + "\""); } } // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("<" + className + ">")) { LOGGER.info("Replacing open tag: <" + className + "> with: <" + classNameRuleMap.get(className) + ">" + " at docid= " + docid); xml = xml.replace("<" + className + ">", "<" + classNameRuleMap.get(className) + ">"); } } // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("</" + className + ">")) { LOGGER.info("Replacing close tag: </" + className + "> with: </" + classNameRuleMap.get(className) + ">" + " at docid= " + docid); xml = xml.replace("</" + className + ">", "</" + classNameRuleMap.get(className) + ">"); } } // replace classnames not updated so far that were captured by smoke test below // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("maintainableImplClass=\"" + className + "\"")) { LOGGER.info("Replacing maintainableImplClass= attribute: " + className + " with: " + classNameRuleMap.get(className) + " at docid= " + docid); xml = xml.replace("maintainableImplClass=\"" + className + "\"", "maintainableImplClass=\"" + classNameRuleMap.get(className) + "\""); } } // investigative logging, still useful as a smoke test for (String oldClassName : classNameRuleMap.keySet()) { if (xml.contains(oldClassName)) { LOGGER.warn("Document has classname in contents that should have been mapped: " + oldClassName); LOGGER.warn("at docid= " + docid + " for xml= " + xml); } } checkForElementsWithClassAttribute(document); return xml; }
From source file:uk.ac.ox.webauth.WebauthGetTokensRequest.java
/** Post a token request message to the WebKDC and parse the response. */ public void tokenRequest() throws IOException { String request = getRequestMessage(krb_ap_req); WebKdcXmlRequest wkxr = new WebKdcXmlRequest(url); Document doc = wkxr.doPost(request); /* check if we actually got an error response and if so throw an exception <errorResponse>/*from ww w . ja v a 2s. com*/ <!-- only if present in request --> <messageId>{message-id}</messageId> <errorCode>{numeric}<errorCode> <errorMessage>{message}<errorMessage> </errorResponse> */ if ("errorResponse".equalsIgnoreCase(doc.getFirstChild().getNodeName())) { NodeList children = doc.getFirstChild().getChildNodes(); String errorCode = null; String errorMessage = null; for (int i = 0; i < children.getLength(); i++) { Node n = children.item(i); String nodeName = n.getNodeName(); if ("errorCode".equalsIgnoreCase(nodeName)) { errorCode = n.getFirstChild().getNodeValue(); } else if ("errorMessage".equalsIgnoreCase(nodeName)) { errorMessage = n.getFirstChild().getNodeValue(); } } throw new IOException("Received error message when trying to request service token. Error code: '" + errorCode + "', error message: '" + errorMessage + "'"); } parseResponse(doc); }
From source file:uk.me.jeffsutton.pojogen.SimplePOJO.java
public String generate(BufferedReader xml) throws ParserConfigurationException, SAXException, IOException { Document document = parse(xml); rootTageName = stripNS(document.getFirstChild().getNodeName()); visitClass(document.getFirstChild()); List<String> toRemove = new ArrayList<>(); for (XClass xClass : classes.values()) { if (xClass.fields == null || xClass.fields.size() < 1) { toRemove.add(xClass.name);// w w w. ja va2 s . c o m } } for (XClass xClass : classes.values()) { for (XField field : xClass.fields.values()) { if (toRemove.contains(field.dataType)) { field.dataType = "String"; } } } for (String s : toRemove) { classes.remove(s); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); System.out.println(gson.toJson(classes)); return (generateClassText(classes.get(rootTageName))); }
From source file:userstudy.TaskCreator.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww . ja v a 2s. c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); try { String command = request.getParameter("command"); if (command.equalsIgnoreCase("checkTaskNameAvailability")) { String msg = "notExists"; //read the quanttask file to see if the name exists String taskShortName = request.getParameter("taskShortName").toString(); String userid = request.getParameter("userid").toString(); if (!taskShortName.trim().isEmpty()) { //read the quant-task-files. String tasklistFilename = getServletContext().getRealPath("users" + File.separator + userid + File.separator + "quanttasks" + File.separator + "quanttasklist.txt"); File taskListFile = new File(tasklistFilename); String line = ""; if (taskListFile.exists()) { BufferedReader br = new BufferedReader(new FileReader(taskListFile)); boolean exists = false; br.readLine(); //read the header. while ((line = br.readLine()) != null) { String shortname = line.split(":::")[0]; if (taskShortName.trim().equalsIgnoreCase(shortname.trim())) { // System.out.println("--Exists;"); msg = "exists"; break; } } } //now check the main existing files in VisUnit. String sysTasklistFilename = getServletContext() .getRealPath("quanttasks" + File.separator + "quanttasklist.txt"); File sysTaskListFile = new File(sysTasklistFilename); BufferedReader br2 = new BufferedReader(new FileReader(sysTaskListFile)); line = ""; br2.readLine(); while ((line = br2.readLine()) != null) { //System.out.println("&&&---name is "+taskShortName + " and the line is " + line); String shortname = line.split(":::")[0]; if (taskShortName.trim().equalsIgnoreCase(shortname.trim())) { // System.out.println("*** Exists"); msg = "exists"; break; } } br2.close(); } out.write(msg); } else if (command.equalsIgnoreCase("saveNewTask")) { //First Get the parameters of the tasks String taskQuestion = request.getParameter("taskQuestion").toString(); String taskDescription = request.getParameter("taskDescription").toString(); String taskShortName = request.getParameter("taskShortName").toString(); String answerType = request.getParameter("answerType").toString(); //String inputInterface = request.getParameter("inputInterface").toString(); String outputType = request.getParameter("outputType").toString(); String outputTypeDescription = request.getParameter("outputTypeDescription").toString(); String numberOfInputs = request.getParameter("numberOfInputs").toString(); String answerOptions = request.getParameter("answerOptions").toString(); String inputTypeShortNames = request.getParameter("inputTypeShortNames").toString(); String inputTypeDescriptions = request.getParameter("inputTypeDescriptions").toString(); String inputMediums = request.getParameter("inputMediums").toString(); String userid = request.getParameter("userid").toString(); String accuracyCheckingInterface = request.getParameter("accuracyCheckingInterface"); //String questionInputInfos = request.getParameter("questionInputs").toString(); String inputTypeShortNamesArr[] = inputTypeShortNames.split(":::"); String inputTypeDescriptionsArr[] = inputTypeDescriptions.split(":::"); String inputMediumsArr[] = inputMediums.split(":::"); String hasCorrectAnswer = request.getParameter("hasCorrectAnswer").toString(); //String questionInputInfosArr[] = questionInputInfos.split(":::"); //conjugate the answertype if (answerType.equalsIgnoreCase("interface")) { answerType = "interface"; } else { if (answerType.equalsIgnoreCase("options-fixed")) { answerType = answerType + ":::" + answerOptions; } else { answerType = answerType; } } //if the //if user is admin or any of our admin id's we will save the task in the main task //directory otherwise we will save it in the respective user directory. if (!userid.equalsIgnoreCase("admin")) { //write the xml file in that respective user directory. File userdir = new File(getServletContext().getRealPath("users" + File.separator + userid)); File quantTaskDir = new File(getServletContext() .getRealPath("users" + File.separator + userid + File.separator + "quanttasks")); //check if the user directory exists. //if it does not exist, create it and create the other respective directories, //even if it exists, check if the other respective directories exist and create them too. if (userdir.exists()) { //System.out.println("The directory exists"); //check if the quanttasks directory exists, if it does not exist, create it. if (!quantTaskDir.exists()) { //create the quanttasks sub directory quantTaskDir.mkdir(); } } else { //create the user directory and create the quanttask subdirectory. userdir.mkdir(); quantTaskDir.mkdir(); } File userQuantTaskFile = new File(getServletContext().getRealPath("users" + File.separator + userid + File.separator + "quanttasks" + File.separator + taskShortName + ".xml")); BufferedWriter bw1 = new BufferedWriter(new FileWriter(userQuantTaskFile)); PrintWriter pw1 = new PrintWriter(bw1); pw1.println("<?xml version=\"1.0\"?>"); //first line of the xml pw1.println("<task_details>"); pw1.println("\t<taskname>" + taskShortName + "</taskname>"); pw1.println("\t<accuracyCheckingInterface>" + accuracyCheckingInterface + "</accuracyCheckingInterface>"); pw1.println("\t<outputtype>" + outputType + "</outputtype>"); pw1.println("\t<outputTypeDescription>" + outputTypeDescription + "</outputTypeDescription>"); pw1.println("\t<answertype>" + answerType + "</answertype>"); pw1.println("\t<taskquestion>" + taskQuestion + "</taskquestion>"); pw1.println("\t<taskDescription>" + taskDescription + "</taskDescription>"); pw1.println("\t<inputsize>" + numberOfInputs + "</inputsize>"); pw1.println("<hasCorrectAnswer>" + hasCorrectAnswer + "</hasCorrectAnswer>"); //create the input elements for (int i = 0; i < Integer.parseInt(numberOfInputs); i++) { pw1.println("\t<input>"); //beginning of the input tag //System.out.println(questionInputInfosArr[i]); pw1.println("\t\t<inputtype>" + inputTypeShortNamesArr[i] + "</inputtype>"); pw1.println("\t\t<inputdescription>" + inputTypeDescriptionsArr[i] + "</inputdescription>"); pw1.println("\t\t<inputmedium>" + inputMediumsArr[i] + "</inputmedium>"); /* pw1.println("\t\t<partofaquestion>" + questionInputInfosArr[i] + "</partofaquestion>"); */ pw1.println("\t</input>"); //end of the input tag } pw1.println("</task_details>"); pw1.close(); bw1.close(); //also append the short name to the end of the task list file File taskListFile = new File(getServletContext().getRealPath("users" + File.separator + userid + File.separator + "quanttasks" + File.separator + "quanttasklist.txt")); boolean newFile = false; if (!taskListFile.exists()) { taskListFile.createNewFile(); //write the header too. newFile = true; } FileWriter fw = new FileWriter(taskListFile, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); if (newFile) { pw.println("shortname ::: taskquestion ::: taskgroup"); } pw.println(taskShortName + " ::: " + taskQuestion + " ::: " + " noGroup"); //noGroup now, but later we can let the user specify their own goup. //close the streams. pw.close(); fw.close(); bw.close(); } else { //Write an xml file with it. String quanTaskFileName = getServletContext() .getRealPath("quanttasks" + File.separator + "quanttasks.xml"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(quanTaskFileName); //Get the root element Node root = doc.getFirstChild(); //create the task element Element taskElem = doc.createElement("task"); //create the elements that will be below the task element Element tasknameElem = doc.createElement("taskname"); //Element inpInterfaceElem = doc.createElement("inputinterface"); Element outInterfaceElem = doc.createElement("outputtype"); Element outputTypeDescripElem = doc.createElement("outputTypeDescription"); Element answertypeElem = doc.createElement("answertype"); Element taskquestionElem = doc.createElement("taskquestion"); Element taskDescriptionElem = doc.createElement("taskDescription"); Element inputsizeElem = doc.createElement("inputsize"); tasknameElem.appendChild(doc.createTextNode(taskShortName)); taskquestionElem.appendChild(doc.createTextNode(taskQuestion)); taskDescriptionElem.appendChild(doc.createTextNode(taskDescription)); answertypeElem.appendChild(doc.createTextNode(answerType)); // inpInterfaceElem.appendChild(doc.createTextNode(inputInterface)); outInterfaceElem.appendChild(doc.createTextNode(outputType)); outputTypeDescripElem.appendChild(doc.createTextNode(outputTypeDescription)); inputsizeElem.appendChild(doc.createTextNode(numberOfInputs)); //append the elements to the task element taskElem.appendChild(tasknameElem); //taskElem.appendChild(inpInterfaceElem); taskElem.appendChild(outInterfaceElem); taskElem.appendChild(outputTypeDescripElem); taskElem.appendChild(answertypeElem); taskElem.appendChild(taskquestionElem); taskElem.appendChild(taskDescriptionElem); taskElem.appendChild(inputsizeElem); //create the input elements for (int i = 0; i < Integer.parseInt(numberOfInputs); i++) { Element inputElem = doc.createElement("input"); Element inputShortNameElem = doc.createElement("inputtype"); inputShortNameElem.appendChild(doc.createTextNode(inputTypeShortNamesArr[i])); Element inputDescriptionElem = doc.createElement("inputdescription"); inputDescriptionElem.appendChild(doc.createTextNode(inputTypeDescriptionsArr[i])); inputElem.appendChild(inputShortNameElem); inputElem.appendChild(inputDescriptionElem); //append the input Elem to the task Elem. taskElem.appendChild(inputElem); } //append the task node to the root node. root.appendChild(taskElem); //write it to file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(quanTaskFileName)); transformer.transform(source, result); } } else if (command.equalsIgnoreCase("uploadNewTaskXMLFile")) { String userid = request.getParameter("userid").toString(); String taskShortname = request.getParameter("taskShortName").toString(); String taskDirUrl = "users" + File.separator + userid + File.separator + "quanttasks"; if (ServletFileUpload.isMultipartContent(request)) { // System.out.println("here now"); try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); //get the name for the dataset without the file extensions String taskName = taskShortname + ".xml"; // System.out.println("dataset name is " + dsName); String taskDirPath = getServletContext() .getRealPath(taskDirUrl + File.separator + taskName); //File taskDir = new File(taskDirPath); // System.out.println(taskDirPath); //now write the dataset in that directory item.write(new File(taskDirPath)); System.out.println("here"); //now read the file to get the task question File fXmlFile = new File(taskDirPath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); // System.out.println("here2"); boolean validFile = true; //System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); String taskQn = ""; NodeList taskNode = doc.getElementsByTagName("task_details"); if (taskNode != null) { System.out.println("here3"); Node nNode = taskNode.item(0); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; taskQn = eElement.getElementsByTagName("taskquestion").item(0) .getTextContent(); } else { validFile = false; } } else { validFile = false; } if (validFile) { //now write this to the quantlist //also append the short name to the end of the task list file File taskListFile = new File(getServletContext() .getRealPath("users" + File.separator + userid + File.separator + "quanttasks" + File.separator + "quanttasklist.txt")); boolean newFile = false; if (!taskListFile.exists()) { taskListFile.createNewFile(); //write the header too. newFile = true; } FileWriter fw = new FileWriter(taskListFile, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); if (newFile) { pw.println("shortname ::: taskquestion ::: taskgroup"); } pw.println(taskShortname + " ::: " + taskQn + " ::: " + " noGroup"); //noGroup now, but later we can let the user specify their own goup. //System.out.println("finish printing"); //close the streams. pw.close(); fw.close(); bw.close(); out.print("successful"); } else { out.print("failed"); } } } } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } } else if (command.equalsIgnoreCase("uploadNewTaskInstancesXMLFile")) { String userid = request.getParameter("userid").toString(); String task = request.getParameter("task").toString(); String viewer = request.getParameter("viewer").toString(); String dataset = request.getParameter("dataset").toString(); // if(viewer.trim()===) String name = dataset.trim(); if (name.isEmpty()) { name = viewer.trim(); } //We will be adding this to the task instances rather. String taskInstanceDirUrl = "users" + File.separator + userid + File.separator + "taskInstances" + File.separator + name; //create the directory that the task instance will be saved in if File taskInstanceDir = new File(getServletContext().getRealPath(taskInstanceDirUrl)); if (!taskInstanceDir.exists()) { taskInstanceDir.mkdir(); } //get the taskShort name too. String taskName = getTaskCode(task, userid); if (ServletFileUpload.isMultipartContent(request)) { // System.out.println("here now"); try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { //String name = new File(item.getName()).getName(); //get the name for the dataset without the file extensions taskName = taskName + ".xml"; // System.out.println("dataset name is " + dsName); String taskInstanceFilePath = getServletContext() .getRealPath(taskInstanceDirUrl + File.separator + taskName); //now write the dataset in that directory item.write(new File(taskInstanceFilePath)); //now read the file to get the task question File fXmlFile = new File(taskInstanceFilePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); // System.out.println("here2"); boolean validFile = true; //System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); String taskQn = ""; NodeList taskNode = doc.getElementsByTagName("taskFile"); if (taskNode != null) { // System.out.println("here3"); Node nNode = taskNode.item(0); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; taskQn = eElement.getElementsByTagName("question").item(0).getTextContent(); } else { validFile = false; } } else { validFile = false; } //System.out.println(taskInstanceFilePath + " :: "); if (validFile) { out.print("successful"); } else { out.print("failed"); } } } } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:wssec.TestWSSecurityWSS234.java
/** * Test that signs and verifies a WS-Security envelope * <p/>// www . j ava 2 s.c o m * * @throws java.lang.Exception Thrown when there is any problem in signing or verification */ public void testSignature() throws Exception { WSSecSignature builder = new WSSecSignature(); builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security"); LOG.info("Before Signing...."); Document doc = unsignedEnvelope.getAsDocument(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document signedDoc = builder.build(doc, crypto, secHeader); // Add a comment node as the first node element org.w3c.dom.Node firstChild = signedDoc.getFirstChild(); org.w3c.dom.Node newNode = signedDoc.removeChild(firstChild); org.w3c.dom.Node commentNode = signedDoc.createComment("This is a comment"); signedDoc.appendChild(commentNode); signedDoc.appendChild(newNode); if (LOG.isDebugEnabled()) { LOG.debug("After Signing...."); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } verify(signedDoc); }
From source file:xmlconverter.controller.logic.GetFileCount.java
/** * This method is/are going to update the site information. The statements * are based on flags that are passed. This method should detect if files * content has changed and also update thous changed if node count has * changed./* ww w.java2 s .c o m*/ * * @param path * @param pathXml * @throws DOMException * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws TransformerException */ private void updateSite(Document newDoc, File pathXml) throws TransformerException, DOMException, ParserConfigurationException, IOException, SAXException { //System.out.println("I updated: " + pathXml.getName()); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document oldDoc = docBuilder.parse(pathXml); //Old root & NodeList Node root = oldDoc.getFirstChild(); NodeList staff = root.getChildNodes(); ArrayList<Node> oldNodes = new ArrayList<>(); for (int i = 0; i < staff.getLength(); i++) { oldNodes.add(staff.item(i)); } //New root & NodeList Node rootNew = newDoc.getFirstChild(); NodeList staffNew = rootNew.getChildNodes(); ArrayList<Node> newNodes = new ArrayList<>(); for (int i = 0; i < staffNew.getLength(); i++) { newNodes.add(staffNew.item(i)); } // * All extra nodes will be removed // * All not maching "id's" will be replaced if (oldNodes.size() > newNodes.size()) { for (int i = 0; i < oldNodes.size(); i++) { if (i >= newNodes.size()) { root.removeChild(oldNodes.get(i));//remove extra old nodes } else if (!oldNodes.get(i).getAttributes().getNamedItem("id").getNodeValue() .equals(newNodes.get(i).getAttributes().getNamedItem("id").getNodeValue())) { root.replaceChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true)), oldNodes.get(i)); //replace new node with old node } else { //System.out.println(i + "equal"); } } // * All not maching "id's" will be replaced } else if (oldNodes.size() == newNodes.size()) { for (int i = 0; i < oldNodes.size(); i++) { if (!oldNodes.get(i).getAttributes().getNamedItem("id").getNodeValue() .equals(newNodes.get(i).getAttributes().getNamedItem("id").getNodeValue())) { root.replaceChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true)), oldNodes.get(i));// replace old with new node } else { //System.out.println(i + " equal"); } } // * All extra nodes will be apended // * All not maching "id's" will be replaced } else if (oldNodes.size() < newNodes.size()) { for (int i = 0; i < newNodes.size(); ++i) { if (i >= oldNodes.size()) { root.appendChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true))); //append extra new node } else if (!newNodes.get(i).getAttributes().getNamedItem("id").getNodeValue() .equals(oldNodes.get(i).getAttributes().getNamedItem("id").getNodeValue())) { root.replaceChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true)), oldNodes.get(i));//replace old with new node } else { //System.out.println(i + "equal"); } } } writeDocument(oldDoc, pathXml); }
From source file:xmlconverter.controller.logic.GetFileCount.java
/** * This method is going to update file called "Anlagenbaum.xml" The updates * that are done to this file are essential when adding new site witch is * done automatically. It needs to be done for GMA-manager software to * detect changes/ that folder/site has been added. * * @throws javax.xml.parsers.ParserConfigurationException * @throws org.xml.sax.SAXException//w w w . j a v a2 s .co m * @throws javax.xml.transform.TransformerException * @throws java.io.IOException */ public void updateAnlage() throws DOMException, ParserConfigurationException, TransformerException, IOException, SAXException { File anlageFile = new File(home.getAbsolutePath() + slash + "Anlagenbaum.xml"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(anlageFile); // Get the root element Node root = doc.getFirstChild(); NodeList staff = doc.getElementsByTagName("GraphicsContainerNode"); ArrayList<String> staffList = new ArrayList<>(); for (int i = 0; i < staff.getLength(); i++) { NamedNodeMap attr = staff.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("id"); String content = nodeAttr.getTextContent(); staffList.add(content); } File[] siteName = home.listFiles(directoryFilter); ArrayList<String> siteNameList = new ArrayList<>(); for (File f : siteName) { siteNameList.add(f.getName()); } Collection site = siteNameList; Collection staffCollection = staffList; if (staff.getLength() == 0) { for (String s : siteNameList) { Element graphicsNode = doc.createElement("GraphicsContainerNode"); graphicsNode.setAttribute("id", s); graphicsNode.setAttribute("load", s + slash + s); graphicsNode.setAttribute("name", s); root.appendChild(graphicsNode); } } else if (staff.getLength() <= siteName.length || staff.getLength() > 0) { site.removeAll(staffCollection); for (Object s : site) { Element graphicsNode = doc.createElement("GraphicsContainerNode"); graphicsNode.setAttribute("id", s.toString()); graphicsNode.setAttribute("load", s.toString() + slash + s.toString()); graphicsNode.setAttribute("name", s.toString()); root.appendChild(graphicsNode); } } writeDocument(doc, anlageFile); log.info("updating site tree successful!"); }
From source file:xsul.dsig.globus.security.authentication.wssec.WSSecurityUtil.java
/** * Returns the first WS-Security header element for a given actor * Only one WS-Security header is allowed for an actor. *///from www. j a va2s. com public static Element getSecurityHeader(Document doc, String actor) { Element soapHeaderElement = (Element) getDirectChild(doc.getFirstChild(), XmlConstants.S_HEADER, WSConstants.SOAP_NS); // TODO: this can also be slightly optimized NodeList list = soapHeaderElement.getElementsByTagNameNS(WSConstants.WSSE_NS, WSConstants.WS_SEC_LN); int len = list.getLength(); Element elem; Attr attr; String hActor; for (int i = 0; i < len; i++) { elem = (Element) list.item(i); attr = elem.getAttributeNodeNS(WSConstants.SOAP_NS, "actor"); hActor = (attr != null) ? attr.getValue() : null; if ((((hActor == null) || (hActor.length() == 0)) && ((actor == null) || (actor.length() == 0))) || ((hActor != null) && (actor != null) && hActor.equalsIgnoreCase(actor))) { return elem; } } return null; }
From source file:xsul.dsig.globus.security.authentication.wssec.WSSecurityUtil.java
public static Element findFirstBodyElement(Document doc) { Element soapBodyElement = (Element) WSSecurityUtil.getDirectChild(doc.getFirstChild(), "Body", WSConstants.SOAP_NS);/*from w w w . ja v a 2 s . c om*/ if (soapBodyElement == null) { soapBodyElement = (Element) WSSecurityUtil.getDirectChild(doc.getFirstChild(), "Body", WSConstants.SOAP12_NS); } if (soapBodyElement == null) logger.finest("yes soapBodyElement is null"); for (Node currentChild = soapBodyElement.getFirstChild(); currentChild != null; currentChild = currentChild .getNextSibling()) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { return (Element) currentChild; } } return null; }