List of usage examples for org.w3c.dom Element getNodeName
public String getNodeName();
From source file:io.personium.core.bar.BarFileReadRunner.java
/** * 90_rootprops.xml??response???????//from ww w .j a v a2 s. c om * @param rootPropsName ?????() * @param response ??responseJAXB * @return ????? * WebDAV?Service?WebDAV???? * ?????????????????? */ private int getCollectionType(String rootPropsName, Response response) { // <propstat>??????????? // ?prop/resourcetype/collecton ?DOM???????? // ???"p:odata" ??? "p:service" ?DOM??????WebDAV???? // - ????????WebDAv??????? for (Propstat propstat : response.getPropstat()) { Prop prop = propstat.getProp(); Resourcetype resourceType = prop.getResourcetype(); if (resourceType != null && resourceType.getCollection() != null) { List<Element> elements = resourceType.getAny(); for (Element element : elements) { String nodeName = element.getNodeName(); if (nodeName.equals("p:odata")) { return TYPE_ODATA_COLLECTION; } else if (nodeName.equals("p:service")) { return TYPE_SERVICE_COLLECTION; } else { String message = MessageFormat.format(PersoniumCoreMessageUtils.getMessage("PL-BI-2018"), nodeName); writeOutputStream(true, "PL-BI-1004", rootPropsName, message); return TYPE_MISMATCH; } } } else { return TYPE_DAV_FILE; } } return TYPE_WEBDAV_COLLECTION; }
From source file:com.fujitsu.dc.core.bar.BarFileReadRunner.java
/** * 90_rootprops.xml??response???????/*from ww w .j a va2 s . c o m*/ * @param rootPropsName ?????() * @param response ??responseJAXB * @return ????? * WebDAV?Service?WebDAV???? * ?????????????????? */ private int getCollectionType(String rootPropsName, Response response) { // <propstat>??????????? // ?prop/resourcetype/collecton ?DOM???????? // ???"dc:odata" ??? "dc:service" ?DOM??????WebDAV???? // - ????????WebDAv??????? for (Propstat propstat : response.getPropstat()) { Prop prop = propstat.getProp(); Resourcetype resourceType = prop.getResourcetype(); if (resourceType != null && resourceType.getCollection() != null) { List<Element> elements = resourceType.getAny(); for (Element element : elements) { String nodeName = element.getNodeName(); if (nodeName.equals("dc:odata")) { return TYPE_ODATA_COLLECTION; } else if (nodeName.equals("dc:service")) { return TYPE_SERVICE_COLLECTION; } else { String message = MessageFormat.format(DcCoreMessageUtils.getMessage("PL-BI-2018"), nodeName); writeOutputStream(true, "PL-BI-1004", rootPropsName, message); return TYPE_MISMATCH; } } } else { return TYPE_DAV_FILE; } } return TYPE_WEBDAV_COLLECTION; }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * Process the mappings after xsl transformation * /* w w w .jav a 2 s. c o m*/ * @param xrefElement * @return the processed Element */ private Element processMappings(Element xrefElement) throws XtentisException { try { String xrefcluster = xrefElement.getAttribute("xrefCluster"); //$NON-NLS-1$ String xrefIn = xrefElement.getAttribute("xrefIn"); //$NON-NLS-1$ String xrefOut = xrefElement.getAttribute("xrefOut"); //$NON-NLS-1$ String xrefIgnore = xrefElement.getAttribute("xrefIgnore"); //$NON-NLS-1$ String xrefDefault = xrefElement.getAttribute("xrefDefault"); //$NON-NLS-1$ Logger.getLogger(XSLTTransformerPluginBean.class) .debug("\n xrefIgnore=" + xrefIgnore + "\n xrefDefault=" + xrefDefault); //$NON-NLS-1$ //$NON-NLS-2$ // parse xrefbein dockey1:xrefkey1,dockey2:xrefkey2 String[] mappings = xrefIn.split(","); //$NON-NLS-1$ HashMap<String, String> itemvals = new HashMap<String, String>(); for (int j = 0; j < mappings.length; j++) { String[] relations = mappings[j].split("="); //$NON-NLS-1$ String docpath = relations[0]; String xrefpath = relations[1]; String itemval = ""; //$NON-NLS-1$ try { if (docpath.startsWith("[")) // hardcoded value //$NON-NLS-1$ itemval = docpath.substring(1, docpath.length() - 1); else itemval = Util.getFirstTextNode(xrefElement, docpath); } catch (Exception x) { throw new XtentisException( "Value for business element '" + xrefElement.getNodeName() + '/' + docpath //$NON-NLS-1$ + "' cannot be found!"); //$NON-NLS-1$ } if (itemval == null) itemval = ""; //$NON-NLS-1$ String content = stripeOuterBracket(itemval); if (content.split(",").length >= mappings.length) //$NON-NLS-1$ itemvals.put(xrefpath, content.split(",")[j]); //$NON-NLS-1$ else itemvals.put(xrefpath, ""); //$NON-NLS-1$ } WhereAnd wAnd = new WhereAnd(); Collection<Map.Entry<String, String>> c = itemvals.entrySet(); int i = 0; for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) { i++; Map.Entry<String, String> entry = iter.next(); wAnd.add(new WhereCondition(entry.getKey(), WhereCondition.EQUALS, entry.getValue(), WhereCondition.PRE_NONE, false)); } ArrayList<String> resList = Util.getItemCtrl2Local().xPathsSearch(new DataClusterPOJOPK(xrefcluster), null, new ArrayList<String>(Arrays.asList(new String[] { xrefOut })), wAnd, -1, // spell 0, // start 1, // limit false); String val = ""; //$NON-NLS-1$ if ((resList == null) || (resList.size() == 0)) { if (xrefIgnore.equals("true") || xrefIgnore.equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$ if (xrefDefault != null) val = xrefDefault; else val = ""; //$NON-NLS-1$ } else { String ks = ""; //$NON-NLS-1$ c = itemvals.entrySet(); for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) { Map.Entry<String, String> entry = iter.next(); ks += " " + entry.getKey() + "=\"" + entry.getValue() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } throw new XtentisException("Foreign keys values not found for: " + ks); //$NON-NLS-1$ } } else { // read result Pattern p = Pattern.compile("<.*?>(.*?)</.*>", Pattern.DOTALL); //$NON-NLS-1$ Matcher m = p.matcher(resList.iterator().next()); if (m.matches()) val = StringEscapeUtils.unescapeXml(m.group(1)); else { Pattern p2 = Pattern.compile("<.*?/>", Pattern.DOTALL); //$NON-NLS-1$ Matcher m2 = p2.matcher(resList.iterator().next()); if (!m2.matches() && !(xrefIgnore.equals("true") || xrefIgnore.equals("1"))) { //$NON-NLS-1$ //$NON-NLS-2$ throw new XtentisException("Result values were not understood for crossref element"); //$NON-NLS-1$ } } } NodeList l = xrefElement.getChildNodes(); for (int j = 0; j < l.getLength(); j++) { switch (l.item(j).getNodeType()) { case Node.TEXT_NODE: l.item(j).setNodeValue(val); break; case Node.ELEMENT_NODE: xrefElement.removeChild(l.item(j)); break; default: } } xrefElement.removeAttribute("xrefCluster"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefIgnore"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefDefault"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefIn"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefOut"); //$NON-NLS-1$ return xrefElement; } catch (Exception e) { String err = "Unable to process the mappings for the element '" + xrefElement.getLocalName() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ LOG.error(err, e); throw new XtentisException(err); } }
From source file:io.personium.core.bar.BarFileReadRunner.java
/** * 90_rootprops_xml???Collectoin/ACL/WebDAV???. * @param rootPropsName 90_rootprops_xml?bar?? * @param inputStream //from ww w . jav a 2s. c o m * @param boxUrl box?URL * @return ????true */ protected boolean registXmlEntry(String rootPropsName, InputStream inputStream, String boxUrl) { // XML(StAX,SAX,DOM)?InputStream??????????? // ????????????????? try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuffer buf = new StringBuffer(); String str; while ((str = bufferedReader.readLine()) != null) { buf.append(str); } Multistatus multiStatus = Multistatus.unmarshal(new ByteArrayInputStream(buf.toString().getBytes())); // 90_rootprops.xml?????? // ????????????? if (!validateCollectionDefinitions(multiStatus, rootPropsName)) { return false; } for (Response response : multiStatus.getResponse()) { int collectionType = TYPE_WEBDAV_COLLECTION; boolean hasCollection = false; boolean isBox = false; List<String> hrefs = response.getHref(); String href = hrefs.get(0); if (href.equals("dcbox:")) { href = DCBOX; } if (href.equals(DCBOX)) { isBox = true; } String collectionUrl = null; collectionUrl = href.replaceFirst(DCBOX, boxUrl + "/"); List<Element> propElements = new ArrayList<Element>(); Element aclElement = null; String contentType = null; for (Propstat propstat : response.getPropstat()) { Prop prop = propstat.getProp(); Resourcetype resourceType = prop.getResourcetype(); if (resourceType != null) { if (resourceType.getCollection() != null) { hasCollection = true; } List<Element> elements = resourceType.getAny(); for (Element element : elements) { String nodeName = element.getNodeName(); if (nodeName.equals("p:odata")) { collectionType = TYPE_ODATA_COLLECTION; } else if (nodeName.equals("p:service")) { collectionType = TYPE_SERVICE_COLLECTION; } } } // prop?? Getcontenttype getContentType = prop.getGetcontenttype(); if (getContentType != null) { contentType = getContentType.getValue(); } List<Element> pElements = prop.getAny(); for (Element element : pElements) { String nodeName = element.getNodeName(); if (nodeName.equals("creationdate") || nodeName.equals("getlastmodified") || nodeName.equals("resourcetype")) { continue; } if (nodeName.equals("acl")) { if (!BarFileUtils.aclNameSpaceValidate(rootPropsName, element, this.schemaUrl)) { String message = PersoniumCoreMessageUtils.getMessage("PL-BI-2007"); log.info(message + " [" + rootPropsName + "]"); writeOutputStream(true, "PL-BI-1004", rootPropsName, message); return false; } aclElement = element; continue; } propElements.add(element); } } String entryName = CONTENTS_DIR + href.replaceFirst(DCBOX, ""); if (isBox) { // Box???ACL registBoxAclAndProppatch(this.box, aclElement, propElements, collectionUrl); } else if (hasCollection) { if (!entryName.endsWith("/")) { entryName += "/"; } // ????ACL?PROPPATH log.info(entryName); createCollection(collectionUrl, entryName, this.cell, this.box, collectionType, aclElement, propElements); } else { // WebDAV this.davFileMap.put(entryName, contentType); } } } catch (PersoniumCoreException e) { log.info("PersoniumCoreException: " + e.getMessage()); writeOutputStream(true, "PL-BI-1004", rootPropsName, e.getMessage()); return false; } catch (Exception ex) { String message = getErrorMessage(ex); log.info("XMLParseException: " + message, ex.fillInStackTrace()); writeOutputStream(true, "PL-BI-1004", rootPropsName, message); return false; } return true; }
From source file:com.fujitsu.dc.core.bar.BarFileReadRunner.java
/** * 90_rootprops_xml???Collectoin/ACL/WebDAV???. * @param rootPropsName 90_rootprops_xml?bar?? * @param inputStream /* w w w . j a v a2 s . c o m*/ * @param boxUrl box?URL * @return ????true */ protected boolean registXmlEntry(String rootPropsName, InputStream inputStream, String boxUrl) { // XML(StAX,SAX,DOM)?InputStream??????????? // ????????????????? try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuffer buf = new StringBuffer(); String str; while ((str = bufferedReader.readLine()) != null) { buf.append(str); } Multistatus multiStatus = Multistatus.unmarshal(new ByteArrayInputStream(buf.toString().getBytes())); // 90_rootprops.xml?????? // ????????????? if (!validateCollectionDefinitions(multiStatus, rootPropsName)) { return false; } for (Response response : multiStatus.getResponse()) { int collectionType = TYPE_WEBDAV_COLLECTION; boolean hasCollection = false; boolean isBox = false; List<String> hrefs = response.getHref(); String href = hrefs.get(0); if (href.equals("dcbox:")) { href = DCBOX; } if (href.equals(DCBOX)) { isBox = true; } String collectionUrl = null; collectionUrl = href.replaceFirst(DCBOX, boxUrl + "/"); List<Element> propElements = new ArrayList<Element>(); Element aclElement = null; String contentType = null; for (Propstat propstat : response.getPropstat()) { Prop prop = propstat.getProp(); Resourcetype resourceType = prop.getResourcetype(); if (resourceType != null) { if (resourceType.getCollection() != null) { hasCollection = true; } List<Element> elements = resourceType.getAny(); for (Element element : elements) { String nodeName = element.getNodeName(); if (nodeName.equals("dc:odata")) { collectionType = TYPE_ODATA_COLLECTION; } else if (nodeName.equals("dc:service")) { collectionType = TYPE_SERVICE_COLLECTION; } } } // prop?? Getcontenttype getContentType = prop.getGetcontenttype(); if (getContentType != null) { contentType = getContentType.getValue(); } List<Element> pElements = prop.getAny(); for (Element element : pElements) { String nodeName = element.getNodeName(); if (nodeName.equals("creationdate") || nodeName.equals("getlastmodified") || nodeName.equals("resourcetype")) { continue; } if (nodeName.equals("acl")) { if (!BarFileUtils.aclNameSpaceValidate(rootPropsName, element, this.schemaUrl)) { String message = DcCoreMessageUtils.getMessage("PL-BI-2007"); log.info(message + " [" + rootPropsName + "]"); writeOutputStream(true, "PL-BI-1004", rootPropsName, message); return false; } aclElement = element; continue; } propElements.add(element); } } String entryName = CONTENTS_DIR + href.replaceFirst(DCBOX, ""); if (isBox) { // Box???ACL registBoxAclAndProppatch(this.box, aclElement, propElements, collectionUrl); } else if (hasCollection) { if (!entryName.endsWith("/")) { entryName += "/"; } // ????ACL?PROPPATH log.info(entryName); createCollection(collectionUrl, entryName, this.cell, this.box, collectionType, aclElement, propElements); } else { // WebDAV this.davFileMap.put(entryName, contentType); } } } catch (DcCoreException e) { log.info("DcCoreException: " + e.getMessage()); writeOutputStream(true, "PL-BI-1004", rootPropsName, e.getMessage()); return false; } catch (Exception ex) { String message = getErrorMessage(ex); log.info("XMLParseException: " + message, ex.fillInStackTrace()); writeOutputStream(true, "PL-BI-1004", rootPropsName, message); return false; } return true; }
From source file:loci.formats.in.LIFReader.java
private void translateMetadata(Element root) throws FormatException { Element realRoot = (Element) root.getChildNodes().item(0); NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master"); if (toPrune != null) { for (int i = 0; i < toPrune.getLength(); i++) { Element prune = (Element) toPrune.item(i); Element parent = (Element) prune.getParentNode(); parent.removeChild(prune);/*from www .j a va2 s .c o m*/ } } NodeList images = getNodes(realRoot, "Image"); List<Element> imageNodes = new ArrayList<Element>(); Long[] oldOffsets = null; if (images.getLength() > offsets.size()) { oldOffsets = offsets.toArray(new Long[offsets.size()]); offsets.clear(); } int nextOffset = 0; for (int i = 0; i < images.getLength(); i++) { Element image = (Element) images.item(i); Element grandparent = (Element) image.getParentNode(); if (grandparent == null) { continue; } grandparent = (Element) grandparent.getParentNode(); if (grandparent == null) { continue; } if (!"ProcessingHistory".equals(grandparent.getNodeName())) { // image is being referenced from an event list imageNodes.add(image); if (oldOffsets != null && nextOffset < oldOffsets.length) { offsets.add(oldOffsets[nextOffset]); } } grandparent = (Element) grandparent.getParentNode(); if (grandparent == null) { continue; } grandparent = (Element) grandparent.getParentNode(); if (grandparent != null) { if (!"Image".equals(grandparent.getNodeName())) { nextOffset++; } } } tileCount = new int[imageNodes.size()]; Arrays.fill(tileCount, 1); core = new ArrayList<CoreMetadata>(imageNodes.size()); acquiredDate = new double[imageNodes.size()]; descriptions = new String[imageNodes.size()]; laserWavelength = new List[imageNodes.size()]; laserIntensity = new List[imageNodes.size()]; laserActive = new List[imageNodes.size()]; laserFrap = new List[imageNodes.size()]; timestamps = new double[imageNodes.size()][]; activeDetector = new List[imageNodes.size()]; serialNumber = new String[imageNodes.size()]; lensNA = new Double[imageNodes.size()]; magnification = new Double[imageNodes.size()]; immersions = new String[imageNodes.size()]; corrections = new String[imageNodes.size()]; objectiveModels = new String[imageNodes.size()]; posX = new Length[imageNodes.size()]; posY = new Length[imageNodes.size()]; posZ = new Length[imageNodes.size()]; refractiveIndex = new Double[imageNodes.size()]; cutIns = new List[imageNodes.size()]; cutOuts = new List[imageNodes.size()]; filterModels = new List[imageNodes.size()]; microscopeModels = new String[imageNodes.size()]; detectorModels = new List[imageNodes.size()]; detectorIndexes = new HashMap[imageNodes.size()]; zSteps = new Double[imageNodes.size()]; tSteps = new Double[imageNodes.size()]; pinholes = new Double[imageNodes.size()]; zooms = new Double[imageNodes.size()]; expTimes = new Double[imageNodes.size()][]; gains = new Double[imageNodes.size()][]; detectorOffsets = new Double[imageNodes.size()][]; channelNames = new String[imageNodes.size()][]; exWaves = new Double[imageNodes.size()][]; imageROIs = new ROI[imageNodes.size()][]; imageNames = new String[imageNodes.size()]; core.clear(); for (int i = 0; i < imageNodes.size(); i++) { Element image = imageNodes.get(i); CoreMetadata ms = new CoreMetadata(); core.add(ms); int index = core.size() - 1; setSeries(index); translateImageNames(image, index); translateImageNodes(image, index); translateAttachmentNodes(image, index); translateScannerSettings(image, index); translateFilterSettings(image, index); translateTimestamps(image, index); translateLaserLines(image, index); translateROIs(image, index); translateSingleROIs(image, index); translateDetectors(image, index); final Deque<String> nameStack = new ArrayDeque<String>(); populateOriginalMetadata(image, nameStack); addUserCommentMeta(image, i); } setSeries(0); int totalSeries = 0; for (int count : tileCount) { totalSeries += count; } ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>(); for (int i = 0; i < core.size(); i++) { for (int tile = 0; tile < tileCount[i]; tile++) { newCore.add(core.get(i)); } } core = newCore; }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
@Override public void prepareForTransaction(Context context) throws EngineException { Engine.logBeans.debug("(HttpConnector) Preparing for transaction"); if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) { System.setProperty("javax.net.debug", "all"); Engine.logBeans.trace("(HttpConnector) Enabling SSL debug mode"); } else {//from w w w.ja v a 2 s . c om System.setProperty("javax.net.debug", ""); Engine.logBeans.debug("(HttpConnector) Disabling SSL debug mode"); } Engine.logBeans.debug("(HttpConnector) Initializing..."); if (context.isRequestFromVic) { // Check the VIC authorizations only if this is a non trusted // request, i.e. from a request not triggered from VIC (for // instance, from a web service call). if (!context.isTrustedRequest) { try { VicApi vicApi = new VicApi(); if (!vicApi.isServiceAuthorized(context.tasUserName, context.tasVirtualServerName, context.tasServiceCode)) { throw new EngineException("The service '" + context.tasServiceCode + "' is not authorized for the user '" + context.tasUserName + "'"); } } catch (IOException e) { throw new EngineException("Unable to retrieve authorization from the VIC database.", e); } } } AbstractHttpTransaction httpTransaction = null; try { httpTransaction = (AbstractHttpTransaction) context.requestedObject; } catch (ClassCastException e) { throw new EngineException("Requested object is not a transaction", e); } handleCookie = httpTransaction.isHandleCookie(); if (!handleCookie && httpState != null) { httpState.clearCookies(); // remove cookies from previous transaction } httpParameters = httpTransaction.getCurrentHttpParameters(); contentType = MimeType.WwwForm.value(); for (List<String> httpParameter : httpParameters) { String headerName = httpParameter.get(0); String value = httpParameter.get(1); // Content-Type if (HeaderName.ContentType.is(headerName)) { contentType = value; } // oAuth Parameters are passed as standard Headers if (HeaderName.OAuthKey.is(headerName)) { oAuthKey = value; } if (HeaderName.OAuthSecret.is(headerName)) { oAuthSecret = value; } if (HeaderName.OAuthToken.is(headerName)) { oAuthToken = value; } if (HeaderName.OAuthTokenSecret.is(headerName)) { oAuthTokenSecret = value; } } { String overrideContentType = ParameterUtils .toString(httpTransaction.getParameterValue(Parameter.HttpContentType.getName())); if (overrideContentType != null) { contentType = overrideContentType; } } int len = httpTransaction.numberOfVariables(); boolean isFormUrlEncoded = MimeType.WwwForm.is(contentType); doMultipartFormData = false; for (int i = 0; i < len; i++) { RequestableHttpVariable trVariable = (RequestableHttpVariable) httpTransaction.getVariable(i); if (trVariable.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { doMultipartFormData = true; isFormUrlEncoded = true; } } // Retrieve request template file if necessary File requestTemplateFile = null; if (!isFormUrlEncoded) { String requestTemplateUrl = httpTransaction.getRequestTemplate(); if (!requestTemplateUrl.equals("")) { String projectDirectoryName = context.project.getName(); String absoluteRequestTemplateUrl = Engine.PROJECTS_PATH + "/" + projectDirectoryName + "/" + (context.subPath.length() > 0 ? context.subPath + "/" : "") + requestTemplateUrl; Engine.logBeans.debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl); requestTemplateFile = new File(absoluteRequestTemplateUrl); if (!requestTemplateFile.exists()) { Engine.logBeans.debug( "(HttpConnector) The local request template file (\"" + absoluteRequestTemplateUrl + "\") does not exist. Trying search in Convertigo TEMPLATES directory..."); absoluteRequestTemplateUrl = Engine.TEMPLATES_PATH + "/" + requestTemplateUrl; Engine.logBeans.debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl); requestTemplateFile = new File(absoluteRequestTemplateUrl); if (!requestTemplateFile.exists()) { Engine.logBeans.debug("(HttpConnector) The common request template file (\"" + absoluteRequestTemplateUrl + "\") does not exist. Trying absolute search..."); absoluteRequestTemplateUrl = requestTemplateUrl; Engine.logBeans .debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl); requestTemplateFile = new File(absoluteRequestTemplateUrl); if (!requestTemplateFile.exists()) { throw new EngineException( "Could not find any request template file \"" + requestTemplateUrl + "\" for transaction \"" + httpTransaction.getName() + "\"."); } } } } } // Sets or overwrites server url String httpUrl = httpTransaction.getParameterStringValue(Parameter.ConnectorConnectionString.getName()); if (httpUrl != null) setBaseUrl(httpUrl); else setBaseUrl(); String transactionBaseDir = httpTransaction.getCurrentSubDir(); if (transactionBaseDir.startsWith("http")) { sUrl = transactionBaseDir; /* * if (transactionBaseDir.startsWith("https")) setHttps(true); */ } else sUrl += transactionBaseDir; // Setup the SSL properties if needed if (https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } String variable, method, httpVariable, queryString = ""; Object httpObjectVariableValue; boolean isMultiValued = false; boolean bIgnoreVariable = false; String urlEncodingCharset = httpTransaction.getComputedUrlEncodingCharset(); // Replace variables in URL List<String> urlPathVariableList = AbstractHttpTransaction.getPathVariableList(sUrl); if (!urlPathVariableList.isEmpty()) { Engine.logBeans.debug("(HttpConnector) Defined URL: " + sUrl); for (String varName : urlPathVariableList) { RequestableHttpVariable rVariable = (RequestableHttpVariable) httpTransaction.getVariable(varName); httpObjectVariableValue = rVariable == null ? "" : httpTransaction.getParameterValue(varName); httpVariable = rVariable == null ? "null" : varName; method = rVariable == null ? "NULL" : rVariable.getHttpMethod(); Engine.logBeans.trace( "(HttpConnector) Path variable: " + varName + " => (" + method + ") " + httpVariable); sUrl = sUrl.replaceAll("\\{" + varName + "\\}", ParameterUtils.toString(httpObjectVariableValue)); } } // Build query string for (int i = 0; i < len; i++) { RequestableHttpVariable rVariable = (RequestableHttpVariable) httpTransaction.getVariable(i); variable = rVariable.getName(); isMultiValued = rVariable.isMultiValued(); method = rVariable.getHttpMethod(); httpVariable = rVariable.getHttpName(); httpObjectVariableValue = httpTransaction.getParameterValue(variable); bIgnoreVariable = urlPathVariableList.contains(variable) || httpObjectVariableValue == null || httpVariable.isEmpty() || !method.equals("GET"); if (!bIgnoreVariable) { Engine.logBeans.trace( "(HttpConnector) Query variable: " + variable + " => (" + method + ") " + httpVariable); try { // handle multivalued variable if (isMultiValued) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { queryString += ((queryString.length() != 0) ? "&" : ""); queryString += httpVariable + "=" + URLEncoder .encode(ParameterUtils.toString(httpVariableValue), urlEncodingCharset); } } } // standard case else { queryString += ((queryString.length() != 0) ? "&" : ""); queryString += httpVariable + "=" + URLEncoder .encode(ParameterUtils.toString(httpObjectVariableValue), urlEncodingCharset); } } catch (UnsupportedEncodingException e) { throw new EngineException(urlEncodingCharset + " encoding is not supported.", e); } } } // Encodes URL if it contains special characters sUrl = URLUtils.encodeAbsoluteURL(sUrl, urlEncodingCharset); if (queryString.length() != 0) { if (sUrl.indexOf('?') == -1) { sUrl += "?" + queryString; } else { sUrl += "&" + queryString; } } Engine.logBeans.debug("(HttpConnector) URL: " + sUrl); if (Engine.logBeans.isDebugEnabled()) { Engine.logBeans.debug("(HttpConnector) GET query: " + Visibility.Logs.replaceVariables(httpTransaction.getVariablesList(), queryString)); } if (doMultipartFormData) { Engine.logBeans.debug("(HttpConnector) Skip postQuery computing and do a multipart/formData content"); return; } // Build body for POST/PUT postQuery = ""; // Load request template in postQuery if necessary if (!isFormUrlEncoded) { // Ticket #1040 // A request template may be an XML document; in this case, the // "standard" // process apply: tokens are replaced by their respective value. // But a request template may also be an XSL document. In this case, // an XML // document giving all transaction variables should be built and // applied to // the XSL in order to produce a real XML request template. if (requestTemplateFile != null) { try { FileInputStream fis = new FileInputStream(requestTemplateFile); Document requestTemplate = XMLUtils.parseDOM(fis); Element documentElement = requestTemplate.getDocumentElement(); // XSL document if (documentElement.getNodeName().equalsIgnoreCase("xsl:stylesheet")) { // Build the variables XML document Document variablesDocument = XMLUtils.createDom("java"); Element variablesElement = variablesDocument.createElement("variables"); variablesDocument.appendChild(variablesElement); for (RequestableVariable requestableVariable : httpTransaction.getVariablesList()) { RequestableHttpVariable trVariable = (RequestableHttpVariable) requestableVariable; variable = trVariable.getName(); isMultiValued = trVariable.isMultiValued(); httpVariable = trVariable.getHttpName(); Element variableElement = variablesDocument.createElement("variable"); variablesElement.appendChild(variableElement); variableElement.setAttribute("name", variable); httpObjectVariableValue = httpTransaction.getParameterValue(variable); if (httpObjectVariableValue != null) { if (isMultiValued) { variableElement.setAttribute("multi", "true"); if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { Element valueElement = variablesDocument.createElement("value"); variableElement.appendChild(valueElement); Text valueText = variablesDocument .createTextNode(getStringValue(trVariable, httpVariableValue)); valueElement.appendChild(valueText); } } } else { Element valueElement = variablesDocument.createElement("value"); variableElement.appendChild(valueElement); Text valueText = variablesDocument .createTextNode(getStringValue(trVariable, httpObjectVariableValue)); valueElement.appendChild(valueText); } } } if (Engine.logBeans.isDebugEnabled()) { String sVariablesDocument = XMLUtils.prettyPrintDOM((Document) Visibility.Logs .replaceVariables(httpTransaction.getVariablesList(), variablesDocument)); Engine.logBeans.debug("Build variables XML document:\n" + sVariablesDocument); } // Apply XSL TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource streamSource = new StreamSource(new FileInputStream(requestTemplateFile)); Transformer transformer = tFactory.newTransformer(streamSource); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(variablesElement), new StreamResult(sw)); postQuery = sw.getBuffer().toString(); } // XML document else { // Template has been parsed from file, retrieve its declared encoding char set // If not found use "UTF-8" according to HTTP POST for text/xml (see getData) String xmlEncoding = requestTemplate.getXmlEncoding(); xmlEncoding = (xmlEncoding == null) ? "UTF-8" : xmlEncoding; postQuery = XMLUtils.prettyPrintDOMWithEncoding(requestTemplate, xmlEncoding); } } catch (Exception e) { Engine.logBeans.warn("Unable to parse the request template file as a valid XML/XSL document"); throw new EngineException( "An unexpected error occured while retrieving the request template file for transaction \"" + httpTransaction.getName() + "\".", e); } } } RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null) { method = body.getHttpMethod(); httpObjectVariableValue = httpTransaction.getParameterValue(Parameter.HttpBody.getName()); if (method.equals("POST") && httpObjectVariableValue != null) { postQuery = ParameterUtils.toString(httpObjectVariableValue); isFormUrlEncoded = false; } } // Add all input variables marked as POST boolean isLogHidden = false; List<String> logHiddenValues = new ArrayList<String>(); for (int i = 0; i < len; i++) { bIgnoreVariable = false; RequestableHttpVariable trVariable = (RequestableHttpVariable) httpTransaction.getVariable(i); variable = trVariable.getName(); isMultiValued = trVariable.isMultiValued(); method = trVariable.getHttpMethod(); httpVariable = trVariable.getHttpName(); isLogHidden = Visibility.Logs.isMasked(trVariable.getVisibility()); // do not add variable to query if empty name if (httpVariable.equals("")) bIgnoreVariable = true; // Retrieves variable value httpObjectVariableValue = httpTransaction.getParameterValue(variable); if (method.equals("POST")) { // variable must be sent as an HTTP parameter if (!bIgnoreVariable) { Engine.logBeans.trace("(HttpConnector) Parameter variable: " + variable + " => (" + method + ") " + httpVariable); // Content-Type is 'application/x-www-form-urlencoded' if (isFormUrlEncoded) { // Replace variable value in postQuery if (httpObjectVariableValue != null) { // handle multivalued variable if (isMultiValued) { if (httpObjectVariableValue instanceof Collection<?>) for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { postQuery += ((postQuery.length() != 0) ? "&" : ""); postQuery += httpVariable + "=" + ParameterUtils.toString(httpVariableValue); } else if (httpObjectVariableValue.getClass().isArray()) for (Object httpVariableValue : (Object[]) httpObjectVariableValue) { postQuery += ((postQuery.length() != 0) ? "&" : ""); postQuery += httpVariable + "=" + ParameterUtils.toString(httpVariableValue); } } // standard case else { postQuery += ((postQuery.length() != 0) ? "&" : ""); postQuery += httpVariable + "=" + ParameterUtils.toString(httpObjectVariableValue); } } } // Content-Type is 'text/xml' else { // Replace variable value in postQuery if (httpObjectVariableValue != null) { // Handle multivalued variable if (isMultiValued) { String varPattern = "$(" + httpVariable + ")"; int varPatternIndex, indexAfterPattern, beginTagIndex, endTagIndex; if (httpObjectVariableValue instanceof Collection<?>) { // while postQuery contains the variable // pattern while (postQuery.indexOf(varPattern) != -1) { varPatternIndex = postQuery.indexOf(varPattern); indexAfterPattern = varPatternIndex + varPattern.length(); if (postQuery.substring(indexAfterPattern).startsWith("concat")) { // concat every value from the // vector // to replace the occurrence in the // template // by the concatenation of the // multiple values String httpVariableValue = ""; for (Object var : (Collection<?>) httpObjectVariableValue) httpVariableValue += getStringValue(trVariable, var); if (isLogHidden) logHiddenValues.add(httpVariableValue); postQuery = postQuery.substring(0, varPatternIndex) + httpVariableValue + postQuery.substring(indexAfterPattern + "concat".length()); } else { // duplicate the tag surrounding the // occurrence in the template // for each value from the vector beginTagIndex = postQuery.substring(0, varPatternIndex) .lastIndexOf('<'); endTagIndex = indexAfterPattern + postQuery.substring(indexAfterPattern).indexOf('>'); String tmpPostQuery = postQuery.substring(0, beginTagIndex); for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { String stringValue = getStringValue(trVariable, httpVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } tmpPostQuery += (postQuery.substring(beginTagIndex, varPatternIndex) + stringValue + postQuery.substring(indexAfterPattern, endTagIndex + 1)); } tmpPostQuery += postQuery.substring(endTagIndex + 1); postQuery = tmpPostQuery; } } } else { String stringValue = getStringValue(trVariable, httpObjectVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } StringEx sx = new StringEx(postQuery); sx.replaceAll("$(" + httpVariable + ")concat", stringValue); postQuery = sx.toString(); } } // Handle single valued variable else { String stringValue = getStringValue(trVariable, httpObjectVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } StringEx sx = new StringEx(postQuery); sx.replaceAll("$(" + httpVariable + ")noE", stringValue); sx.replaceAll("$(" + httpVariable + ")", stringValue); postQuery = sx.toString(); } } // Remove variable from postQuery else { String varPattern = "$(" + httpVariable + ")"; int varPatternIndex, beginTagIndex, endTagIndex; // while postQuery contains the variable pattern while (postQuery.indexOf(varPattern) != -1) { varPatternIndex = postQuery.indexOf(varPattern); beginTagIndex = postQuery.substring(0, varPatternIndex).lastIndexOf('<'); endTagIndex = postQuery.indexOf('>', varPatternIndex); postQuery = postQuery.substring(0, beginTagIndex) + postQuery.substring(endTagIndex + 1); } } } } } else if (method.equals("")) { // Replace variable value in postQuery if (httpObjectVariableValue != null) { if (!isFormUrlEncoded && (!(httpVariable.equals("")))) {// used // to // replace // empty // element String stringValue = getStringValue(trVariable, httpObjectVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } StringEx sx = new StringEx(postQuery); sx.replaceAll(httpVariable, stringValue); postQuery = sx.toString(); } } } } if (Engine.logBeans.isDebugEnabled()) { Engine.logBeans.debug("(HttpConnector) POST query: " + (isFormUrlEncoded ? "" : "\n") + (isFormUrlEncoded ? Visibility.Logs.replaceVariables(httpTransaction.getVariablesList(), postQuery) : Visibility.Logs.replaceValues(logHiddenValues, postQuery))); } Engine.logBeans.debug("(HttpConnector) Connector successfully prepared for transaction"); }
From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java
protected Document parseResultDocument(String result, String expectedRootElement) throws Exception { Document doc = Util.parse(result); Element rootElement = doc.getDocumentElement(); if (!rootElement.getNodeName().equals(expectedRootElement)) { // When there is a null value in fields, the viewable fields sequence is not enclosed by expected element // FIXME Better to find out a solution at the underlying stage doc.removeChild(rootElement);// w w w.jav a 2 s . c o m Element resultElement = doc.createElement(expectedRootElement); resultElement.appendChild(rootElement); } return doc; }
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
@Override public void checkSigningCertificate() { final CandidatesForSigningCertificate candidates = getCandidatesForSigningCertificate(); /**// ww w.jav a 2 s . co m * The ../SignedProperties/SignedSignatureProperties/SigningCertificate element MAY contain references and digests values of other * certificates (that MAY form a chain up to the point of trust). */ boolean isEn319132 = false; NodeList list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT); int length = list.getLength(); if (length == 0) { list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT_V2); length = list.getLength(); isEn319132 = true; } if (length == 0) { final CertificateValidity theCertificateValidity = candidates.getTheCertificateValidity(); final CertificateToken certificateToken = theCertificateValidity == null ? null : theCertificateValidity.getCertificateToken(); // The check need to be done at the level of KeyInfo for (final Reference reference : references) { final String uri = reference.getURI(); if (!uri.startsWith("#")) { continue; } final String id = uri.substring(1); final Element element = signatureElement.getOwnerDocument().getElementById(id); // final Element element = // DSSXMLUtils.getElement(signatureElement, ""); if (!hasSignatureAsParent(element)) { continue; } if ((certificateToken != null) && id.equals(certificateToken.getXmlId())) { theCertificateValidity.setSigned(element.getNodeName()); return; } } } // This Map contains the list of the references to the certificate which // were already checked and which correspond to a certificate. Map<Element, Boolean> alreadyProcessedElements = new HashMap<Element, Boolean>(); final List<CertificateValidity> certificateValidityList = candidates.getCertificateValidityList(); for (final CertificateValidity certificateValidity : certificateValidityList) { final CertificateToken certificateToken = certificateValidity.getCertificateToken(); for (int ii = 0; ii < length; ii++) { certificateValidity.setAttributePresent(true); final Element element = (Element) list.item(ii); if (alreadyProcessedElements.containsKey(element)) { continue; } final Element certDigestElement = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__CERT_DIGEST); certificateValidity.setDigestPresent(certDigestElement != null); final Element digestMethodElement = DSSXMLUtils.getElement(certDigestElement, xPathQueryHolder.XPATH__DIGEST_METHOD); if (digestMethodElement == null) { continue; } final String xmlAlgorithmName = digestMethodElement.getAttribute(XMLE_ALGORITHM); // The default algorithm is used in case of bad encoded // algorithm name final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forXML(xmlAlgorithmName, DigestAlgorithm.SHA1); final Element digestValueElement = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__CERT_DIGEST_DIGEST_VALUE); if (digestValueElement == null) { continue; } // That must be a binary comparison final byte[] storedBase64DigestValue = DSSUtils .base64StringToBase64Binary(digestValueElement.getTextContent()); /** * Step 1:<br> * Take the first child of the property and check that the content of ds:DigestValue matches the result of digesting <i>the candidate * for</i> the signing certificate with the algorithm indicated in ds:DigestMethod. If they do not match, take the next child and * repeat this step until a matching child element has been found or all children of the element have been checked. If they do match, * continue with step 2. If the last element is reached without finding any match, the validation of this property shall be taken as * failed and INVALID/FORMAT_FAILURE is returned. */ final byte[] digest = DSSUtils.digest(digestAlgorithm, certificateToken.getEncoded()); final byte[] recalculatedBase64DigestValue = Base64.encodeBase64(digest); certificateValidity.setDigestEqual(false); BigInteger serialNumber = new BigInteger("0"); if (Arrays.equals(recalculatedBase64DigestValue, storedBase64DigestValue)) { X500Principal issuerName = null; if (isEn319132) { final Element issuerNameEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_ISSUER_V2); if (issuerNameEl != null) { final String textContent = issuerNameEl.getTextContent(); ASN1InputStream is = new ASN1InputStream(Base64.decodeBase64(textContent)); ASN1Sequence seq = null; try { seq = (ASN1Sequence) is.readObject(); is.close(); } catch (IOException e) { e.printStackTrace(); } //IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(seq); IssuerAndSerialNumber issuerAndSerial = IssuerAndSerialNumber.getInstance(seq); issuerName = new X500Principal(issuerAndSerial.getName().toString()); serialNumber = issuerAndSerial.getSerialNumber().getValue(); } } else { final Element issuerNameEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_ISSUER_NAME); // This can be allayed when the distinguished name is not // correctly encoded // final String textContent = // DSSUtils.unescapeMultiByteUtf8Literals(issuerNameEl.getTextContent()); final String textContent = issuerNameEl.getTextContent(); issuerName = DSSUtils.getX500PrincipalOrNull(textContent); } final X500Principal candidateIssuerName = certificateToken.getIssuerX500Principal(); // final boolean issuerNameMatches = // candidateIssuerName.equals(issuerName); final boolean issuerNameMatches = DSSUtils.x500PrincipalAreEquals(candidateIssuerName, issuerName); if (!issuerNameMatches) { final String c14nCandidateIssuerName = candidateIssuerName.getName(X500Principal.CANONICAL); LOG.info("candidateIssuerName: " + c14nCandidateIssuerName); final String c14nIssuerName = issuerName == null ? "" : issuerName.getName(X500Principal.CANONICAL); LOG.info("issuerName : " + c14nIssuerName); } if (!isEn319132) { final Element serialNumberEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_SERIAL_NUMBER); final String serialNumberText = serialNumberEl.getTextContent(); // serial number can contain leading and trailing whitespace. serialNumber = new BigInteger(serialNumberText.trim()); } final BigInteger candidateSerialNumber = certificateToken.getSerialNumber(); final boolean serialNumberMatches = candidateSerialNumber.equals(serialNumber); certificateValidity.setDigestEqual(true); certificateValidity.setSerialNumberEqual(serialNumberMatches); certificateValidity.setDistinguishedNameEqual(issuerNameMatches); // The certificate was identified alreadyProcessedElements.put(element, true); // If the signing certificate is not set yet then it must be // done now. Actually if the signature is tempered then the // method checkSignatureIntegrity cannot set the signing // certificate. if (candidates.getTheCertificateValidity() == null) { candidates.setTheCertificateValidity(certificateValidity); } break; } } } }
From source file:de.betterform.connector.serializer.FormDataSerializer.java
protected void serializeElement(PrintWriter writer, Element element, String boundary, String charset) throws Exception { /* The specs http://www.w3.org/TR/2003/REC-xforms-20031014/slice11.html#serialize-form-data */*from ww w. j a v a 2 s .c o m*/ * Each element node is visited in document order. * * Each element that has exactly one text node child is selected * for inclusion. * * Element nodes selected for inclusion are as encoded as * Content-Disposition: form-data MIME parts as defined in * [RFC 2387], with the name parameter being the element local name. * * Element nodes of any datatype populated by upload are serialized * as the specified content and additionally have a * Content-Disposition filename parameter, if available. * * The Content-Type must be text/plain except for xsd:base64Binary, * xsd:hexBinary, and derived types, in which case the header * represents the media type of the attachment if known, otherwise * application/octet-stream. If a character set is applicable, the * Content-Type may have a charset parameter. * */ String nodeValue = null; boolean isCDATASection = false; boolean includeTextNode = true; NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); switch (n.getNodeType()) { /* CDATA sections are not mentioned ... ignore for now case Node.CDATA_SECTION_NODE: isCDATASection = true; */ case Node.TEXT_NODE: if (includeTextNode) { if (nodeValue != null) { /* only one text node allowed by specs */ includeTextNode = false; } else { nodeValue = n.getNodeValue(); } } break; /* Real ambiguity in specs, what if there's one text node and * n elements ? Let's assume if there is an element, ignore the * text nodes */ case Node.ELEMENT_NODE: includeTextNode = false; serializeElement(writer, (Element) n, boundary, charset); break; default: // ignore comments and other nodes... } } if (nodeValue != null && includeTextNode) { Object object = element.getUserData(""); if (object != null && !(object instanceof ModelItem)) { throw new XFormsException("Unknown instance data format."); } ModelItem item = (ModelItem) object; writer.print("\r\n--" + boundary); String name = element.getLocalName(); if (name == null) { name = element.getNodeName(); } // mediatype tells about file upload if (item != null && item.getMediatype() != null) { writer.print("\r\nContent-Disposition: form-data; name=\"" + name + "\";"); if (item.getFilename() != null) { File file = new File(item.getFilename()); writer.print(" filename=\"" + file.getName() + "\";"); } writer.print("\r\nContent-Type: " + item.getMediatype()); } else { writer.print("\r\nContent-Disposition: form-data; name=\"" + name + "\";"); writer.print("\r\nContent-Type: text/plain; charset=\"" + charset + "\";"); } String encoding = "8bit"; if (item != null && "base64Binary".equalsIgnoreCase(item.getDeclarationView().getDatatype())) { encoding = "base64"; } else if (item != null && "hexBinary".equalsIgnoreCase(item.getDeclarationView().getDatatype())) { // recode to base64 because of MIME nodeValue = new String(Base64.encodeBase64(Hex.decodeHex(nodeValue.toCharArray()), true)); encoding = "base64"; } writer.print("\r\nContent-Transfer-Encoding: " + encoding); writer.print("\r\n\r\n" + nodeValue); } writer.flush(); }