@Override public InputStream getFileAsStream( long companyId, long repositoryId, String fileName, String versionLabel) throws PortalException, SystemException { Session session = null; try { session = JCRFactoryUtil.createSession(); Node contentNode = getFileContentNode(session, companyId, repositoryId, fileName, versionLabel); Property property = contentNode.getProperty(JCRConstants.JCR_DATA); Value value = property.getValue(); Binary binary = value.getBinary(); if ((session instanceof Map)) { Map<String, Binary> mapSession = (Map<String, Binary>) session; mapSession.put(fileName, binary); } return binary.getStream(); } catch (RepositoryException re) { throw new SystemException(re); } finally { JCRFactoryUtil.closeSession(session); } }
private Row prepareAnActivityRow(String path) throws RepositoryException { Row activityRow = mock(Row.class); Value pathValue = mock(Value.class); when(pathValue.getString()).thenReturn(path); when(activityRow.getValue("jcr:path")).thenReturn(pathValue); return activityRow; }
@Override public ResultSet query(String text, String lang) { Session session = (Session) this.getThreadLocalRequest().getSession().getAttribute("session"); ResultSet rs = new ResultSet(); try { QueryManager qm = session.getWorkspace().getQueryManager(); Query q = qm.createQuery(text, lang); QueryResult qr = q.execute(); rs.setColumnNames(qr.getColumnNames()); ArrayList<String[]> rows = new ArrayList(); RowIterator it = qr.getRows(); while (it.hasNext()) { Row row = it.nextRow(); String[] list = new String[qr.getColumnNames().length]; for (int i = 0; i < qr.getColumnNames().length; i++) { Value v = row.getValue(qr.getColumnNames()[i]); list[i] = v != null ? v.getString() : "null"; } rows.add(list); } rs.setRows(rows); } catch (RepositoryException e) { log.log(Level.SEVERE, "Error executing query: " + text, e); } return rs; }
/** * Gets the spell suggestion. * * @param checkingWord the checking word * @param manageableRepository the manageable repository * @return the spell suggestion * @throws Exception the exception */ private String getSpellSuggestion(String checkingWord, ManageableRepository manageableRepository) throws Exception { // Retrieve spell suggestion in special way to avoid access denied exception String suggestion = null; Session session = null; try { session = manageableRepository.getSystemSession( manageableRepository.getConfiguration().getDefaultWorkspaceName()); QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery( "SELECT rep:spellcheck() FROM nt:base WHERE jcr:path like '/' AND SPELLCHECK('" + checkingWord + "')", Query.SQL); RowIterator rows = query.execute().getRows(); Value value = rows.nextRow().getValue("rep:spellcheck()"); if (value != null) { suggestion = value.getString(); } } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } finally { if (session != null) session.logout(); } return suggestion; }
protected void performCheck(String statement, String expected) throws RepositoryException { QueryManager qm = superuser.getWorkspace().getQueryManager(); Query query = qm.createQuery( "/jcr:root[rep:spellcheck('" + statement + "')]/(rep:spellcheck())", Query.XPATH); RowIterator rows = query.execute().getRows(); assertEquals("no results returned", 1, rows.getSize()); Row r = rows.nextRow(); Value v = r.getValue("rep:spellcheck()"); if (statement.equals(expected)) { assertNull("must not return a suggestion", v); } else { assertNotNull("no suggestion returned", v); assertEquals("wrong suggestion returned", expected, v.getString()); } query = qm.createQuery( "select rep:spellcheck() from nt:base where " + "jcr:path = '/' and spellcheck('" + statement + "')", Query.SQL); rows = query.execute().getRows(); assertEquals("no results returned", 1, rows.getSize()); r = rows.nextRow(); v = r.getValue("rep:spellcheck()"); if (statement.equals(expected)) { assertNull("must not return a suggestion", v); } else { assertNotNull("no suggestion returned", v); assertEquals("wrong suggestion returned", expected, v.getString()); } }
@Test public void testNonSiteNode() throws RepositoryException, JSONException { SiteSearchResultProcessor siteSearchResultProcessor = new SiteSearchResultProcessor(); SiteService siteService = createMock(SiteService.class); siteSearchResultProcessor.bindSiteService(siteService); Row row = createMock(Row.class); Value val = createMock(Value.class); expect(val.getString()).andReturn(""); expect(row.getValue("jcr:path")).andReturn(val); expect(siteService.isSite(isA(Item.class))).andReturn(false); Node resultNode = createMock(Node.class); expect(resultNode.getPath()).andReturn(""); SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); ResourceResolver resourceResolver = createMock(ResourceResolver.class); Session session = createMock(Session.class); expect(request.getResourceResolver()).andReturn(resourceResolver); expect(resourceResolver.adaptTo(Session.class)).andReturn(session); expect(session.getItem("")).andReturn(resultNode); replay(); try { siteSearchResultProcessor.writeNode(request, null, null, row); fail(); } catch (JSONException e) { assertEquals("Unable to write non-site node result", e.getMessage()); } }
private RestQueryResult.RestRow createRestRow( Session session, QueryResult result, RestQueryResult restQueryResult, String[] columnNames, String baseUrl, Row resultRow) throws RepositoryException { RestQueryResult.RestRow restRow = restQueryResult.new RestRow(); Map<Value, String> binaryPropertyPaths = null; for (String columnName : columnNames) { Value value = resultRow.getValue(columnName); if (value == null) { continue; } String propertyPath = null; // because we generate links for binary properties, we need the path of the property which has // the value if (value.getType() == PropertyType.BINARY) { if (binaryPropertyPaths == null) { binaryPropertyPaths = binaryPropertyPaths(resultRow, result.getSelectorNames()); } propertyPath = binaryPropertyPaths.get(value); } String valueString = valueToString(propertyPath, value, baseUrl, session); restRow.addValue(columnName, valueString); } return restRow; }
private Row getRow(String key, String val) throws RepositoryException { Row row = createMock(Row.class); Value value = createMock(Value.class); expect(value.getString()).andReturn(val); expect(row.getValue(key)).andReturn(value); return row; }
@Test public void testNextWithLiteralBoolean() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.BOOLEAN); when(mockValue.getString()).thenReturn("true"); final QuerySolution solution = testObj.next(); assertEquals("true", solution.get("a").asLiteral().getLexicalForm()); }
@Test public void testNextWithURI() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.URI); when(mockValue.getString()).thenReturn("info:xyz"); final QuerySolution solution = testObj.next(); assertEquals("info:xyz", solution.get("a").asResource().getURI()); }
@Test public void testNextWithLiteralDouble() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.DOUBLE); when(mockValue.getDouble()).thenReturn(1.0); final QuerySolution solution = testObj.next(); assertEquals(1.0, solution.get("a").asLiteral().getDouble(), 0.1); }
@Test public void testNextWithLiteralLong() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.LONG); when(mockValue.getLong()).thenReturn(1L); final QuerySolution solution = testObj.next(); assertEquals(1L, solution.get("a").asLiteral().getLong()); }
/** * This method will check notify type of watcher, userName is equal value of property with * notification type * * @param documentNode specify a node to watch * @param userName userName to watch a document * @param notification Notification Type * @return boolean * @throws Exception */ private boolean checkNotifyTypeOfWatcher( Node documentNode, String userName, String notificationType) throws Exception { if (documentNode.hasProperty(notificationType)) { Value[] watchers = documentNode.getProperty(notificationType).getValues(); for (Value value : watchers) { if (userName.equalsIgnoreCase(value.getString())) return true; } } return false; }
/** Tests conversion from Date type to Double type. */ public void testGetDouble() throws RepositoryException { Value val = PropertyUtil.getValue(prop); double d = val.getDouble(); long mili = val.getDate().getTimeInMillis(); assertEquals( "Conversion from a Date value to a Double value " + "returns a different number of miliseconds.", mili, (long) d); }
@Test public void testNextWithLiteralDate() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.DATE); final Calendar date = Calendar.getInstance(); when(mockValue.getDate()).thenReturn(date); final QuerySolution solution = testObj.next(); assertNotNull(solution.get("a").asLiteral()); assertEquals(XSDDatatype.XSDdateTime.getURI(), solution.get("a").asLiteral().getDatatypeURI()); }
@Test public void testScore() throws RepositoryException { Row row = createMock(Row.class); Value value = createMock(Value.class); expect(value.getLong()).andReturn(Long.parseLong("1554")); expect(row.getValue("jcr:score")).andReturn(value); replay(); long score = RowUtils.getScore(row); assertEquals("Score is not the same", 1554, score); }
/** Tests if a calendar is returned and if the conversion to a string has correct format. */ public void testGetString() throws RepositoryException { Value val = PropertyUtil.getValue(prop); // correct format: YYYY-MM-DDThh:mm:ss.sssTZD // month(01-12), day(01-31), hours(00-23), minutes(00-59), seconds(00-59), // TZD(Z or +hh:mm or -hh:mm) // String aDay="2005-01-19T15:34:15.917+01:00"; String date = val.getString(); log.println("date str = " + date); boolean match = PropertyUtil.isDateFormat(prop.getString()); assertTrue("Date not in correct String format.", match); }
/** Tests failure of conversion from Date type to Boolean type. */ public void testGetBoolean() throws RepositoryException { try { Value val = PropertyUtil.getValue(prop); val.getBoolean(); fail( "Conversion from a Date value to a Boolean value " + "should throw a ValueFormatException."); } catch (ValueFormatException vfe) { // ok } }
@Test public void testNextWithResource() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.PATH); when(mockValue.getString()).thenReturn("/x"); when(mockGraphSubjects.getSubject("/x")).thenReturn(ResourceFactory.createResource("info:x")); final QuerySolution solution = testObj.next(); assertTrue(solution.contains("a")); assertEquals("info:x", solution.get("a").asResource().getURI()); assertEquals(solution.get("a"), solution.getResource("a")); }
@Test public void ferrari_is_available_with_capacity_3500cc() throws RepositoryException { Node ferrari = session.getNode("/cars/ferrari"); Value[] capacities = ferrari.getProperty("catalog:enginecapacity").getValues(); boolean isFound = false; for (Value capacity : capacities) { isFound = capacity.getLong() == 3500 ? true : isFound; } assertThat(isFound, is(true)); }
@Test public void testDefaultExcerptProp() throws RepositoryException { Row row = createMock(Row.class); Value value = createMock(Value.class); expect(value.getString()).andReturn("foo"); expect(row.getValue("rep:excerpt(jcr:content)")).andReturn(null).once(); expect(row.getValue("rep:excerpt(.)")).andReturn(value).once(); replay(); String result = RowUtils.getDefaultExcerpt(row); assertEquals("Excerpt is not the same", "foo", result); }
@Test public void testNextWithReference() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.REFERENCE); when(mockValue.getString()).thenReturn("uuid"); when(mockSession.getNodeByIdentifier("uuid")).thenReturn(mockNode); when(mockGraphSubjects.getSubject(mockNode.getPath())) .thenReturn(ResourceFactory.createResource("http://localhost:8080/xyz")); final QuerySolution solution = testObj.next(); assertEquals("http://localhost:8080/xyz", solution.get("a").asResource().getURI()); }
/* (non-Javadoc) * @see org.exoplatform.services.wcm.link.LiveLinkManagerService#updateLinks(javax.jcr.Node, java.util.List) */ public void updateLinkDataForNode(Node webContent, List<String> newLinks) throws Exception { ValueFactory valueFactory = webContent.getSession().getValueFactory(); if (webContent.canAddMixin("exo:linkable")) { webContent.addMixin("exo:linkable"); } // get old link from exo:links property List<String> listExtractedLink = new ArrayList<String>(); if (webContent.hasProperty("exo:links")) { Property property = webContent.getProperty("exo:links"); for (Value value : property.getValues()) { listExtractedLink.add(value.getString()); } } // compare, remove old link, add new link, create new List List<String> listResult = new ArrayList<String>(); for (String extractedLink : listExtractedLink) { for (String newUrl : newLinks) { if (LinkBean.parse(extractedLink).getUrl().equals(newUrl)) { listResult.add(extractedLink); } } } List<String> listTemp = new ArrayList<String>(); listTemp.addAll(newLinks); for (String newUrl : newLinks) { for (String extractedLink : listExtractedLink) { if (newUrl.equals(LinkBean.parse(extractedLink).getUrl())) { listTemp.set(newLinks.indexOf(newUrl), ""); } } } for (String strTemp : listTemp) { if (!strTemp.equals("")) { listResult.add(strTemp); } } // Create an array of value to add to exo:links property Value[] values = new Value[listResult.size()]; for (String url : listResult) { if (url.indexOf(LinkBean.STATUS) < 0) { LinkBean linkBean = new LinkBean(url, LinkBean.STATUS_UNCHECKED); values[listResult.indexOf(url)] = valueFactory.createValue(linkBean.toString()); } else { values[listResult.indexOf(url)] = valueFactory.createValue(url); } } webContent.setProperty("exo:links", values); webContent.save(); }
/** * Gets the values as string. * * @param node the node * @param propName the prop name * @return the values as string * @throws Exception the exception */ public static List<String> getValuesAsString(Node node, String propName) throws Exception { if (!node.hasProperty(propName)) return new ArrayList<String>(); List<String> results = new ArrayList<String>(); try { for (Value value : node.getProperty(propName).getValues()) { results.add(value.getString()); } } catch (ValueFormatException ex) { results.add(node.getProperty(propName).getValue().getString()); } return results; }
public VNodeDefinition(Node node) throws RepositoryException { name = node.getProperty(JCR_NODETYPENAME).getString(); // do properties properties = new HashMap<String, VPropertyDefinitionI>(); childSuggestions = new HashMap<String, String>(); NodeIterator nodeIterator = node.getNodes(); while (nodeIterator.hasNext()) { Node definitionNode = nodeIterator.nextNode(); String nodeType = definitionNode.getProperty(AbstractProperty.JCR_PRIMARYTYPE).getString(); // do a property if (NT_PROPERTYDEFINITION.equals(nodeType)) { String propertyName = "*"; // default to wildcard name if (definitionNode.hasProperty(JCR_NAME)) { // only add non-autogenerated properties if (!definitionNode.getProperty(JCR_AUTOCREATED).getBoolean()) { propertyName = definitionNode.getProperty(JCR_NAME).getString(); properties.put(propertyName, new VPropertyDefinition(definitionNode)); } } else { // property with no name means this node can accept custom properties canAddProperties = true; } } // do a child suggestion if (NT_CHILDNODEDEFINITION.equals(nodeType)) { String childName = "*"; // only do well-defined childnodedefinitions with the following 2 jcr properties if (definitionNode.hasProperty(JCR_NAME) && definitionNode.hasProperty(JCR_DEFAULTPRIMARYTYPE)) { childSuggestions.put( definitionNode.getProperty(JCR_NAME).getString(), definitionNode.getProperty(JCR_DEFAULTPRIMARYTYPE).getString()); } } } // do supertypes supertypes = new HashSet<String>(); if (node.hasProperty(JCR_SUPERTYPES)) { for (Value value : node.getProperty(JCR_SUPERTYPES).getValues()) { supertypes.add(value.getString()); } } // set mixin status isMixin = node.hasProperty(JCR_ISMIXIN) && node.getProperty(JCR_ISMIXIN).getBoolean(); }
/** * Reads the list of recipients from the <code>james:recipients</code> property. * * @param node mail node * @return list of recipient, or an empty list if not set * @throws MessagingException if a messaging error occurs * @throws RepositoryException if a repository error occurs */ @SuppressWarnings("unchecked") private Collection<MailAddress> getRecipients(Node node) throws MessagingException, RepositoryException { try { Value[] values = node.getProperty("james:recipients").getValues(); Collection<MailAddress> recipients = new ArrayList<MailAddress>(values.length); for (Value value : values) { recipients.add(new MailAddress(value.getString())); } return recipients; } catch (PathNotFoundException e) { return Collections.EMPTY_LIST; } }
public List<ContentMap> getItems(Node item, String nodeType, String workspace) { final List<ContentMap> items = new ArrayList<ContentMap>(0); try { final Value[] values = item.getProperty(nodeType).getValues(); if (values != null) { for (Value value : values) { items.add(templatingFunctions.contentById(value.getString(), workspace)); } } } catch (RepositoryException e) { log.error("Exception while getting items", e.getMessage()); } return items; }
/** * Grants the specified permission to the role. Both permission and role nodes have to exist. The * {@link Session#save()} is not called by this method; it is the responsibility of the caller. * * @param permissionPath the path of the permission to be granted * @param rolePath the path of the role the permission should be granted to * @param session current JCR session * @return <code>true</code> if any modification was done; if the role already has that permission * assigned, <code>false</code> is returned. * @throws RepositoryException in case of an error */ public static boolean grantPermissionToRole( String permissionPath, String rolePath, JCRSessionWrapper session) throws RepositoryException { if (permissionPath == null || !permissionPath.startsWith("/permissions/")) { throw new IllegalArgumentException( "Illegal value for the permission path: " + permissionPath); } if (rolePath == null || rolePath.length() == 0) { throw new IllegalArgumentException("Illegal value for the role: " + rolePath); } boolean modified = true; JCRNodeWrapper permission = session.getNode(permissionPath); String permissionId = permission.getIdentifier(); JCRNodeWrapper role = session.getNode(rolePath.contains("/") ? rolePath : "/roles/" + rolePath); if (role.hasProperty("j:permissions")) { Value[] values = role.getProperty("j:permissions").getValues(); boolean alreadyPresent = false; for (Value value : values) { if (permissionId.equals(value.getString())) { alreadyPresent = true; break; } } if (!alreadyPresent) { Value[] newValues = new Value[values.length + 1]; System.arraycopy(values, 0, newValues, 0, values.length); newValues[values.length] = session.getValueFactory().createValue(permission, true); role.setProperty("j:permissions", newValues); logger.info("Granted permission {} to role {}", permission.getPath(), role.getPath()); } else { if (logger.isDebugEnabled()) { logger.debug( "Role {} already has permission {} granted", role.getPath(), permission.getPath()); } modified = false; } } else { role.setProperty( "j:permissions", new Value[] {session.getValueFactory().createValue(permission, true)}); logger.info("Granted permission {} to role {}", permission.getPath(), role.getPath()); } return modified; }
protected void assertCanObtainValue(Value value, int expectedType) throws Exception { switch (expectedType) { case PropertyType.BINARY: Binary binary = value.getBinary(); try { InputStream stream = binary.getStream(); assertThat(stream, is(notNullValue())); try { stream.read(); } finally { stream.close(); } } finally { binary.dispose(); } break; case PropertyType.BOOLEAN: assertThat(value.getBoolean() || !value.getBoolean(), is(true)); break; case PropertyType.DATE: Calendar cal = value.getDate(); assertThat(cal, is(notNullValue())); break; case PropertyType.DOUBLE: double doubleValue = value.getDouble(); assertThat(doubleValue < 0.0d || doubleValue >= -1.0d, is(true)); break; case PropertyType.LONG: long longValue = value.getLong(); assertThat(longValue < 0L || longValue >= 0L, is(true)); break; case PropertyType.NAME: context.getValueFactories().getNameFactory().create(value.getString()); break; case PropertyType.PATH: context.getValueFactories().getPathFactory().create(value.getString()); break; case PropertyType.REFERENCE: UUID uuid = context.getValueFactories().getUuidFactory().create(value.getString()); assertThat(uuid, is(notNullValue())); break; case PropertyType.STRING: value.getString(); break; } }
@Override public JcrRepositoryDescriptor repositoryInfo() { Session session = (Session) this.getThreadLocalRequest().getSession().getAttribute("session"); JcrRepositoryDescriptor desc = new JcrRepositoryDescriptor(); Repository repo = session.getRepository(); try { String keys[] = session.getRepository().getDescriptorKeys(); for (int i = 0; i < keys.length; i++) { Value value = repo.getDescriptorValue(keys[i]); desc.add(keys[i], value != null ? value.getString() : "N/A"); } } catch (RepositoryException e) { log.log(Level.SEVERE, "Error getting repository information", e); } return desc; }