List of usage examples for org.w3c.dom Element getFirstChild
public Node getFirstChild();
From source file:com.hp.application.automation.tools.results.RunResultRecorder.java
private void processSlaRule(JobLrScenarioResult jobLrScenarioResult, Element slaRuleElement, LrTest.SLA_GOAL slaGoal) {//w w w. j a va2s . c o m switch (slaGoal) { case AverageThroughput: WholeRunResult averageThroughput = new WholeRunResult(); averageThroughput.setSlaGoal(LrTest.SLA_GOAL.AverageThroughput); averageThroughput.setActualValue(Double.valueOf(slaRuleElement.getAttribute(SLA_ACTUAL_VALUE_LABEL))); averageThroughput.setGoalValue(Double.valueOf(slaRuleElement.getAttribute(SLA_GOAL_VALUE_LABEL))); averageThroughput.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); averageThroughput.setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getTextContent())); jobLrScenarioResult.scenarioSlaResults.add(averageThroughput); break; case TotalThroughput: WholeRunResult totalThroughput = new WholeRunResult(); totalThroughput.setSlaGoal(LrTest.SLA_GOAL.TotalThroughput); totalThroughput.setActualValue(Double.valueOf(slaRuleElement.getAttribute(SLA_ACTUAL_VALUE_LABEL))); totalThroughput.setGoalValue(Double.valueOf(slaRuleElement.getAttribute(SLA_GOAL_VALUE_LABEL))); totalThroughput.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); totalThroughput.setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getTextContent())); jobLrScenarioResult.scenarioSlaResults.add(totalThroughput); break; case AverageHitsPerSecond: WholeRunResult averageHitsPerSecond = new WholeRunResult(); averageHitsPerSecond.setSlaGoal(LrTest.SLA_GOAL.AverageHitsPerSecond); averageHitsPerSecond .setActualValue(Double.valueOf(slaRuleElement.getAttribute(SLA_ACTUAL_VALUE_LABEL))); averageHitsPerSecond.setGoalValue(Double.valueOf(slaRuleElement.getAttribute(SLA_GOAL_VALUE_LABEL))); averageHitsPerSecond.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); averageHitsPerSecond.setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getTextContent())); jobLrScenarioResult.scenarioSlaResults.add(averageHitsPerSecond); break; case TotalHits: WholeRunResult totalHits = new WholeRunResult(); totalHits.setSlaGoal(LrTest.SLA_GOAL.TotalHits); totalHits.setActualValue(Double.valueOf(slaRuleElement.getAttribute(SLA_ACTUAL_VALUE_LABEL))); totalHits.setGoalValue(Double.valueOf(slaRuleElement.getAttribute(SLA_GOAL_VALUE_LABEL))); totalHits.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); totalHits.setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getTextContent())); jobLrScenarioResult.scenarioSlaResults.add(totalHits); break; case ErrorsPerSecond: TimeRangeResult errPerSec = new AvgTransactionResponseTime(); errPerSec.setSlaGoal(LrTest.SLA_GOAL.ErrorsPerSecond); errPerSec.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); errPerSec.setLoadThrashold(slaRuleElement.getAttribute("SLALoadThresholdValue")); errPerSec.setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getFirstChild().getTextContent())); //Might not work due to time ranges addTimeRanges(errPerSec, slaRuleElement); jobLrScenarioResult.scenarioSlaResults.add(errPerSec); break; case PercentileTRT: PercentileTransactionWholeRun percentileTransactionWholeRun = new PercentileTransactionWholeRun(); percentileTransactionWholeRun.setSlaGoal(LrTest.SLA_GOAL.PercentileTRT); percentileTransactionWholeRun.setName(slaRuleElement.getAttribute("TransactionName")); percentileTransactionWholeRun .setActualValue(Double.valueOf(slaRuleElement.getAttribute(SLA_ACTUAL_VALUE_LABEL))); percentileTransactionWholeRun .setGoalValue(Double.valueOf(slaRuleElement.getAttribute(SLA_GOAL_VALUE_LABEL))); percentileTransactionWholeRun.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); percentileTransactionWholeRun.setPrecentage(Double.valueOf(slaRuleElement.getAttribute("Percentile"))); percentileTransactionWholeRun.setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getTextContent())); jobLrScenarioResult.scenarioSlaResults.add(percentileTransactionWholeRun); break; case AverageTRT: AvgTransactionResponseTime transactionTimeRange = new AvgTransactionResponseTime(); transactionTimeRange.setSlaGoal(LrTest.SLA_GOAL.AverageTRT); transactionTimeRange.setName(slaRuleElement.getAttribute("TransactionName")); transactionTimeRange.setFullName(slaRuleElement.getAttribute(SLA_ULL_NAME)); transactionTimeRange.setLoadThrashold(slaRuleElement.getAttribute("SLALoadThresholdValue")); transactionTimeRange .setStatus(LrTest.SLA_STATUS.checkStatus(slaRuleElement.getFirstChild().getTextContent())); //Might not work due to time ranges addTimeRanges(transactionTimeRange, slaRuleElement); jobLrScenarioResult.scenarioSlaResults.add(transactionTimeRange); break; case Bad: break; } }
From source file:org.apache.manifoldcf.crawler.connectors.meridio.MeridioConnector.java
/** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above./*from w w w. j a v a 2 s . c om*/ *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { // Get forced acls/security enable/disable String[] acls = getAcls(spec); // Sort it, in case it is needed. if (acls != null) java.util.Arrays.sort(acls); // Look at the metadata attributes. // So that the version strings are comparable, we will put them in an array first, and sort them. Set<String> holder = new HashSet<String>(); String pathAttributeName = null; MatchMap matchMap = new MatchMap(); boolean allMetadata = false; int i = 0; while (i < spec.getChildCount()) { SpecificationNode n = spec.getChild(i++); if (n.getType().equals("ReturnedMetadata")) { String category = n.getAttributeValue("category"); String attributeName = n.getAttributeValue("property"); String metadataName; if (category == null || category.length() == 0) metadataName = attributeName; else metadataName = category + "." + attributeName; holder.add(metadataName); } else if (n.getType().equals("AllMetadata")) { String value = n.getAttributeValue("value"); if (value != null && value.equals("true")) { allMetadata = true; } } else if (n.getType().equals("pathnameattribute")) pathAttributeName = n.getAttributeValue("value"); else if (n.getType().equals("pathmap")) { // Path mapping info also needs to be looked at, because it affects what is // ingested. String pathMatch = n.getAttributeValue("match"); String pathReplace = n.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch, pathReplace); } } while (true) { getSession(); // The version string returned must include everything that could affect what is ingested. In meridio's // case, this includes the date stamp, but it also includes the part of the specification that describes // the metadata desired. // The code here relies heavily on the search method to do it's thing. The search method originally // used the document specification to determine what metadata to return, which was problematic because that // meant this method had to modify the specification (not good practice), and was also wrong from the point // of view that we need to get the metadata specification appended to the version string in some way, and // use THAT data in processDocuments(). So I've broken all that up. try { // Put into an array ReturnMetadata[] categoryPropertyValues; String[] categoryPropertyStringValues; String[] sortArray; if (allMetadata) { categoryPropertyStringValues = getMeridioDocumentProperties(); } else { categoryPropertyStringValues = new String[holder.size()]; i = 0; for (String value : holder) { categoryPropertyStringValues[i++] = value; } } // Sort! java.util.Arrays.sort(categoryPropertyStringValues); categoryPropertyValues = new ReturnMetadata[categoryPropertyStringValues.length]; i = 0; for (String value : categoryPropertyStringValues) { int dotIndex = value.indexOf("."); String categoryName = null; String propertyName; if (dotIndex == -1) propertyName = value; else { categoryName = value.substring(0, dotIndex); propertyName = value.substring(dotIndex + 1); } categoryPropertyValues[i++] = new ReturnMetadata(categoryName, propertyName); } // Prepare the part of the version string that is decodeable StringBuilder decodeableString = new StringBuilder(); // Add the metadata piece first packList(decodeableString, categoryPropertyStringValues, '+'); // Now, put in the forced acls. // The version string needs only to contain the forced acls, since the version date captures changes // made to the acls that are actually associated with the document. if (acls == null) decodeableString.append('-'); else { decodeableString.append('+'); packList(decodeableString, acls, '+'); decodeableString.append('+'); pack(decodeableString, defaultAuthorityDenyToken, '+'); } // Calculate the part of the version string that comes from path name and mapping. if (pathAttributeName != null) { decodeableString.append("+"); pack(decodeableString, pathAttributeName, '+'); pack(decodeableString, matchMap.toString(), '+'); } else decodeableString.append("-"); long[] docIds = new long[documentIdentifiers.length]; for (i = 0; i < documentIdentifiers.length; i++) { docIds[i] = new Long(documentIdentifiers[i]).longValue(); } /*================================================================= * Call the search, with the document specification and the list of * document ids - the search will never return more than exactly * one match per document id * * We are assuming that the maximum number of hits to return * should never be more than the maximum batch size set up for this * class * * We are just making one web service call (to the search API) * rather than iteratively calling a web service method for each * document passed in as part of the document array * * Additionally, re-using the same search method as for the * "getDocumentIdentifiers" method ensures that we are not * duplicating any logic which ensures that the document/records * in question match the search criteria or not. *================================================================*/ DMSearchResults searchResults = documentSpecificationSearch(spec, 0, 0, 1, this.getMaxDocumentRequest(), docIds, null); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Found a total of <" + searchResults.totalHitsCount + "> hit(s) " + "and <" + searchResults.returnedHitsCount + "> were returned by the method call"); // If we are searching based on document identifier, then it is possible that we will not // find a document we are looking for, if it was removed from the system between the time // it was put in the queue and when it's version is obtained. Documents where this happens // should return a version string of null. // Let's go through the search results and build a hash based on the document identifier. Map<Long, SEARCHRESULTS_DOCUMENTS> documentMap = new HashMap<Long, SEARCHRESULTS_DOCUMENTS>(); if (searchResults.dsDM != null) { SEARCHRESULTS_DOCUMENTS[] srd = searchResults.dsDM.getSEARCHRESULTS_DOCUMENTS(); for (i = 0; i < srd.length; i++) { documentMap.put(new Long(srd[i].getDocId()), srd[i]); } } // Now, walk through the individual documents. Map<Long, String> versionStrings = new HashMap<Long, String>(); for (int j = 0; j < docIds.length; j++) { String documentIdentifier = documentIdentifiers[j]; long docId = docIds[j]; Long docKey = new Long(docId); // Look up the record. SEARCHRESULTS_DOCUMENTS doc = documentMap.get(docKey); if (doc != null) { // Set the version string. The parseable stuff goes first, so parsing is easy. String version = doc.getStr_value(); StringBuilder composedVersion = new StringBuilder(); composedVersion.append(decodeableString); composedVersion.append(version); // Added 9/7/2007 composedVersion.append("_").append(urlVersionBase); // String versionString = composedVersion.toString(); if (Logging.connectors.isDebugEnabled()) Logging.connectors .debug("Meridio: Document " + docKey + " has version " + versionString); if (activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) versionStrings.put(docKey, versionString); } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: Document " + docKey + " is no longer in the search set, or has been deleted - removing."); activities.deleteDocument(documentIdentifier); } } // Now submit search requests for all the documents requiring fetch. Map<Long, Map<String, String>> documentPropertyMap = new HashMap<Long, Map<String, String>>(); // Only look up metadata if we need some! if (versionStrings.size() > 0 && categoryPropertyValues.length > 0) { long[] fetchIds = new long[versionStrings.size()]; i = 0; for (Long docKey : versionStrings.keySet()) { fetchIds[i++] = docKey; } /*================================================================= * Call the search, with the document specification and the list of * document ids - the search will never return more than exactly * one match per document id * * This call will return all the metadata that was specified in the * document specification for all the documents and * records in one call. *================================================================*/ searchResults = documentSpecificationSearch(spec, 0, 0, 1, fetchIds.length, fetchIds, categoryPropertyValues); // If we ask for a document and it is no longer there, we should treat this as a deletion. // The activity in that case is to delete the document. A similar thing should happen if // any of the other methods (like getting the document's content) also fail to find the // document. // Let's build a hash which contains all the document metadata returned. The form of // the hash will be: key = the document identifier, value = another hash, which is keyed // by the metadata category/property, and which has a value that is the metadata value. Map<Long, MutableInteger> counterMap = new HashMap<Long, MutableInteger>(); if (searchResults.dsDM != null) { SEARCHRESULTS_DOCUMENTS[] searchResultsDocuments = searchResults.dsDM .getSEARCHRESULTS_DOCUMENTS(); for (SEARCHRESULTS_DOCUMENTS searchResultsDocument : searchResultsDocuments) { long docId = searchResultsDocument.getDocId(); Long docKey = new Long(docId); MutableInteger counterMapItem = counterMap.get(docKey); if (counterMapItem == null) { counterMapItem = new MutableInteger(); counterMap.put(docKey, counterMapItem); } String propertyName = categoryPropertyStringValues[counterMapItem.getValue()]; counterMapItem.increment(); String propertyValue = searchResultsDocuments[i].getStr_value(); Map<String, String> propertyMap = documentPropertyMap.get(docKey); if (propertyMap == null) { propertyMap = new HashMap<String, String>(); documentPropertyMap.put(docKey, propertyMap); } if (propertyValue != null && propertyValue.length() > 0) propertyMap.put(propertyName, propertyValue); } } } // Okay, we are ready now to go through the individual documents and do the ingestion or deletion. for (String documentIdentifier : documentIdentifiers) { Long docKey = new Long(documentIdentifier); long docId = docKey.longValue(); String docVersion = versionStrings.get(docKey); if (docVersion != null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Processing document identifier '" + documentIdentifier + "' " + "with version string '" + docVersion + "'"); // For each document, be sure the job is still allowed to run. activities.checkJobStillActive(); RepositoryDocument repositoryDocument = new RepositoryDocument(); // Load the metadata items into the ingestion document object Map<String, String> docMetadataMap = documentPropertyMap.get(docKey); if (docMetadataMap != null) { for (String categoryPropertyName : categoryPropertyStringValues) { String propertyValue = docMetadataMap.get(categoryPropertyName); if (propertyValue != null && propertyValue.length() > 0) repositoryDocument.addField(categoryPropertyName, propertyValue); } } /*================================================================= * Construct the URL to the object * * HTTP://HOST:PORT/meridio/browse/downloadcontent.aspx?documentId=<docId>&launchMode=1&launchAs=0 * * I expect we need to add additional parameters to the configuration * specification *================================================================*/ String fileURL = urlBase + new Long(docId).toString(); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug( "URL for document '" + new Long(docId).toString() + "' is '" + fileURL + "'"); /*================================================================= * Get the object's ACLs and owner information *================================================================*/ DMDataSet documentData = null; documentData = meridio_.getDocumentData((int) docId, true, true, false, false, DmVersionInfo.LATEST, false, false, false); if (null == documentData) { if (Logging.connectors.isDebugEnabled()) Logging.connectors .debug("Meridio: Could not retrieve document data for document id '" + new Long(docId).toString() + "' in processDocuments method - deleting document."); activities.noDocument(documentIdentifier, docVersion); continue; } if (null == documentData.getDOCUMENTS() || documentData.getDOCUMENTS().length != 1) { if (Logging.connectors.isDebugEnabled()) Logging.connectors .debug("Meridio: Could not retrieve document owner for document id '" + new Long(docId).toString() + "' in processDocuments method. No information or incorrect amount " + "of information was returned"); activities.noDocument(documentIdentifier, docVersion); continue; } // Do path metadata if (pathAttributeName != null && pathAttributeName.length() > 0) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: Path attribute name is " + pathAttributeName); RMDataSet partList; int recordType = documentData.getDOCUMENTS()[0].getPROP_recordType(); if (recordType == 0 || recordType == 4 || recordType == 19) partList = meridio_.getRecordPartList((int) docId, false, false); else partList = meridio_.getDocumentPartList((int) docId); if (partList != null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: Document '" + new Long(docId).toString() + "' has a part list with " + Integer.toString(partList.getRm2vPart().length) + " values"); for (int k = 0; k < partList.getRm2vPart().length; k++) { repositoryDocument.addField(pathAttributeName, matchMap.translate(partList.getRm2vPart()[k].getParentTitlePath())); } } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: Document '" + new Long(docId).toString() + "' has no part list, so no path attribute"); } } // Process acls. If there are forced acls, use those, otherwise get them from Meridio. String[] allowAcls; String[] denyAcls; // forcedAcls will be null if security is off, or nonzero length if security is on but hard-wired if (acls != null && acls.length == 0) { ACCESSCONTROL[] documentAcls = documentData.getACCESSCONTROL(); List<String> allowAclsArrayList = new ArrayList<String>(); List<String> denyAclsArrayList = new ArrayList<String>(); // Allow a broken authority to disable all Meridio documents, even if the document is 'wide open', because // Meridio does not permit viewing of the document if the user does not exist (at least, I don't know of a way). denyAclsArrayList.add(defaultAuthorityDenyToken); if (documentAcls != null) { for (int j = 0; j < documentAcls.length; j++) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Object Id '" + documentAcls[j].getObjectId() + "' " + "Object Type '" + documentAcls[j].getObjectType() + "' " + "Permission '" + documentAcls[j].getPermission() + "' " + "User Id '" + documentAcls[j].getUserId() + "' " + "Group Id '" + documentAcls[j].getGroupId() + "'"); if (documentAcls[j].getPermission() == 0) // prohibit permission { if (documentAcls[j].getGroupId() > 0) { denyAclsArrayList.add("G" + documentAcls[j].getGroupId()); } else if (documentAcls[j].getUserId() > 0) { denyAclsArrayList.add("U" + documentAcls[j].getUserId()); } } else // read, amend or manage { if (documentAcls[j].getGroupId() > 0) { allowAclsArrayList.add("G" + documentAcls[j].getGroupId()); } else if (documentAcls[j].getUserId() > 0) { allowAclsArrayList.add("U" + documentAcls[j].getUserId()); } } } } DOCUMENTS document = documentData.getDOCUMENTS()[0]; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Document id '" + new Long(docId).toString() + "' is owned by owner id '" + document.getPROP_ownerId() + "' having the owner name '" + document.getPROP_ownerName() + "' Record Type is '" + document.getPROP_recordType() + "'"); if (document.getPROP_recordType() == 4 || document.getPROP_recordType() == 19) { RMDataSet rmds = meridio_.getRecord((int) docId, false, false, false); Rm2vRecord record = rmds.getRm2vRecord()[0]; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Record User Id Owner is '" + record.getOwnerID() + "' Record Group Owner Id is '" + record.getGroupOwnerID() + "'"); /*================================================================= * Either a group or a user owns a record, cannot be both and the * group takes priority if it is set *================================================================*/ if (record.getGroupOwnerID() > 0) { allowAclsArrayList.add("G" + record.getGroupOwnerID()); } else if (record.getOwnerID() > 0) { allowAclsArrayList.add("U" + record.getOwnerID()); } } else { allowAclsArrayList.add("U" + document.getPROP_ownerId()); } /*================================================================= * Set up the string arrays and then set the ACLs in the * repository document *================================================================*/ allowAcls = new String[allowAclsArrayList.size()]; for (int j = 0; j < allowAclsArrayList.size(); j++) { allowAcls[j] = allowAclsArrayList.get(j); if (Logging.connectors.isDebugEnabled()) Logging.connectors .debug("Meridio: Adding '" + allowAcls[j] + "' to allow ACLs"); } denyAcls = new String[denyAclsArrayList.size()]; for (int j = 0; j < denyAclsArrayList.size(); j++) { denyAcls[j] = denyAclsArrayList.get(j); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: Adding '" + denyAcls[j] + "' to deny ACLs"); } } else { allowAcls = acls; if (allowAcls == null) denyAcls = null; else denyAcls = new String[] { defaultAuthorityDenyToken }; } repositoryDocument.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT, allowAcls, denyAcls); /*================================================================= * Get the object's content, and ingest the document *================================================================*/ try { AttachmentPart ap = meridio_.getLatestVersionFile((int) docId); if (null == ap) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: Failed to get content for document '" + new Long(docId).toString() + "'"); // No document. Delete what's there activities.noDocument(documentIdentifier, docVersion); continue; } try { // Get the file name. String fileName = ap.getDataHandler().getName(); // Log what we are about to do. if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Meridio: File data is supposedly in " + fileName); File theTempFile = new File(fileName); if (theTempFile.isFile()) { long fileSize = theTempFile.length(); // ap.getSize(); if (activities.checkLengthIndexable(fileSize)) { InputStream is = new FileInputStream(theTempFile); // ap.getDataHandler().getInputStream(); try { repositoryDocument.setBinary(is, fileSize); if (null != activities) { activities.ingestDocumentWithException(documentIdentifier, docVersion, fileURL, repositoryDocument); } } finally { is.close(); } } else { activities.noDocument(documentIdentifier, docVersion); continue; } } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug( "Meridio: Expected temporary file was not present - skipping document '" + new Long(docId).toString() + "'"); activities.deleteDocument(documentIdentifier); continue; } } finally { ap.dispose(); } } catch (java.net.SocketTimeoutException ioex) { throw new ManifoldCFException("Socket timeout exception: " + ioex.getMessage(), ioex); } catch (ConnectTimeoutException ioex) { throw new ManifoldCFException("Connect timeout exception: " + ioex.getMessage(), ioex); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED); } catch (org.apache.axis.AxisFault e) { throw e; } catch (RemoteException e) { throw e; } catch (SOAPException soapEx) { throw new ManifoldCFException( "SOAP Exception encountered while retrieving document content: " + soapEx.getMessage(), soapEx); } catch (IOException ioex) { throw new ManifoldCFException("Input stream failure: " + ioex.getMessage(), ioex); } } } Logging.connectors.debug("Meridio: Exiting 'processDocuments' method"); return; } catch (org.apache.axis.AxisFault e) { long currentTime = System.currentTimeMillis(); if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) { org.w3c.dom.Element elem = e.lookupFaultDetail( new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode")); if (elem != null) { elem.normalize(); String httpErrorCode = elem.getFirstChild().getNodeValue().trim(); throw new ManifoldCFException("Unexpected http error code " + httpErrorCode + " accessing Meridio: " + e.getMessage(), e); } throw new ManifoldCFException( "Unknown http error occurred while getting doc versions: " + e.getMessage(), e); } if (e.getFaultCode().equals(new javax.xml.namespace.QName( "http://schemas.xmlsoap.org/soap/envelope/", "Server.userException"))) { String exceptionName = e.getFaultString(); if (exceptionName.equals("java.lang.InterruptedException")) throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED); } if (e.getFaultCode().equals( new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"))) { if (e.getFaultString().indexOf(" 23031#") != -1) { // This means that the session has expired, so reset it and retry meridio_ = null; continue; } } if (Logging.connectors.isDebugEnabled()) Logging.connectors .debug("Meridio: Got an unknown remote exception getting doc versions - axis fault = " + e.getFaultCode().getLocalPart() + ", detail = " + e.getFaultString() + " - retrying", e); throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L, currentTime + 3 * 60 * 60000L, -1, false); } catch (RemoteException remoteException) { throw new ManifoldCFException("Meridio: A remote exception occurred while getting doc versions: " + remoteException.getMessage(), remoteException); } catch (MeridioDataSetException meridioDataSetException) { throw new ManifoldCFException("Meridio: A problem occurred manipulating the Web " + "Service XML: " + meridioDataSetException.getMessage(), meridioDataSetException); } } }
From source file:org.alfresco.web.config.forms.FormConfigRuntime.java
/** * @param properties//w w w . j a va 2s . com * @return */ public boolean syncForm(HashMap<String, Object> properties) { boolean status = false; Element currentElem = null; String configType = (String) properties.get("config-type"); if (configType != null) { if (configType.equals("node-type") || configType.equals("model-type") || configType.equals("aspect")) { String typeName = (String) properties.get("type-name"); String newTypeName = (properties.containsKey("new-type-name")) ? (String) properties.get("new-type-name") : null; String formId = (String) properties.get("form-id"); String newFormId = (properties.containsKey("new-form-id")) ? (String) properties.get("new-form-id") : null; if (typeName != null && formId != null) { Element configElem = XmlUtils.findFirstElement( "config[@evaluator='" + configType + "' and @condition='" + typeName + "']", (Element) configDocument.getFirstChild()); if (newTypeName != null && !newTypeName.equals(typeName) && configElem != null) { //configElem.getParentNode().removeChild(configElem); removeChild(configElem); typeName = newTypeName; configElem = null; status = true; } if (configElem == null) { configElem = configDocument.createElement("config"); manageAttribute(configElem, "evaluator", configType); manageAttribute(configElem, "condition", typeName); appendChild((Element) configDocument.getFirstChild(), configElem); status = true; } Element formsElem = XmlUtils.findFirstElement("forms", configElem); if (formsElem == null) { formsElem = configDocument.createElement("forms"); appendChild(configElem, formsElem); status = true; } String formXpath = formId.equals("") ? "form[not(@condition)]" : "form[@id='" + formId + "']"; Element formElem = XmlUtils.findFirstElement(formXpath, formsElem); if (newFormId != null && !newFormId.equals(formId) && formElem != null) { //formElem.getParentNode().removeChild(formElem); removeChild(formElem); formId = newFormId; formElem = null; status = true; } if (formElem == null) { formElem = configDocument.createElement("form"); manageAttribute(formElem, "id", formId); appendChild(formsElem, formElem); status = true; } FormConfigElement formConfig = (FormConfigElement) properties.get("form-config"); if (formConfig != null) { if (manageAttribute(formElem, "submission-url", formConfig.getSubmissionURL())) { status = true; } SyncStatus syncStatus = syncTemplateElement(formConfig.getViewTemplate(), "view-form", formElem, null); if (syncStatus.getElement() != null) { currentElem = syncStatus.getElement(); } if (syncStatus.isStatus()) { status = true; } syncStatus = syncTemplateElement(formConfig.getEditTemplate(), "edit-form", formElem, currentElem); if (syncStatus.getElement() != null) { currentElem = syncStatus.getElement(); } if (syncStatus.isStatus()) { status = true; } syncStatus = syncTemplateElement(formConfig.getCreateTemplate(), "create-form", formElem, currentElem); if (syncStatus.getElement() != null) { currentElem = syncStatus.getElement(); } if (syncStatus.isStatus()) { status = true; } Element visibilityInstructionElem = XmlUtils.findFirstElement("field-visibility", formElem); if (visibilityInstructionElem == null) { visibilityInstructionElem = configDocument.createElement("field-visibility"); insertChildAfter(formElem, visibilityInstructionElem, currentElem); currentElem = visibilityInstructionElem; status = true; } if (properties.containsKey("visibility-instructions") && properties .get("visibility-instructions") instanceof FieldVisibilityInstructionCustom[]) { FieldVisibilityInstructionCustom[] visibilityInstructions = (FieldVisibilityInstructionCustom[]) (properties .get("visibility-instructions")); boolean visibilityChanged = false; if (visibilityInstructions.length != visibilityInstructionElem.getChildNodes() .getLength()) { visibilityChanged = true; } else { for (FieldVisibilityInstruction fieldVisibilityInstruction : visibilityInstructions) { String fieldVisibilityXpath = fieldVisibilityInstruction.getShowOrHide() .equals(Visibility.SHOW) ? "show" : "hide"; fieldVisibilityXpath += "[@id='" + fieldVisibilityInstruction.getFieldId() + "'"; if (fieldVisibilityInstruction.getModes() != null) { if (fieldVisibilityInstruction.getModes().size() != Mode.values().length) { fieldVisibilityXpath += " and @for-mode='"; for (int i = 0; i < fieldVisibilityInstruction.getModes().size() - 1; i++) { fieldVisibilityXpath += fieldVisibilityInstruction.getModes().get(i) .toString() + ","; } fieldVisibilityXpath += fieldVisibilityInstruction.getModes() .get(fieldVisibilityInstruction.getModes().size() - 1) .toString() + "'"; } if (formConfig.getForcedFields() != null) { if (formConfig.getForcedFieldsAsList() .contains(fieldVisibilityInstruction.getFieldId())) { fieldVisibilityXpath += " and @force='true'"; } } } fieldVisibilityXpath += "]"; Element fieldVisibilityElem = XmlUtils.findFirstElement(fieldVisibilityXpath, visibilityInstructionElem); if (fieldVisibilityElem == null) { visibilityChanged = true; } } } if (visibilityChanged) { while (visibilityInstructionElem.getChildNodes().getLength() > 0) { //visibilityInstructionElem.getFirstChild().getParentNode().removeChild(visibilityInstructionElem.getFirstChild()); removeChild(visibilityInstructionElem.getFirstChild()); } for (FieldVisibilityInstructionCustom fieldVisibilityInstruction : visibilityInstructions) { String fieldVisibility = fieldVisibilityInstruction.getShowOrHide() .equals(Visibility.SHOW) ? "show" : "hide"; String fieldId = fieldVisibilityInstruction.getFieldId(); Element fieldVisibilityElem = configDocument.createElement(fieldVisibility); manageAttribute(fieldVisibilityElem, "id", fieldId); if (fieldVisibilityInstruction.getModes() != null) { if (fieldVisibilityInstruction.getModes().size() != Mode.values().length) { String fieldVisibilityMode = ""; for (int i = 0; i < fieldVisibilityInstruction.getModes().size() - 1; i++) { fieldVisibilityMode += fieldVisibilityInstruction.getModes().get(i) .toString() + ","; } fieldVisibilityMode += fieldVisibilityInstruction.getModes() .get(fieldVisibilityInstruction.getModes().size() - 1) .toString(); manageAttribute(fieldVisibilityElem, "for-mode", fieldVisibilityMode); } if (formConfig.getForcedFields() != null) { if (formConfig.getForcedFieldsAsList() .contains(fieldVisibilityInstruction.getFieldId())) { manageAttribute(fieldVisibilityElem, "for-mode", "true"); } } } manageAttribute(fieldVisibilityElem, "force", fieldVisibilityInstruction.getForce()); appendChild(visibilityInstructionElem, fieldVisibilityElem); } } } Element appearanceElem = XmlUtils.findFirstElement("appearance", formElem); if (appearanceElem == null) { appearanceElem = configDocument.createElement("appearance"); insertChildAfter(formElem, appearanceElem, currentElem); status = true; } Map<String, FormSet> sets = formConfig.getSets(); boolean setChanged = false; if (XmlUtils.findElements("set", appearanceElem).size() != sets.size() - 1) { setChanged = true; } else { for (Element fieldElement : XmlUtils.findElements("set", appearanceElem)) { if (!sets.keySet().contains(fieldElement.getAttribute("id"))) { setChanged = true; } } } if (setChanged) { for (Element setElement : XmlUtils.findElements("set", appearanceElem)) { //setElement.getParentNode().removeChild(setElement); removeChild(setElement); } status = true; } // now sync individual set element Element currentAppearanceElem = null; for (FormSet formSet : sets.values()) { String setId = formSet.getSetId(); if (!setId.equals("")) { Element setElement = XmlUtils.findFirstElement("set[@id='" + setId + "']", appearanceElem); if (setElement == null) { setElement = configDocument.createElement("set"); insertChildAfter(appearanceElem, setElement, currentAppearanceElem); } if (this.manageAttribute(setElement, "id", setId)) { status = true; } if (this.manageAttribute(setElement, "parent", formSet.getParentId())) { status = true; } if (this.manageAttribute(setElement, "label", formSet.getLabel())) { status = true; } if (this.manageAttribute(setElement, "label-id", formSet.getLabelId())) { status = true; } if (this.manageAttribute(setElement, "appearance", formSet.getAppearance())) { status = true; } if (this.manageAttribute(setElement, "template", formSet.getTemplate())) { status = true; } List<Element> setElems = XmlUtils.findElements("set", appearanceElem); currentAppearanceElem = setElems.get(setElems.size() - 1); } } Map<String, FormField> fields = formConfig.getFields(); int appearanceCounter = 0; for (FormField formField : fields.values()) { if (formField.getAttributes() != null) { appearanceCounter++; } } boolean fieldChanged = false; if (XmlUtils.findElements("field", appearanceElem).size() != appearanceCounter) { fieldChanged = true; } else { for (Element fieldElement : XmlUtils.findElements("field", appearanceElem)) { if (!fields.keySet().contains(fieldElement.getAttribute("id"))) { fieldChanged = true; } } if (!fieldChanged) { for (FormField formField : fields.values()) { if (formField.getAttributes() != null && isFieldChanged(appearanceElem, formField)) { fieldChanged = true; } } } } if (fieldChanged) { for (Element fieldElement : XmlUtils.findElements("field", appearanceElem)) { //fieldElement.getParentNode().removeChild(fieldElement); removeChild(fieldElement); } status = true; // now sync individual field element for (FormField formField : fields.values()) { if (formField.getAttributes() != null && !formField.getAttributes().isEmpty() && isFieldChanged(appearanceElem, formField)) { String formFieldId = formField.getId(); Element fieldElement = XmlUtils .findFirstElement("field[@id='" + formFieldId + "']", appearanceElem); if (fieldElement == null) { fieldElement = configDocument.createElement("field"); manageAttribute(fieldElement, "id", formFieldId); for (String key : formField.getAttributes().keySet()) { manageAttribute(fieldElement, key, formField.getAttributes().get(key)); } if (formField.getControl() != null) { Control control = formField.getControl(); Element controlElement = configDocument.createElement("control"); manageAttribute(controlElement, "template", control.getTemplate()); if (control.getParams() != null) { for (ControlParam param : control.getParams()) { Element paramElement = configDocument .createElement("control-param"); manageAttribute(paramElement, "name", param.getName()); paramElement.setTextContent(param.getValue()); appendChild(controlElement, paramElement); } } appendChild(fieldElement, controlElement); } if (formField.getConstraintDefinitionMap() != null) { Element constraintsElement = configDocument .createElement("constraint-handlers"); Map<String, ConstraintHandlerDefinition> constraints = formField .getConstraintDefinitionMap(); for (String constraintId : constraints.keySet()) { ConstraintHandlerDefinition constraint = constraints .get(constraintId); Element constraintElement = configDocument .createElement("constraint"); manageAttribute(constraintElement, "type", constraint.getType()); manageAttribute(constraintElement, "event", constraint.getEvent()); manageAttribute(constraintElement, "message", constraint.getMessage()); manageAttribute(constraintElement, "message-id", constraint.getMessageId()); manageAttribute(constraintElement, "validation-handler", constraint.getValidationHandler()); appendChild(constraintsElement, constraintElement); } appendChild(fieldElement, constraintsElement); } insertChildAfter(appearanceElem, fieldElement, currentAppearanceElem); currentAppearanceElem = fieldElement; } } } } } } } } return status; }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
protected Document getMenuItem(User user, int key, int tagItem, boolean withParents, boolean complete, boolean includePageConfig, boolean withChildren, boolean includeHidden, boolean includeTypeSpecificXML, boolean tagItems, int levels) { Document doc = XMLTool.createDocument("menuitems"); Element rootElement = doc.getDocumentElement(); Connection con = null;/*from w w w . jav a2 s. c o m*/ PreparedStatement preparedStmt = null; ResultSet resultSet = null; try { con = getConnection(); String sql = getSecurityHandler().appendMenuItemSQL(user, MENU_ITEM_SELECT_BY_KEY, null); preparedStmt = con.prepareStatement(sql); preparedStmt.setInt(1, key); resultSet = preparedStmt.executeQuery(); if (!withChildren) { if (resultSet.next()) { buildMenuItemXML(doc, rootElement, resultSet, tagItem, complete, includePageConfig, includeHidden, includeTypeSpecificXML, tagItems, levels); } // include parents? if (withParents) { // yep. call getMenuItemDOM recursivly. Element menuItemElement = (Element) doc.getDocumentElement().getFirstChild(); String tmp = menuItemElement.getAttribute("parent"); while (tmp != null && tmp.length() > 0) { // get the parent: doc = getMenuItem(user, Integer.parseInt(tmp), false, false, false); // move the child inside the parent: rootElement = doc.getDocumentElement(); Element parentElement = (Element) rootElement.getFirstChild(); Element menuItemsElement = XMLTool.createElement(doc, parentElement, "menuitems"); menuItemsElement.appendChild(doc.importNode(menuItemElement, true)); menuItemElement = parentElement; tmp = menuItemElement.getAttribute("parent"); } } } else { buildMenuItemsXML(user, resultSet, doc, rootElement, levels, tagItem, complete, includePageConfig, includeHidden, includeTypeSpecificXML, tagItems); } } catch (SQLException sqle) { VerticalEngineLogger.error(this.getClass(), 30, "SQL error.", sqle); } finally { close(resultSet); close(preparedStmt); close(con); } return doc; }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
protected Document getMenuItem(User user, int key, boolean withParents, boolean complete, boolean includePageConfig, boolean withChildren) { Document doc;//from w w w . ja v a 2 s .c o m Element rootElement; doc = XMLTool.createDocument("menuitems"); rootElement = doc.getDocumentElement(); Connection con = null; PreparedStatement preparedStmt = null; ResultSet resultSet = null; try { con = getConnection(); preparedStmt = con .prepareStatement(getSecurityHandler().appendMenuItemSQL(user, MENU_ITEM_SELECT_BY_KEY)); preparedStmt.setInt(1, key); resultSet = preparedStmt.executeQuery(); if (!withChildren) { if (resultSet.next()) { buildMenuItemXML(doc, rootElement, resultSet, -1, complete, includePageConfig, true, true, true, -1); } // include parents? if (withParents) { // yep. call getMenuItemDOM recursivly. Element menuItemElement = (Element) doc.getDocumentElement().getFirstChild(); if (menuItemElement.hasAttribute("parent")) { int parentKey = Integer.valueOf(menuItemElement.getAttribute("parent")); while (parentKey >= 0) { // get the parent: doc = getMenuItem(user, parentKey, false, false, false); // move the child inside the parent: rootElement = doc.getDocumentElement(); Element parentElement = (Element) rootElement.getFirstChild(); if (parentElement != null) { Element menuItemsElement = XMLTool.createElement(doc, parentElement, "menuitems"); menuItemsElement.appendChild(doc.importNode(menuItemElement, true)); menuItemElement = parentElement; if (menuItemElement.hasAttribute("parent")) { parentKey = Integer.valueOf(menuItemElement.getAttribute("parent")); } else { parentKey = -1; } } else { parentKey = -1; } } } } } else { buildMenuItemsXML(user, resultSet, doc, rootElement, -1, -1, complete, includePageConfig, true, true, true); } } catch (SQLException sqle) { VerticalEngineLogger.error(this.getClass(), 30, "SQL error.", sqle); } finally { close(resultSet); close(preparedStmt); close(con); } return doc; }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
private Hashtable<String, Element> appendMenuItemsBySettings(User user, Document doc, Hashtable<String, Element> hashtable_menus, MenuGetterSettings getterSettings) { Hashtable<String, Element> hashtable_MenuItems = new Hashtable<String, Element>(); List<Integer> paramValues = new ArrayList<Integer>(2); StringBuffer sqlMenuItems = new StringBuffer(MENU_ITEM_SELECT); // menuKey// w w w.ja v a 2 s . c om MenuItemCriteria criteria = getterSettings.getMenuItemCriteria(); if (getterSettings.hasMenuKeys() || criteria.hasMenuKey()) { if (getterSettings.hasMenuKeys()) { int[] menuKeys = getterSettings.getMenuKeys(); sqlMenuItems.append(" AND men_lKey IN ("); for (int i = 0; i < menuKeys.length; i++) { if (i > 0) { sqlMenuItems.append(','); } sqlMenuItems.append(menuKeys[i]); } sqlMenuItems.append(')'); } else { sqlMenuItems.append(" AND mei_men_lKey = ?"); paramValues.add(criteria.getMenuKeyAsInteger()); } } // only root menuitems if (getterSettings.getOnlyRootMenuItems()) { sqlMenuItems.append(" AND mei_lParent IS NULL"); } if (user != null) { getSecurityHandler().appendMenuItemSQL(user, sqlMenuItems, criteria); } sqlMenuItems.append(ORDER_BY); Connection con = null; PreparedStatement statement = null; ResultSet resultSet = null; Element element_AdminReadMenuItems = doc.getDocumentElement(); try { con = getConnection(); statement = con.prepareStatement(sqlMenuItems.toString()); int i = 1; for (Iterator<Integer> iter = paramValues.iterator(); iter.hasNext(); i++) { Object paramValue = iter.next(); statement.setObject(i, paramValue); } try { // Hender ut menuitems resultSet = statement.executeQuery(); while (resultSet.next()) { int curMenuItemKey = resultSet.getInt("mei_lKey"); Element menuItem = buildMenuItemXML(doc, element_AdminReadMenuItems, resultSet, -1, false, false, true, true, false, 1); Element accessRights = XMLTool.createElement(doc, menuItem, "accessrights"); getSecurityHandler().appendAccessRightsOnMenuItem(user, curMenuItemKey, accessRights, true); XMLTool.createElement(doc, menuItem, "menuitems"); // Lagrer referansen til kategori-elementet for raskt oppslag til senere bruk hashtable_MenuItems.put(String.valueOf(curMenuItemKey), menuItem); } } finally { close(resultSet); resultSet = null; close(statement); statement = null; } // Gr igjennom menuitems og bygger opp trestrukturen Element curAdminReadMenuItem = (Element) element_AdminReadMenuItems.getFirstChild(); while (curAdminReadMenuItem != null) { String parentKey = curAdminReadMenuItem.getAttribute("parent"); Element nextElement = (Element) curAdminReadMenuItem.getNextSibling(); // Forelder node finnes ikke fra fr if ("menuitem".equals(curAdminReadMenuItem.getNodeName())) { insertParentMenuItem(user, MENU_ITEM_SELECT_BY_KEY, doc, element_AdminReadMenuItems, hashtable_menus, hashtable_MenuItems, curAdminReadMenuItem, parentKey); } curAdminReadMenuItem = nextElement; } } catch (SQLException sqle) { String message = "Failed to get menuitems: %t"; VerticalEngineLogger.error(this.getClass(), 0, message, sqle); } finally { close(resultSet); close(statement); close(con); } return hashtable_MenuItems; }
From source file:com.icesoft.faces.context.DOMResponseWriter.java
private void enhanceBody(Element body) { //id required for forwarded (server-side) redirects body.setAttribute("id", "document:body"); // TODO This is only meant to be a transitional focus retention(management) solution. String focusId = context.getFocusId(); if (focusId != null && !focusId.equals("null")) { JavascriptContext.focus(context, focusId); }/* www . j av a2s . c om*/ ExternalContext externalContext = context.getExternalContext(); ViewHandler handler = context.getApplication().getViewHandler(); String sessionIdentifier = context.getIceFacesId(); String viewIdentifier = context.getViewNumber(); String prefix = sessionIdentifier + ':' + viewIdentifier + ':'; Element script = (Element) body.appendChild(document.createElement("script")); script.setAttribute("id", prefix + "dynamic-code"); script.setAttribute("type", "text/javascript"); String calls = JavascriptContext.getJavascriptCalls(context); script.appendChild(document.createTextNode(calls)); String contextPath = handler.getResourceURL(context, "/"); if (blockingRequestHandlerContext == null) { //ICE-3784 //Only need to strip leading and trailing slashes. Removing all slashes //will cause problems with contexts that actually contain slashes e.g /myapp/mysubapp. String normalizedPath = contextPath; if (normalizedPath.length() > 0) { if (normalizedPath.charAt(0) == '/') { normalizedPath = normalizedPath.substring(1); } if (normalizedPath.length() > 0) { if (normalizedPath.charAt(normalizedPath.length() - 1) == '/') { normalizedPath = normalizedPath.substring(0, normalizedPath.length() - 1); } } } blockingRequestHandlerContext = URI.create("/").resolve(normalizedPath + "/").toString(); } String connectionLostRedirectURI; try { String uri = configuration.getAttribute("connectionLostRedirectURI"); connectionLostRedirectURI = "'" + handler.getResourceURL(context, uri.replaceAll("'", "")) + "'"; } catch (ConfigurationException e) { connectionLostRedirectURI = "null"; } String sessionExpiredRedirectURI; try { String uri = configuration.getAttribute("sessionExpiredRedirectURI"); sessionExpiredRedirectURI = "'" + handler.getResourceURL(context, uri.replaceAll("'", "")) + "'"; } catch (ConfigurationException e) { sessionExpiredRedirectURI = "null"; } String configurationID = prefix + "configuration-script"; //add viewIdentifier property to the container element ("body" for servlet env., any element for the portlet env.) ResourceBundle localizedBundle = bridgeMessageResolver.bundleFor(context.getViewRoot().getLocale()); //todo: build startup script only once on aplication startup boolean synchronousMode = configuration.getAttributeAsBoolean("synchronousUpdate", false); String startupScript = "window.disposeViewsURI = '" + blockingRequestHandlerContext + "block/dispose-views';\n" + "var container = '" + configurationID + "'.asElement().parentNode;\n" + "container.bridge = new Ice.Community.Application({" + "blockUI: " + configuration.getAttribute("blockUIOnSubmit", "false") + "," + "session: '" + sessionIdentifier + "'," + "view: " + viewIdentifier + "," + "synchronous: " + synchronousMode + "," + "connectionLostRedirectURI: " + connectionLostRedirectURI + "," + "sessionExpiredRedirectURI: " + sessionExpiredRedirectURI + "," + "serverErrorRetryTimeouts: [" + configuration .getAttribute("serverErrorRetryTimeouts", "1000 2000 4000").trim().replaceAll("\\s+", ",") + "], " + "connection: {" + "context: '" + contextPath + "', " + (synchronousMode ? //encode path for URL rewrite session tracking mode ("sendReceiveUpdatesURI: '" + externalContext.encodeResourceURL(contextPath + "block/send-receive-updates") + "',") : ("sendReceiveUpdatesURI: '" + contextPath + "block/send-receive-updates" + "'," + "pingURI: '" + contextPath + "block/ping" + "'," + "receiveUpdatesURI: '" + contextPath + "block/receive-updates" + "'," + "receiveUpdatedViewsURI: '" + blockingRequestHandlerContext + "block/receive-updated-views" + "',") + "heartbeat: {" + "interval: " + configuration.getAttributeAsLong("heartbeatInterval", 50000) + "," + "timeout: " + configuration.getAttributeAsLong("heartbeatTimeout", 30000) + "," + "retries: " + configuration.getAttributeAsLong("heartbeatRetries", 3) + "},") + "timeout: " + configuration.getAttributeAsLong("connectionTimeout", 60000) + "}," + "messages: {" + "sessionExpired: '" + localizedBundle.getString("session-expired") + "'," + "connectionLost: '" + localizedBundle.getString("connection-lost") + "'," + "serverError: '" + localizedBundle.getString("server-error") + "'," + "description: '" + localizedBundle.getString("description") + "'," + "buttonText: '" + localizedBundle.getString("button-text") + "'" + "}" + "}, container);"; Element configurationElement = (Element) body.appendChild(document.createElement("script")); configurationElement.setAttribute("id", configurationID); configurationElement.setAttribute("type", "text/javascript"); configurationElement.appendChild(document.createTextNode(startupScript)); body.insertBefore(configurationElement, body.getFirstChild()); Element iframe = document.createElement("iframe"); body.insertBefore(iframe, body.getFirstChild()); String iframeID = "history-frame:" + sessionIdentifier + ":" + viewIdentifier; iframe.setAttribute("id", iframeID); iframe.setAttribute("name", iframeID); Object request = externalContext.getRequest(); final String frameURI; //another "workaround" to resolve the iframe URI if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getRequestURI() == null) { frameURI = "about:blank"; } else { frameURI = CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank"); } } else { frameURI = CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank"); // ICE-2553 } iframe.setAttribute("title", "Icefaces Redirect"); iframe.setAttribute("src", frameURI); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("style", "z-index: 10000; visibility: hidden; width: 0; height: 0; position: absolute; opacity: 0.22; filter: alpha(opacity=22);"); if (checkJavaScript) { Element noscript = (Element) body.appendChild(document.createElement("noscript")); Element noscriptMeta = (Element) noscript.appendChild(document.createElement("meta")); noscriptMeta.setAttribute("http-equiv", "refresh"); noscriptMeta.setAttribute("content", "0;url=" + handler.getResourceURL(context, "/xmlhttp/javascript-blocked")); } if (context.isContentIncluded()) { Element element = (Element) body.insertBefore(document.createElement("div"), configurationElement); element.setAttribute("style", "display: none;"); //id added so the conditional rendering of the components under the portlet, //won't send the body level update element.setAttribute("id", "cntIncDiv"); appendContentReferences(element); } }
From source file:com.amalto.workbench.providers.XSDTreeLabelProvider.java
@Override public String getText(Object obj) { // log.info("getText "+obj.getClass().getName()); if (obj instanceof XSDElementDeclaration) { String name = ((XSDElementDeclaration) obj).getName(); if (((XSDElementDeclaration) obj).isAbstract()) { name += Messages.XSDTreeLabelProvider_0; }// www . j a va 2 s .c o m String tail = ((XSDElementDeclaration) obj).getTargetNamespace() != null ? " : "//$NON-NLS-1$ + ((XSDElementDeclaration) obj).getTargetNamespace() : "";//$NON-NLS-1$ return name + tail; } if (obj instanceof XSDParticle) { XSDParticle xsdParticle = (XSDParticle) obj; XSDParticleContent content = xsdParticle.getContent(); XSDTerm xsdTerm = xsdParticle.getTerm(); String name = "";//$NON-NLS-1$ if (content instanceof XSDElementDeclaration) { XSDElementDeclaration decl = (XSDElementDeclaration) content; name += (decl.getName() == null ? "" : decl.getName());//$NON-NLS-1$ if (decl.getTypeDefinition() == null) { name += " [" + ((XSDElementDeclaration) xsdTerm).getName() + "]";//$NON-NLS-1$//$NON-NLS-2$ } } else if (content instanceof XSDModelGroup) { // log.info("SHOULD NOT HAPPEN????"); if (xsdParticle.getContainer() instanceof XSDComplexTypeDefinition) { String ctdName = ((XSDComplexTypeDefinition) xsdParticle.getContainer()).getName(); name = (ctdName != null ? ctdName : "");//$NON-NLS-1$ } } else { name = "[Any]";//$NON-NLS-1$ } if (!((xsdParticle.getMinOccurs() == 1) && (xsdParticle.getMaxOccurs() == 1))) { name += " [";//$NON-NLS-1$ name += xsdParticle.getMinOccurs(); name += "...";//$NON-NLS-1$ name += (xsdParticle.getMaxOccurs() == -1) ? "many" : "" + xsdParticle.getMaxOccurs();//$NON-NLS-1$//$NON-NLS-2$ name += "]";//$NON-NLS-1$ } return name; } if (obj instanceof XSDSimpleTypeDefinition) { return getSimpleTypeDefinition((XSDSimpleTypeDefinition) obj); } if (obj instanceof XSDModelGroup) { // return the name of the complex type definition XSDParticle particle = (XSDParticle) (((XSDModelGroup) obj).getContainer()); XSDComplexTypeDefinition complexTypeDefinition = (XSDComplexTypeDefinition) particle.getContainer(); String name = complexTypeDefinition.getName(); if (name == null) { name = "anonymous type ";//$NON-NLS-1$ } // return the occurrence if (!((particle.getMinOccurs() == 1) && (particle.getMaxOccurs() == 1))) { name += " [";//$NON-NLS-1$ name += particle.getMinOccurs(); name += "...";//$NON-NLS-1$ name += (particle.getMaxOccurs() == -1) ? "many" : "" + particle.getMaxOccurs();//$NON-NLS-1$//$NON-NLS-2$ name += "]";//$NON-NLS-1$ } // get extend type XSDTypeDefinition extendType = complexTypeDefinition.getBaseTypeDefinition(); String extendTypeName = ""; //$NON-NLS-1$ if (extendType != null && extendType != complexTypeDefinition && !"anyType".equals(extendType.getName())) { //$NON-NLS-1$ extendTypeName = ":" + extendType.getName(); //$NON-NLS-1$ } XSDSchema schema = particle.getSchema(); String tail = ""; //$NON-NLS-1$ if (schema != null && schema.getTargetNamespace() != null) { tail = " : "//$NON-NLS-1$ + schema.getTargetNamespace(); } return name + tail + extendTypeName; } if (obj instanceof XSDFacet) { return ((XSDFacet) obj).getFacetName() + ": " + ((XSDFacet) obj).getLexicalValue();//$NON-NLS-1$ } if (obj instanceof XSDIdentityConstraintDefinition) { return ((XSDIdentityConstraintDefinition) obj).getName(); } if (obj instanceof XSDXPathDefinition) { XSDXPathDefinition xpath = (XSDXPathDefinition) obj; return xpath.getValue(); } if (obj instanceof XSDAttributeGroupDefinition) { XSDAttributeGroupDefinition attributeGroupDefinition = (XSDAttributeGroupDefinition) obj; String name = (attributeGroupDefinition.getName() == null ? "" : attributeGroupDefinition.getName());//$NON-NLS-1$ if (attributeGroupDefinition.getContents().size() == 0) { name += " [" + attributeGroupDefinition.getResolvedAttributeGroupDefinition().getName() + "]";//$NON-NLS-1$//$NON-NLS-2$ } return name; } if (obj instanceof XSDAttributeUse) { XSDAttributeUse attributeUse = (XSDAttributeUse) obj; String name = attributeUse.getAttributeDeclaration().getName(); if (name == null) { name = " [" + attributeUse.getAttributeDeclaration().getResolvedAttributeDeclaration().getName() //$NON-NLS-1$ + "]";//$NON-NLS-1$ } return name; } if (obj instanceof XSDAttributeDeclaration) { XSDAttributeDeclaration attributeDec = (XSDAttributeDeclaration) obj; String name = attributeDec.getName(); if (name == null) { name = attributeDec.getAliasName(); if (name == null) { name = " [null]"; //$NON-NLS-1$ } } return name; } if (obj instanceof XSDAnnotation) { // XSDAnnotation annotation = (XSDAnnotation) obj; return "Annotations";//$NON-NLS-1$ } if (obj instanceof Element) { try { Element e = (Element) obj; if (e.getLocalName().equals("documentation")) {//$NON-NLS-1$ return "Documentation: " + e.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$ } else if (e.getLocalName().equals("appinfo")) {//$NON-NLS-1$ String source = e.getAttribute("source");//$NON-NLS-1$ if (source != null) { if (source.startsWith("X_Label_")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_1, Util.iso2lang.get(source.substring(8).toLowerCase()), e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_ForeignKey")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_2, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_ForeignKey_NotSep")) {//$NON-NLS-1$ Boolean v = Boolean.valueOf(e.getChildNodes().item(0).getNodeValue()); return Messages.bind(Messages.XSDTreeLabelProvider_3, Messages.SimpleXpathInputDialog_sepFkTabPanel, v); } else if (source.equals("X_Visible_Rule")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_4, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Default_Value_Rule")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_5, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_ForeignKeyInfo")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_6, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_ForeignKeyInfoFormat")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_20, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_PrimaryKeyInfo")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_7, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_SourceSystem")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_8, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_TargetSystem")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_9, e.getChildNodes().item(0).getNodeValue()); } else if (source.startsWith("X_Description_")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_10, Util.iso2lang.get(source.substring(14).toLowerCase()), e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Write")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_11, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Deny_Create")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_12, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Deny_LogicalDelete")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_13, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Deny_PhysicalDelete")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_14, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Lookup_Field")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_15, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Workflow")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_16, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_Hide")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_17, e.getChildNodes().item(0).getNodeValue()); // add by ymli; bugId 0009157 } else if (source.equals("X_AutoExpand")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_18, e.getChildNodes().item(0).getNodeValue()); } else if (source.startsWith("X_Facet")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_19, source.substring(2, 7), source.substring(8), e.getChildNodes().item(0).getNodeValue()); // made schematron show:Schematron: schematron } else if (source.startsWith("X_Display_Format_")) {//$NON-NLS-1$ return source + ": " + e.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$ } else if (source.equals("X_Schematron")) {//$NON-NLS-1$ String pattern = (String) e.getFirstChild().getUserData("pattern_name");//$NON-NLS-1$ if (pattern == null) { Element el = Util.parse(e.getChildNodes().item(0).getNodeValue()) .getDocumentElement(); if (el.getAttributes().getNamedItem("name") != null) { //$NON-NLS-1$ pattern = el.getAttributes().getNamedItem("name").getTextContent();//$NON-NLS-1$ } } return Messages.bind(Messages.XSDTreeLabelProvider_21, (pattern == null ? Messages.XSDTreeLabelProvider_22 : pattern));// e.getChildNodes().item(0).getNodeValue(); // end } else if (source.equals("X_Retrieve_FKinfos")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_23, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_FKIntegrity")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_24, e.getChildNodes().item(0).getNodeValue()); } else if (source.equals("X_FKIntegrity_Override")) {//$NON-NLS-1$ return Messages.bind(Messages.XSDTreeLabelProvider_25, e.getChildNodes().item(0).getNodeValue()); } if (source.equals("X_ForeignKey_Filter")) {//$NON-NLS-1$ String nodeValue = e.getChildNodes().item(0).getNodeValue(); if (nodeValue.startsWith("$CFFP:")) {//$NON-NLS-1$ nodeValue = StringEscapeUtils.unescapeXml(nodeValue).substring(6); } return Messages.bind(Messages.XSDTreeLabelProvider_26, nodeValue); } else { return source + ": " + Util.nodeToString((Element) obj);//$NON-NLS-1$ } } else { return Util.nodeToString((Element) obj); } } else { return Util.nodeToString((Element) obj); } } catch (Exception e) { log.error(e.getMessage(), e); } } if (obj == null) { return "NULL";//$NON-NLS-1$ } return "?? " + obj.getClass().getName() + " : " + obj.toString();//$NON-NLS-1$//$NON-NLS-2$ }
From source file:com.portfolio.data.provider.MysqlDataProvider.java
@Override public String postRRGCreate(int userId, String portfolio, String data) { if (!credential.isAdmin(userId) && !credential.isOwner(userId, portfolio)) throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right"); String value = "erreur"; /// Parse data DocumentBuilder documentBuilder; Document document = null;/* w ww. ja va 2 s. c o m*/ try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(data)); document = documentBuilder.parse(is); } catch (Exception e) { e.printStackTrace(); } /// Problme de parsage if (document == null) return value; try { connection.setAutoCommit(false); Element labelNode = document.getDocumentElement(); String label = null; // NodeList rrgNodes = document.getElementsByTagName("rolerightsgroup"); String sqlRRG = "INSERT INTO group_right_info(owner,label,portfolio_id) VALUES(?,?,uuid2bin(?))"; PreparedStatement rrgst = connection.prepareStatement(sqlRRG, Statement.RETURN_GENERATED_KEYS); if (dbserveur.equals("oracle")) { rrgst = connection.prepareStatement(sqlRRG, new String[] { "grid" }); } rrgst.setInt(1, userId); // String sqlGU = "INSERT INTO group_info(grid,owner,label) VALUES(?,?,?)"; // PreparedStatement gust = connection.prepareStatement(sqlGU); // gust.setInt(2, userId); if (labelNode != null) { Node labelText = labelNode.getFirstChild(); if (labelText != null) label = labelText.getNodeValue(); } if (label == null) return value; /// Cration du groupe de droit rrgst.setString(2, label); rrgst.setString(3, portfolio); rrgst.executeUpdate(); ResultSet rs = rrgst.getGeneratedKeys(); Integer grid = 0; if (rs.next()) grid = rs.getInt(1); rrgst.close(); labelNode.setAttribute("id", Integer.toString(grid)); /// Rcupre les donnes avec identifiant mis--jour StringWriter stw = new StringWriter(); Transformer serializer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(document); StreamResult stream = new StreamResult(stw); serializer.transform(source, stream); value = stw.toString(); } catch (Exception e) { try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { connection.setAutoCommit(true); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return value; }