private NodeList getValueNodes(Node operation) { List<Node> valueNL = getChildNodes(operation, "value"); if (valueNL.isEmpty()) { return null; } return valueNL.get(0).getChildNodes(); }
private List<Node> getChildNodes(Node parentNode, String tagName) { List<Node> nodeList = new ArrayList<Node>(); for (Node child = parentNode.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() == Node.ELEMENT_NODE && tagName.equals(child.getNodeName())) { nodeList.add(child); } } return nodeList; }
private boolean handleFault(int i) { Handler handler = _chain.get(i); boolean success = false; _invoked[i] = true; try { if (handler instanceof LogicalHandler) { _logicalContext.getMessage().setPayload(_source); success = handler.handleFault(_logicalContext); _source = _logicalContext.getMessage().getPayload(); } else if (handler instanceof SOAPHandler) { try { _soapContext.setMessage(_source); success = handler.handleFault(_soapContext); _source = _soapContext.getMessage().getSOAPPart().getContent(); } catch (SOAPException e) { throw new WebServiceException(e); } } else { throw new WebServiceException( L.l("Unsupported Handler type: {0}", handler.getClass().getName())); } _protocolException = null; } catch (ProtocolException e) { _protocolException = e; serializeProtocolException(); } catch (RuntimeException e) { _runtimeException = e; serializeRuntimeException(); } return success; }
public boolean invokeInboundFaultHandlers() { for (_i++; _i < _chain.size(); _i++) { if (!handleFault(_i)) return false; if (_runtimeException != null) return false; } return true; }
public InputStream invokeServerInbound(HttpServletRequest request, OutputStream os) throws IOException { Map<String, DataHandler> attachments = new HashMap<String, DataHandler>(); Map<String, Object> httpProperties = new HashMap<String, Object>(); httpProperties.put(HTTP_REQUEST_METHOD, request.getMethod()); Map<String, List<String>> headers = new HashMap<String, List<String>>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); List<String> values = new ArrayList<String>(); Enumeration headerValues = request.getHeaders(name); while (headerValues.hasMoreElements()) { String value = (String) headerValues.nextElement(); values.add(value); } headers.put(name, values); } httpProperties.put(HTTP_REQUEST_HEADERS, headers); prepare(httpProperties, /*request=*/ true); if (!invokeInbound(request.getInputStream(), attachments)) { if (getProtocolException() != null) { reverseDirection(); invokeInboundFaultHandlers(); } else if (getRuntimeException() == null) uninvokeInbound(); closeServer(); finish(os); return null; } return finish(); }
private NodeList findNodes(Document doc, Node operation) { List<Node> xpaths = getChildNodes(operation, "xpath"); if (xpaths.isEmpty()) { return null; } String xpathExpression = xpaths.get(0).getTextContent(); if (xpathExpression == null) { return null; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nl = null; try { XPathExpression expr = xpath.compile(xpathExpression); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) { Utils.onError(new Error.WrongXpathExpression(xpathExpression)); } return nl; }
private void processApply(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> scripts = getChildNodes(operation, "script"); for (int t = 0; t < targets.size(); t++) { String path = absolutePath(targets.get(t).getTextContent()); NodeList[] operations = new NodeList[scripts.size()]; for (int s = 0; s < scripts.size(); s++) { operations[s] = scripts.get(s).getChildNodes(); } apply(path, operations); } }
/** * When a message direction is reversed within the chain, this method runs the message backwards * through the previous handlers. This method should only be invoked when a handler returns false, * but does not throw any kind of exception. */ public boolean uninvokeInbound() throws WebServiceException { // Set the mandatory properties _logicalContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE); _soapContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE); for (_i++; _i < _chain.size(); _i++) { boolean success = handleMessage(_i); if (_protocolException != null) return false; if (_runtimeException != null) return false; if (!success) return false; } return true; }
private void close(int i) { Handler handler = _chain.get(i); if (!_invoked[i]) return; _invoked[i] = false; if (handler instanceof LogicalHandler) { _logicalContext.getMessage().setPayload(_source); handler.close(_logicalContext); _source = _logicalContext.getMessage().getPayload(); } else if (handler instanceof SOAPHandler) { try { _soapContext.setMessage(_source); handler.close(_soapContext); _source = _soapContext.getMessage().getSOAPPart().getContent(); } catch (SOAPException e) { throw new WebServiceException(e); } } }
/** Invoke the handler chain for an outbound message. */ public boolean invokeOutbound(Source source, Map<String, DataHandler> attachments) throws WebServiceException { _source = source; // Set the mandatory properties _logicalContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE); _soapContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE); _logicalContext.put(OUTBOUND_MESSAGE_ATTACHMENTS, attachments); _soapContext.put(OUTBOUND_MESSAGE_ATTACHMENTS, attachments); for (_i = 0; _i < _chain.size(); _i++) { boolean success = handleMessage(_i); if (_protocolException != null) return false; if (_runtimeException != null) return false; if (!success) return false; } return true; }
/** Invoke the handler chain for an inbound message. */ public boolean invokeInbound(InputStream in, Map<String, DataHandler> attachments) throws WebServiceException { _outbound = false; _source = null; try { DOMResult dom = new DOMResult(); getTransformer().transform(new StreamSource(in), dom); // XXX The TCK seems to assume a source that will stand up to repeated // reads... meaning that StreamSource and SAXSource are out, so DOM // must be what they want. _source = new DOMSource(dom.getNode()); } catch (Exception e) { throw new WebServiceException(e); } // Set the mandatory properties _logicalContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.FALSE); _soapContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.FALSE); _logicalContext.put(INBOUND_MESSAGE_ATTACHMENTS, attachments); _soapContext.put(INBOUND_MESSAGE_ATTACHMENTS, attachments); // NOTE: the order is reversed for inbound messages for (_i = _chain.size() - 1; _i >= 0; _i--) { boolean success = handleMessage(_i); if (_protocolException != null) return false; if (_runtimeException != null) return false; if (!success) return false; } return true; }
private void processCopy(Node operation) { List<Node> fromNode = getChildNodes(operation, "from"); List<Node> toNode = getChildNodes(operation, "to"); if (fromNode.isEmpty() || toNode.isEmpty()) { return; } String path = fromNode.get(0).getTextContent(); String fromPath = (new File(path).isAbsolute()) ? path : absolutePath(path); String toPath = absolutePath(toNode.get(0).getTextContent()); Boolean copyContents = fromPath.endsWith(File.separator + "*"); File from = new File((copyContents) ? fromPath.substring(0, fromPath.length() - 2) : fromPath); File to = new File(toPath); if (!from.exists()) { Utils.onError(new Error.FileNotFound(from.getPath())); return; } try { if (copyContents) { FileUtils.forceMkdir(to); FileUtils.copyDirectory(from, to); } else if (from.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyDirectoryToDirectory(from, to); } else { if (to.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyFileToDirectory(from, to); } else { File toDir = new File(Utils.getParentDir(to)); FileUtils.forceMkdir(toDir); FileUtils.copyFile(from, to); } } } catch (IOException ex) { Utils.onError(new Error.FileCopy(from.getPath(), to.getPath())); } }
public void closeClient() { for (int i = _chain.size() - 1; i >= 0; i--) close(i); }
private void processXml(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> appendOpNodes = getChildNodes(operation, "append"); List<Node> setOpNodes = getChildNodes(operation, "set"); List<Node> replaceOpNodes = getChildNodes(operation, "replace"); List<Node> removeOpNodes = getChildNodes(operation, "remove"); if (targets.isEmpty()) { return; } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; try { doc = db.parse(target); } catch (Exception ex) { Utils.onError(new Error.FileParse(target.getPath())); return; } for (int i = 0; i < removeOpNodes.size(); i++) removeXmlEntry(doc, removeOpNodes.get(i)); for (int i = 0; i < replaceOpNodes.size(); i++) replaceXmlEntry(doc, replaceOpNodes.get(i)); for (int i = 0; i < setOpNodes.size(); i++) setXmlEntry(doc, setOpNodes.get(i)); for (int i = 0; i < appendOpNodes.size(); i++) appendXmlEntry(doc, appendOpNodes.get(i)); try { OutputFormat format = new OutputFormat(doc); format.setOmitXMLDeclaration(true); format.setLineWidth(65); format.setIndenting(true); format.setIndent(4); Writer out = new FileWriter(target); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } catch (IOException e) { Utils.onError(new Error.WriteXmlConfig(target.getPath())); } } }
private void processTxt(Node operation) { List<Node> targets = getChildNodes(operation, "target"); List<Node> optionNodes = getChildNodes(operation, "opt"); List<Node> separatorNode = getChildNodes(operation, "separator"); if (targets.isEmpty() || optionNodes.isEmpty()) { return; } String defaultSeparator = "="; String globalSeparator = defaultSeparator; if (!separatorNode.isEmpty()) { globalSeparator = separatorNode.get(0).getTextContent(); if (globalSeparator.length() != 1) { globalSeparator = defaultSeparator; } } Map<String, String> options = new HashMap<String, String>(); Map<String, String> processedOptions = new HashMap<String, String>(); for (int i = 0; i < optionNodes.size(); i++) { Node option = optionNodes.get(i); String name = option.getAttributes().getNamedItem("name").getNodeValue(); String value = option.getTextContent(); if (options.containsKey(name)) { options.remove(name); } options.put(name, value); } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); File tmpFile = new File(Utils.timestamp()); BufferedWriter bw = null; BufferedReader br = null; try { Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator"); String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue(); if (separator.length() != 1) { separator = globalSeparator; } bw = new BufferedWriter(new FileWriter(tmpFile)); if (target.exists()) { br = new BufferedReader(new FileReader(target)); for (String line; (line = br.readLine()) != null; ) { String[] parts = line.split(separator); if (parts.length < 2) { bw.write(line); bw.newLine(); continue; } String optName = parts[0].trim(); if (options.containsKey(optName)) { String optValue = options.get(optName); bw.write(optName + " " + separator + " " + optValue); bw.newLine(); processedOptions.put(optName, optValue); options.remove(optName); } else if (processedOptions.containsKey(optName)) { bw.write(optName + " " + separator + " " + processedOptions.get(optName)); bw.newLine(); } else { bw.write(line); bw.newLine(); } } br.close(); } for (Map.Entry<String, String> entry : options.entrySet()) { bw.write(entry.getKey() + " " + separator + " " + entry.getValue()); bw.newLine(); } bw.close(); FileUtils.copyFile(tmpFile, target); FileUtils.forceDelete(tmpFile); } catch (IOException ex) { Utils.onError(new Error.WriteTxtConfig(target.getPath())); } } }
public void closeServer() { for (int i = 0; i < _chain.size(); i++) close(i); }
public HandlerChainInvoker(List<Handler> chain, BindingProvider bindingProvider) { _chain = JAXWSUtil.sortHandlerChain(chain); _invoked = new boolean[_chain.size()]; _bindingProvider = bindingProvider; }
/** * Unmarshall a Chromosome instance from a given XML Element representation. * * @param a_activeConfiguration current Configuration object * @param a_xmlElement the XML Element representation of the Chromosome * @return a new Chromosome instance setup with the data from the XML Element representation * @throws ImproperXMLException if the given Element is improperly structured or missing data * @throws UnsupportedRepresentationException if the actively configured Gene implementation does * not support the string representation of the alleles used in the given XML document * @throws GeneCreationException if there is a problem creating or populating a Gene instance * @author Neil Rotstan * @since 1.0 */ public static Gene[] getGenesFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException { // Do some sanity checking. Make sure the XML Element isn't null and // that it in fact represents a set of genes. // ----------------------------------------------------------------- if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "given Element is not a 'genes' element."); } List genes = Collections.synchronizedList(new ArrayList()); // Extract the nested gene elements. // --------------------------------- NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG); if (geneElements == null) { throw new ImproperXMLException( "Unable to build Gene instances from XML Element: " + "'" + GENE_TAG + "'" + " sub-elements not found."); } // For each gene, get the class attribute so we know what class // to instantiate to represent the gene instance, and then find // the child text node, which is where the string representation // of the allele is located, and extract the representation. // ------------------------------------------------------------- int numberOfGeneNodes = geneElements.getLength(); for (int i = 0; i < numberOfGeneNodes; i++) { Element thisGeneElement = (Element) geneElements.item(i); thisGeneElement.normalize(); // Fetch the class attribute and create an instance of that // class to represent the current gene. // -------------------------------------------------------- String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE); Gene thisGeneObject; Class geneClass = null; try { geneClass = Class.forName(geneClassName); try { Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class}); thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration}); } catch (NoSuchMethodException nsme) { // Try it by calling method newGeneInternal. // ----------------------------------------- Constructor constr = geneClass.getConstructor(new Class[] {}); thisGeneObject = (Gene) constr.newInstance(new Object[] {}); thisGeneObject = (Gene) PrivateAccessor.invoke( thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {}); } } catch (Throwable e) { throw new GeneCreationException(geneClass, e); } // Find the text node and fetch the string representation of // the allele. // --------------------------------------------------------- NodeList children = thisGeneElement.getChildNodes(); int childrenSize = children.getLength(); String alleleRepresentation = null; for (int j = 0; j < childrenSize; j++) { Element alleleElem = (Element) children.item(j); if (alleleElem.getTagName().equals(ALLELE_TAG)) { alleleRepresentation = alleleElem.getAttribute("value"); } if (children.item(j).getNodeType() == Node.TEXT_NODE) { // We found the text node. Extract the representation. // --------------------------------------------------- alleleRepresentation = children.item(j).getNodeValue(); break; } } // Sanity check: Make sure the representation isn't null. // ------------------------------------------------------ if (alleleRepresentation == null) { throw new ImproperXMLException( "Unable to build Gene instance from XML Element: " + "value (allele) is missing representation."); } // Now set the value of the gene to that reflect the // string representation. // ------------------------------------------------- try { thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation); } catch (UnsupportedOperationException e) { throw new GeneCreationException( "Unable to build Gene because it does not support the " + "setValueFromPersistentRepresentation() method."); } // Finally, add the current gene object to the list of genes. // ---------------------------------------------------------- genes.add(thisGeneObject); } return (Gene[]) genes.toArray(new Gene[genes.size()]); }