List of usage examples for org.dom4j Document getRootElement
Element getRootElement();
From source file:com.doculibre.constellio.utils.xml.SolrShemaXmlReader.java
License:Open Source License
public static List<List<String>> readCopyFields(Document schemaDocument) { List<List<String>> returnList = new ArrayList<List<String>>(); if (schemaDocument != null) { List<Element> dynamicFieldsElement = schemaDocument.getRootElement().elements("copyField"); for (Element elem : dynamicFieldsElement) { List<String> currentCopyField = new ArrayList<String>(); String source = elem.attributeValue("source"); currentCopyField.add(source); String destination = elem.attributeValue("dest"); currentCopyField.add(destination); String maxChars = elem.attributeValue("maxChars"); if (maxChars != null) { currentCopyField.add(maxChars); }/*from w w w.j a v a 2 s . c om*/ returnList.add(currentCopyField); } } return returnList; }
From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java
License:Open Source License
public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) { super(id);/* w ww .j a v a2s . c o m*/ RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices(); RecordServices recordServices = ConstellioSpringUtils.getRecordServices(); SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils .getSearchInterfaceConfigServices(); String collectionName = dataProvider.getSimpleSearch().getCollectionName(); RecordCollection collection = collectionServices.get(collectionName); Record record = recordServices.get(doc); if (record != null) { SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get(); IndexField uniqueKeyField = collection.getUniqueKeyIndexField(); IndexField defaultSearchField = collection.getDefaultSearchIndexField(); IndexField urlField = collection.getUrlIndexField(); IndexField titleField = collection.getTitleIndexField(); if (urlField == null) { urlField = uniqueKeyField; } if (titleField == null) { titleField = urlField; } final String recordURL = record.getUrl(); final String displayURL; if (record.getDisplayUrl().startsWith("/get?file=")) { HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest(); displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl(); } else { displayURL = record.getDisplayUrl(); } String title = record.getDisplayTitle(); final String protocol = StringUtils.substringBefore(displayURL, ":"); boolean linkEnabled = isLinkEnabled(protocol); // rcupration des champs highlight partir de la cl unique // du document, dans le cas de Nutch c'est l'URL QueryResponse response = dataProvider.getQueryResponse(); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL); String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting); if (titleHighlight != null) { title = titleHighlight; } String excerpt = null; String description = getDescription(record); String summary = getSummary(record); if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) { excerpt = description; } else { excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting); if (excerpt == null) { excerpt = description; } } toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink"); add(toggleSummaryLink); toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary)); toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() { @Override protected Object load() { return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')"; } })); summaryLabel = new Label("summary", summary); add(summaryLabel); summaryLabel.setOutputMarkupId(true); summaryLabel.setVisible(StringUtils.isNotBlank(summary)); ExternalLink titleLink; if (displayURL.startsWith("file://")) { HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest(); String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?" + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "=" + collectionName; titleLink = new ExternalLink("titleLink", newDisplayURL); } else { titleLink = new ExternalLink("titleLink", displayURL); } final RecordModel recordModel = new RecordModel(record); AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true, new LoadableDetachableModel() { @Override protected Object load() { Record record = recordModel.getObject(); SimpleSearch simpleSearch = dataProvider.getSimpleSearch(); WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest(); HttpServletRequest httpRequest = webRequest.getHttpServletRequest(); return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch, record); } }); titleLink.add(computeClickAttributeModifier); titleLink.setEnabled(linkEnabled); boolean resultsInNewWindow; PageParameters params = RequestCycle.get().getPageParameters(); if (params != null && params.getString(POPUP_LINK) != null) { resultsInNewWindow = params.getBoolean(POPUP_LINK); } else { resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow(); } titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self")); // Add title title = StringUtils.remove(title, "\n"); title = StringUtils.remove(title, "\r"); if (StringUtils.isEmpty(title)) { title = StringUtils.defaultString(displayURL); title = StringUtils.substringAfterLast(title, "/"); title = StringUtils.substringBefore(title, "?"); try { title = URLDecoder.decode(title, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (title.length() > 120) { title = title.substring(0, 120) + " ..."; } } Label titleLabel = new Label("title", title); titleLink.add(titleLabel.setEscapeModelStrings(false)); add(titleLink); Label excerptLabel = new Label("excerpt", excerpt); add(excerptLabel.setEscapeModelStrings(false)); // add(new ExternalLink("url", url, // url).add(computeClickAttributeModifier).setEnabled(linkEnabled)); if (displayURL.startsWith("file://")) { // Creates a Windows path for file URLs String urlLabel = StringUtils.substringAfter(displayURL, "file:"); urlLabel = StringUtils.stripStart(urlLabel, "/"); urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\"); try { urlLabel = URLDecoder.decode(urlLabel, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } add(new Label("url", urlLabel)); } else { add(new Label("url", displayURL)); } final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>( collection); add(new ListView("searchResultFields", new LoadableDetachableModel() { @Override protected Object load() { RecordCollection collection = collectionModel.getObject(); return collection.getSearchResultFields(); } /** * Detaches from the current request. Implement this method with * custom behavior, such as setting the model object to null. */ protected void onDetach() { recordModel.detach(); collectionModel.detach(); } }) { @Override protected void populateItem(ListItem item) { SearchResultField searchResultField = (SearchResultField) item.getModelObject(); IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices(); Record record = recordModel.getObject(); IndexField indexField = searchResultField.getIndexField(); Locale locale = getLocale(); String indexFieldTitle = indexField.getTitle(locale); if (StringUtils.isBlank(indexFieldTitle)) { indexFieldTitle = indexField.getName(); } StringBuffer fieldValueSb = new StringBuffer(); List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField); Map<String, String> defaultLabelledValues = indexFieldServices .getDefaultLabelledValues(indexField, locale); for (Object fieldValue : fieldValues) { if (fieldValueSb.length() > 0) { fieldValueSb.append("\n"); } String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale); if (fieldValueLabel == null) { fieldValueLabel = defaultLabelledValues.get("" + fieldValue); } if (fieldValueLabel == null) { fieldValueLabel = "" + fieldValue; } fieldValueSb.append(fieldValueLabel); } item.add(new Label("indexField", indexFieldTitle)); item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString())); item.setVisible(fieldValueSb.length() > 0); } @SuppressWarnings("unchecked") @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject(); visible = !searchResultFields.isEmpty(); } return visible; } }); // md5 ConstellioSession session = ConstellioSession.get(); ConstellioUser user = session.getUser(); // TODO Provide access to unauthenticated users ? String md5 = ""; if (user != null) { IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo(); if (intelligidServiceInfo != null) { Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5); if (md5Coll != null) { for (Object md5Obj : md5Coll) { try { String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString()))); InputStream is = HttpClientHelper .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum", "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"), "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"), "password=" + URLEncoder.encode(Base64.encodeBase64String( ConstellioSession.get().getPassword().getBytes())), "ISO-8859-1"); try { Document xmlDocument = new SAXReader().read(is); Element root = xmlDocument.getRootElement(); for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) { Element fichier = it.next(); String url = fichier.attributeValue("url"); md5 += "<a href=\"" + url + "\">" + url + "</a> "; } } finally { IOUtils.closeQuietly(is); } } catch (Exception e) { e.printStackTrace(); } } } } } Label md5Label = new Label("md5", md5) { public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { visible = StringUtils.isNotBlank(this.getModelObjectAsString()); } return visible; } }; md5Label.setEscapeModelStrings(false); add(md5Label); add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch())); } else { setVisible(false); } }
From source file:com.dsh105.nexus.command.module.information.WolframAlphaCommand.java
License:Open Source License
@Override public boolean onCommand(CommandPerformEvent event) { if (event.getArgs().length == 0) { return false; }// ww w. j a v a 2 s . c o m String apiKey = Nexus.getInstance().getConfig().getWolframAlphaKey(); if (apiKey.isEmpty()) { event.errorWithPing("Failed to query WolframAlpha - API key has not been configured."); Nexus.LOGGER.warning("User attempted to access WolframAlpha - API key is invalid!"); return true; } String input = StringUtil.combineSplit(0, event.getArgs(), " "); StringBuilder answer = new StringBuilder(); try { String apiUrl = String.format(API_URL, URLEncoder.encode(input, "UTF-8"), apiKey); Nexus.LOGGER.info("Requesting WolframAlpha interpretation at " + apiUrl); SAXReader reader = new SAXReader(); Document document = reader.read(Unirest.get(apiUrl).asBinary().getBody()); Element root = document.getRootElement(); if (Boolean.valueOf(root.attribute("success").getValue())) { for (Iterator pods = root.elementIterator("pod"); pods.hasNext();) { Element pod = (Element) pods.next(); String primary = pod.attributeValue("primary"); if (primary != null && Boolean.valueOf(primary)) { for (Iterator subpods = pod.elementIterator("subpod"); subpods.hasNext();) { Element subpod = (Element) subpods.next(); String result = subpod.element("plaintext").getText(); if (result != null && !result.isEmpty()) { answer.append(result.replaceAll("\\n", " - ").replaceAll("\\s+", " ")); } } } } if (answer.length() > 0) { event.respondWithPing( answer + " (" + URLShortener.shorten(String.format(QUERY_URL, input)) + ")"); return true; } } List<String> tips = new ArrayList<>(); if (root.element("tips") != null) { for (Iterator tipElements = root.element("tips").elementIterator("tip"); tipElements.hasNext();) { if (tips.size() > 3) { break; } Element tip = (Element) tipElements.next(); String result = tip.attributeValue("text"); if (result != null && !result.isEmpty()) { tips.add(result.replaceAll("\\s+", " ")); } } } event.errorWithPing("WolframAlpha could not interpret that!"); if (!tips.isEmpty()) { event.errorWithPing(Colors.BOLD + "Tips" + Colors.BOLD + ": " + StringUtil.combineSplit(0, tips.toArray(new String[tips.size()]), "; ")); } return true; } catch (UnirestException e) { throw new WolframAlphaQueryException("Failed to execute WolframAlpha query: " + input, e); } catch (DocumentException e) { throw new WolframAlphaQueryException("Failed to execute WolframAlpha query: " + input, e); } catch (UnsupportedEncodingException e) { throw new WolframAlphaQueryException("Failed to encode URL", e); } }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Validate the response is in expected envlope form with <result> content. * * @param response response/* ww w . ja va 2 s . c o m*/ * * @throws com.dtolabs.client.services.CentralDispatcherServerRequestException * if the format is incorrect, or the Envelope indicates an error response. */ private void validateJobsResponse(final WebserviceResponse response) throws CentralDispatcherServerRequestException { if (null == response) { throw new CentralDispatcherServerRequestException("Response was null"); } if (null != response.getResponseMessage()) { logger.info("Response: " + response.getResponseMessage()); } final Document resultDoc = response.getResultDoc(); if (null == resultDoc) { throw new CentralDispatcherServerRequestException("Response content unexpectedly empty"); } try { logger.debug(serialize(resultDoc)); } catch (IOException e) { logger.debug("ioexception serializing result doc", e); } if (!"joblist".equals(resultDoc.getRootElement().getName())) { throw new CentralDispatcherServerRequestException("Response had unexpected content: " + resultDoc); } }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Validate the response is in expected envlope form with <result> content. * * @param response response//from ww w . j a va 2 s. c o m * * @throws com.dtolabs.rundeck.core.dispatcher.CentralDispatcherException * if the format is incorrect, or the Envelope indicates an error response. */ private void validResourceXMLResponse(final WebserviceResponse response) throws CentralDispatcherException { if (null == response) { throw new CentralDispatcherServerRequestException("Response was null"); } if (response.getResultCode() < 200 || response.getResultCode() >= 400) { throw new CentralDispatcherServerRequestException( "Response was not OK: " + response.getResultCode() + ": " + response.getResponseMessage()); } if (null != response.getResponseMessage()) { logger.debug("Response: " + response.getResponseMessage()); } final Document resultDoc = response.getResultDoc(); if (null == resultDoc) { throw new CentralDispatcherServerRequestException("Response content unexpectedly empty. " + (response.getResponseMessage() != null ? response.getResponseMessage() : "")); } try { logger.debug(serialize(resultDoc)); } catch (IOException e) { logger.debug("ioexception serializing result doc", e); } if (!"project".equals(resultDoc.getRootElement().getName())) { throw new CentralDispatcherServerRequestException( "Response had unexpected content: " + resultDoc.getRootElement().getName() + ": " + resultDoc); } }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Validate the response is in expected envlope form with <result> content. * * @param response response//from w w w .j a va2 s. c o m * * @return Envelope if format is correct and there is no error * * @throws com.dtolabs.rundeck.core.dispatcher.CentralDispatcherException * if the format is incorrect, or the Envelope indicates an error response. */ private Envelope validateResponse(final WebserviceResponse response) throws CentralDispatcherException { if (null == response) { throw new CentralDispatcherServerRequestException("Response was null"); } if (null != response.getResponseMessage()) { logger.debug("Response: " + response.getResponseMessage()); } final Document resultDoc = response.getResultDoc(); if (null == resultDoc) { throw new CentralDispatcherServerRequestException("Response content unexpectedly empty. " + (response.getResponseMessage() != null ? response.getResponseMessage() : "")); } try { logger.debug(serialize(resultDoc)); } catch (IOException e) { logger.debug("ioexception serializing result doc", e); } if (!"result".equals(resultDoc.getRootElement().getName())) { throw new CentralDispatcherServerRequestException( "Response had unexpected content: " + resultDoc.getRootElement().getName() + ": " + resultDoc); } final Envelope envelope = new Envelope(response.getResultDoc()); if (envelope.isErrorResult()) { final StringBuffer sb = new StringBuffer(); final StringBuffer buffer = envelope.errorMessages(); if (buffer.length() > 0) { sb.append(buffer); } else { sb.append("Server reported an error"); if (null != response.getResponseMessage()) { sb.append(": ").append(response.getResponseMessage()); } } if (null != response.getResponseMessage()) { logger.error("Server reported an error: " + response.getResponseMessage()); } else { logger.error("Server reported an error."); } throw new CentralDispatcherFailureResponseException(sb.toString()); } return envelope; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Check if the response is an API error response, if so throw an exception, otherwise return; * * @param response response// www. j ava 2s . c o m * * @throws com.dtolabs.rundeck.core.dispatcher.CentralDispatcherException * if the format is incorrect, or the Envelope indicates an error response. */ private void checkErrorResponse(final WebserviceResponse response) throws CentralDispatcherException { if (null == response) { throw new CentralDispatcherServerRequestException("Response was null"); } if (null != response.getResponseMessage()) { logger.info("Response: " + response.getResponseMessage()); } final Document resultDoc = response.getResultDoc(); if (null == resultDoc) { return; } try { logger.debug(serialize(resultDoc)); } catch (IOException e) { logger.debug("ioexception serializing result doc", e); } if (!"result".equals(resultDoc.getRootElement().getName())) { return; } final Envelope envelope = new Envelope(response.getResultDoc()); if (envelope.isErrorResult()) { final StringBuffer sb = new StringBuffer(); final StringBuffer buffer = envelope.errorMessages(); if (buffer.length() > 0) { sb.append(buffer); } else { sb.append("Server reported an error"); if (null != response.getResponseMessage()) { sb.append(": ").append(response.getResponseMessage()); } } if (null != response.getResponseMessage()) { logger.error("Server reported an error: " + response.getResponseMessage()); } else { logger.error("Server reported an error."); } throw new CentralDispatcherFailureResponseException(sb.toString()); } }
From source file:com.dtolabs.client.services.RundeckCentralDispatcher.java
License:Apache License
/** * Validate the response is in expected envlope form with <result> content. * * @param response response/*from w ww. j a va 2s . c o m*/ * * @return Envelope if format is correct and there is no error * * @throws CentralDispatcherException if the format is incorrect, or the Envelope indicates an error response. */ private Envelope validateResponse(final WebserviceResponse response) throws CentralDispatcherException { if (null == response) { throw new CentralDispatcherServerRequestException("Response was null"); } if (null != response.getResponseMessage()) { logger.info("Response: " + response.getResponseMessage()); } final Document resultDoc = response.getResultDoc(); if (null == resultDoc) { throw new CentralDispatcherServerRequestException("Response content unexpectedly empty. " + (response.getResponseMessage() != null ? response.getResponseMessage() : "")); } try { logger.debug(serialize(resultDoc)); } catch (IOException e) { logger.debug("ioexception serializing result doc", e); } if (!"result".equals(resultDoc.getRootElement().getName())) { throw new CentralDispatcherServerRequestException("Response had unexpected content: " + resultDoc); } final Envelope envelope = new Envelope(response.getResultDoc()); if (envelope.isErrorResult()) { final StringBuffer sb = new StringBuffer(); final StringBuffer buffer = envelope.errorMessages(); if (buffer.length() > 0) { sb.append(buffer); } else { sb.append("Server reported an error"); if (null != response.getResponseMessage()) { sb.append(": ").append(response.getResponseMessage()); } } if (null != response.getResponseMessage()) { logger.error("Server reported an error: " + response.getResponseMessage()); } else { logger.error("Server reported an error."); } throw new CentralDispatcherFailureResponseException(sb.toString()); } return envelope; }
From source file:com.dtolabs.shared.resources.ResourceXMLParser.java
License:Apache License
/** * Parse the document, applying the configured Receiver to the parsed entities * * @throws ResourceXMLParserException parse error * @throws java.io.IOException io error//w ww . j av a2s . co m */ public void parse() throws ResourceXMLParserException, IOException { final EntityResolver resolver = createEntityResolver(); final SAXReader reader = new SAXReader(false); reader.setEntityResolver(resolver); try { final Document doc; if (null == this.doc) { final InputStream in; if (null != file) { in = new FileInputStream(file); } else { in = input; } try { doc = reader.read(in); } finally { if (null != file) { in.close(); } } } else { doc = this.doc; } final EntitySet set = new EntitySet(); final Element root = doc.getRootElement(); final List list = root.selectNodes(entityXpath); for (final Object n : list) { final Node node = (Node) n; final Entity ent = parseEnt(node, set); if (null != receiver) { if (!receiver.resourceParsed(ent)) { break; } } } if (null != receiver) { receiver.resourcesParsed(set); } } catch (DocumentException e) { throw new ResourceXMLParserException(e); } }
From source file:com.easyjf.web.ajax.AjaxConfigManager.java
License:Apache License
public void parseConfig(Document doc) { if (doc == null) return;//from www . jav a 2s . c o m Element root = XmlElementUtil.findElement("ajax", doc.getRootElement()); Element maxDepth = XmlElementUtil.findElement("json-max-depth", root); if (maxDepth != null) { try { Integer depth = new Integer(maxDepth.getText()); AjaxUtil.JSON_OBJECT_MAX_DEPTH = depth;//JSON? } catch (NumberFormatException e) { } } Element serviceRoot = XmlElementUtil.findElement("services", root); if (serviceRoot != null) { parseServices(serviceRoot); } List converts = XmlElementUtil.findElements("convert", root); if (converts != null) { parseConvert(converts); } Element signatures = XmlElementUtil.findElement("signatures", root); if (signatures != null) { parseSignatures(signatures); } }