@Override public void sendMail(String emailRecipient, String message) { try { /*Should use subservice to get administrative resource resolver instead of this code*/ ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); Resource templateResource = resourceResolver.getResource(RabbitMQUtil.EMAIL_TEMPLATE_PATH); if (templateResource.getChild("file") != null) { templateResource = templateResource.getChild("file"); } ArrayList<InternetAddress> emailRecipients = new ArrayList<InternetAddress>(); final MailTemplate mailTemplate = MailTemplate.create( templateResource.getPath(), templateResource.getResourceResolver().adaptTo(Session.class)); HtmlEmail email = new HtmlEmail(); Map<String, String> mailTokens = new HashMap<String, String>(); mailTokens.put("message", message); mailTokens.put("subject", "Dummy Subject"); mailTokens.put("email", emailRecipient); if (mailTemplate != null) { emailRecipients.add(new InternetAddress(emailRecipient)); email.setTo(emailRecipients); email.setSubject("Dummy Mail"); email.setTextMsg(message); messageGateway = messageGatewayService.getGateway(HtmlEmail.class); messageGateway.send(email); } } catch (Exception e) { /*Put message in queue again in case of exception.. Based on type of exception, it can be decided whether it has to be put in queue again or not*/ RabbitMQUtil.addMessageToQueue(scrService); e.printStackTrace(System.out); } }
private List<Resource> getPresets(Resource configResource, String relPresetPath) { List<Resource> presets = new ArrayList<Resource>(); // get the configs presets Resource presetsResource = configResource.getChild(relPresetPath); if (presetsResource != null) { presets.addAll(toList(presetsResource.listChildren())); } // get the shared encoding presets Resource sharedResource = configResource.getParent().getParent(); Resource sharedPresetsResource = sharedResource.getChild(relPresetPath); if (sharedPresetsResource != null) { presets.addAll(toList(sharedPresetsResource.listChildren())); } return presets; }
public AbstractJcrVoucher(Resource resource) throws CommerceException { this.resource = resource; page = resource.adaptTo(Page.class); if (page == null || !ResourceUtil.isA( resource.getChild("jcr:content"), AbstractJcrVoucher.VOUCHER_RESOURCE_TYPE)) { throw new CommerceException("Resource is not a JcrVoucher."); } }
protected static Map<String, Map<Long, ResponseValue>> getTallyResponses(Resource tallyResource) throws JSONException { Map<String, Map<Long, ResponseValue>> returnValue = new HashMap<String, Map<Long, ResponseValue>>(); final ResourceResolver resolver = tallyResource.getResourceResolver(); final String tallyPath = tallyResource.getPath(); if (!tallyPath.startsWith("/content/usergenerated")) { tallyResource = resolver.resolve("/content/usergenerated" + tallyPath); } final Resource responsesNode = tallyResource.getChild(TallyConstants.RESPONSES_PATH); if (responsesNode == null) { return null; } NestedBucketStorageSystem bucketSystem = getBucketSystem(responsesNode); if (null == bucketSystem) { return null; } final Iterator<Resource> buckets = bucketSystem.listBuckets(); while (buckets.hasNext()) { final Resource bucketResource = buckets.next(); final Node bucketNode = bucketResource.adaptTo(Node.class); try { final NodeIterator userNodesInBucket = bucketNode.getNodes(); while (userNodesInBucket.hasNext()) { final Node userNode = userNodesInBucket.nextNode(); final NestedBucketStorageSystem userBucketSystem = getBucketSystem(resolver.getResource(userNode.getPath())); final Iterator<Resource> userBuckets = userBucketSystem.listBuckets(); final Map<Long, ResponseValue> userReturnValue = new HashMap<Long, ResponseValue>(); while (userBuckets.hasNext()) { final NodeIterator userResponses = userBuckets.next().adaptTo(Node.class).getNodes(); while (userResponses.hasNext()) { final Node responseNode = userResponses.nextNode(); final Long responseTimestamp = responseNode.getProperty(TIMESTAMP_PROPERTY).getLong(); userReturnValue.put( responseTimestamp, new PollResponse(responseNode.getProperty(RESPONSE_PROPERTY).getString())); } } returnValue.put(userNode.getName(), userReturnValue); } } catch (final RepositoryException e) { throw new JSONException( "Error trying to read user responses from bucket in " + bucketResource.getPath(), e); } } return returnValue; }
public static void extractAttachment( final Writer ioWriter, final JSONWriter writer, final Resource node) throws JSONException, UnsupportedEncodingException { Resource contentNode = node.getChild("jcr:content"); if (contentNode == null) { writer.key(ContentTypeDefinitions.LABEL_ERROR); writer.value( "provided resource was not an attachment - no content node beneath " + node.getPath()); return; } ValueMap content = contentNode.adaptTo(ValueMap.class); if (!content.containsKey("jcr:mimeType") || !content.containsKey("jcr:data")) { writer.key(ContentTypeDefinitions.LABEL_ERROR); writer.value( "provided resource was not an attachment - content node contained no attachment data under " + node.getPath()); return; } writer.key("filename"); writer.value(URLEncoder.encode(node.getName(), "UTF-8")); writer.key("jcr:mimeType"); writer.value(content.get("jcr:mimeType")); try { ioWriter.write(",\"jcr:data\":\""); final InputStream data = (InputStream) content.get("jcr:data"); byte[] byteData = new byte[DATA_ENCODING_CHUNK_SIZE]; int read = 0; while (read != -1) { read = data.read(byteData); if (read > 0 && read < DATA_ENCODING_CHUNK_SIZE) { // make a right-size container for the byte data actually read byte[] byteArray = new byte[read]; System.arraycopy(byteData, 0, byteArray, 0, read); byte[] encodedBytes = Base64.encodeBase64(byteArray); ioWriter.write(new String(encodedBytes)); } else if (read == DATA_ENCODING_CHUNK_SIZE) { byte[] encodedBytes = Base64.encodeBase64(byteData); ioWriter.write(new String(encodedBytes)); } } ioWriter.write("\""); } catch (IOException e) { writer.key(ContentTypeDefinitions.LABEL_ERROR); writer.value( "IOException while getting attachment at " + node.getPath() + ": " + e.getMessage()); } }
@Override public void delete(final Resource resource, final boolean shallow, final boolean autoSave) throws WCMException { try { if (shallow) { Resource contentResource = resource.getChild(JcrConstants.JCR_CONTENT); if (contentResource != null) { this.resourceResolver.delete(contentResource); } } else { this.resourceResolver.delete(resource); } if (autoSave) { this.resourceResolver.commit(); } } catch (PersistenceException ex) { throw new WCMException("Deleting resource at " + resource.getPath() + " failed.", ex); } }
@Test public void testGetPayloadProperties_Asset() throws Exception { // set up jcr properties mockJcrProperties(); Resource payloadRes = mock(Resource.class); Resource mdRes = mock(Resource.class); when(DamUtil.isAsset(payloadRes)).thenReturn(true); when(payloadRes.getChild(JcrConstants.JCR_CONTENT + "/" + DamConstants.METADATA_FOLDER)) .thenReturn(mdRes); // mock valueMap when(mdRes.getValueMap()).thenReturn(vmap); Map<String, String> props = SendTemplatedEmailUtils.getPayloadProperties(payloadRes, sdf); assertEquals(props.get(PN_CALENDAR), CALENDAR_TOSTRING); assertEquals(props.get(PN_TITLE), STR_TOSTRING); assertEquals(props.get(PN_LONG), LONG_TOSTRING); assertEquals(props.get(PN_STR_ARRAY), STR_ARRAY_TOSTRING); }
@Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { HtmlResponse htmlResponse = null; ResourceResolver adminResolver = null; Session adminSession = null; try { String email = request.getParameter(REQ_PRM_USERNAME); String password = request.getParameter(REQ_PRM_PASSWORD); String inviteKey = request.getParameter(REQ_PRM_INVITEKEY); String acceptStatus = request.getParameter(REQ_PRM_ACCEPT_STATUS); adminResolver = getAdminResolver(); adminSession = adminResolver.adaptTo(Session.class); InvitationToken invToken = ccInvitationService.getInvitationTokenByTokenKey(inviteKey, adminResolver); if (invToken != null && invToken.isValid() && inviteKey.equals(invToken.getKey())) { // Gets user account if user is already configured. Gets null // otherwise. Resource configResource = CCUtils.getAccountResourceByUserEmail(adminResolver, email); if (configResource == null) { // Create configuration if not // present. For first time login // encrypt the password if (!crypto.isProtected(password)) { password = crypto.protect(password); } AccessToken token = null; try { token = imsService.getAccessToken(email, password); } catch (Exception e) { log.error(e.getMessage(), e); htmlResponse = HtmlStatusResponseHelper.createStatusResponse(false, "Invalid Credentials"); } if (token != null) { // succesful login String configName = "invited_" + email; configName = configName.replace("@", "_at_").replaceAll("\\.", "_"); PageManager pageManager = pageManagerFactory.getPageManager(adminResolver); pageManager.create(CC_CONFIG_ROOT, configName, configName, CC_CONFIG_PAGE_TEMPLATE); Node configNode = adminSession.getNode(CC_CONFIG_ROOT + "/" + configName); Node contentNode = configNode.getNode("jcr:content"); contentNode.setProperty(CreativeCloudAccountConfig.PROPERTY_USERNAME, email); contentNode.setProperty("sling:resourceType", CreativeCloudAccountConfig.RESOURCE_TYPE); contentNode.setProperty( CreativeCloudAccountConfig.PROPERTY_ACCESS_TOKEN, token.getAccessToken()); contentNode.setProperty( CreativeCloudAccountConfig.PROPERTY_REFRESH_TOKEN, token.getRefreshToken()); contentNode.setProperty( CreativeCloudAccountConfig.PROPERTY_TOKEN_EXPIRES, token.getExpiresIn()); contentNode.setProperty(CreativeCloudAccountConfig.PROPERTY_PASSWORD, password); Node pollConfigNode = contentNode.addNode(CreativeCloudAccountConfig.NN_POLLCONFIG); pollConfigNode.setProperty( CreativeCloudAccountConfig.PROPERTY_INTERVAL, importer.getMinimumInterval()); pollConfigNode.setProperty(CreativeCloudAccountConfig.PROPERTY_ENABLED, true); configResource = adminResolver.getResource(contentNode.getPath()); ccConfigService.initAccount(configResource); } } else { // Sets the jcr content node as the config node configResource = configResource.getChild("jcr:content"); } if (acceptStatus != null && acceptStatus.equalsIgnoreCase("false")) { htmlResponse = HtmlStatusResponseHelper.createStatusResponse(true, "invitation declined"); } else { String[] paths = invToken.getPaths(); for (String path : paths) { // ccShareService.shareWithCCUser(configResource, // adminResolver.getResource(path)); // Asynchronous sharing Object job = new CCShareInBackground(factory, configResource.getPath(), path, ccShareService); String jobName = CCShareInBackground.class.getName() + "_" + UUID.randomUUID().toString().substring(0, 8); scheduler.fireJobAt(jobName, job, null, new Date()); } htmlResponse = HtmlStatusResponseHelper.createStatusResponse(true, "invitation accepted"); } ccInvitationService.acceptInvitation(email, inviteKey, adminResolver); adminSession.save(); } else { htmlResponse = HtmlStatusResponseHelper.createStatusResponse( false, "invitation expired or already accepted/declined"); } } catch (Exception e) { log.error(e.getMessage(), e); htmlResponse = HtmlStatusResponseHelper.createStatusResponse(false, e.getMessage()); htmlResponse.setError(e); } finally { if (adminSession != null) { adminSession.logout(); } if (adminResolver != null) { adminResolver.close(); } assert htmlResponse != null; htmlResponse.send(response, true); } }
public static void extractJournalEntry( final JSONWriter entryObject, final JournalEntry entry, final Writer rawWriter) throws JSONException, IOException { final Resource thisResource = entry.getTextComment().getResource(); final ValueMap vm = thisResource.adaptTo(ValueMap.class); final JSONArray timestampFields = new JSONArray(); // make sure we only migrate the fields we want final Map<String, Boolean> fieldsToMigrate = new HashMap<String, Boolean>(); fieldsToMigrate.put("userIdentifier", true); fieldsToMigrate.put("authorizableId", true); fieldsToMigrate.put("published", true); fieldsToMigrate.put("jcr:description", true); fieldsToMigrate.put("jcr:title", true); fieldsToMigrate.put("negative", true); fieldsToMigrate.put("positive", true); fieldsToMigrate.put("sentiment", true); for (final Map.Entry<String, Object> prop : vm.entrySet()) { if (!fieldsToMigrate.containsKey(prop.getKey())) { continue; } final Object value = prop.getValue(); if (prop.getKey().equals("published") && value instanceof GregorianCalendar) { timestampFields.put("added"); entryObject.key("added"); entryObject.value(((Calendar) value).getTimeInMillis()); } else { entryObject.key(prop.getKey()); try { entryObject.value(URLEncoder.encode(prop.getValue().toString(), "UTF-8")); } catch (final UnsupportedEncodingException e) { throw new JSONException( "Unsupported encoding (UTF-8) for resource at " + thisResource.getPath(), e); } } } // resource type has changed, so ignore the current one and force the new one entryObject.key("sling:resourceType"); entryObject.value("social/journal/components/hbs/entry_topic"); if (timestampFields.length() > 0) { entryObject.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS); entryObject.value(timestampFields); } final Resource translationResource = thisResource.getChild("translation"); if (null != translationResource) { extractTranslation(entryObject, translationResource); } if (entry.hasAttachments()) { entryObject.key(ContentTypeDefinitions.LABEL_ATTACHMENTS); JSONWriter attachmentsArray = entryObject.array(); List<Resource> attachmentList = entry.getAttachments(); for (final Resource attachment : attachmentList) { extractAttachment(rawWriter, attachmentsArray.object(), attachment); attachmentsArray.endObject(); } entryObject.endArray(); } if (entry.hasComments()) { final Iterator<Comment> posts = entry.getComments(); entryObject.key(ContentTypeDefinitions.LABEL_REPLIES); final JSONWriter replyWriter = entryObject.object(); while (posts.hasNext()) { final Comment childPost = posts.next(); replyWriter.key(childPost.getId()); extractComment( replyWriter.object(), childPost, entry.getResource().getResourceResolver(), rawWriter); replyWriter.endObject(); } entryObject.endObject(); } }
public static void extractTopic( final JSONWriter writer, final Post post, final ResourceResolver resolver, final String resourceType, final String childResourceType, final Writer responseWriter) throws JSONException, IOException { final ValueMap vm = post.getProperties(); final JSONArray timestampFields = new JSONArray(); for (final Map.Entry<String, Object> prop : vm.entrySet()) { final Object value = prop.getValue(); if (value instanceof String[]) { final JSONArray list = new JSONArray(); for (String v : (String[]) value) { list.put(v); } writer.key(prop.getKey()); writer.value(list); } else if (value instanceof GregorianCalendar) { timestampFields.put(prop.getKey()); writer.key(prop.getKey()); writer.value(((Calendar) value).getTimeInMillis()); } else if (prop.getKey().equals("sling:resourceType")) { writer.key(prop.getKey()); writer.value(resourceType); } else if (prop.getKey().equals("sentiment")) { writer.key(prop.getKey()); // 1 = 1, 2 = 3, 3 = 5, 4 = 8, 5 = 10 short shortValue = Short.parseShort(value.toString()); switch (shortValue) { case 1: writer.value(1); break; case 2: writer.value(3); break; case 3: writer.value(5); break; case 4: writer.value(8); break; case 5: writer.value(10); break; default: writer.value(value); } } else { writer.key(prop.getKey()); try { writer.value(URLEncoder.encode(prop.getValue().toString(), "UTF-8")); } catch (final UnsupportedEncodingException e) { throw new JSONException( "Unsupported encoding (UTF-8) for resource at " + post.getPath(), e); } } } if (timestampFields.length() > 0) { writer.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS); writer.value(timestampFields); } final Resource thisResource = resolver.getResource(post.getPath()); final Resource attachments = thisResource.getChild("attachments"); if (attachments != null) { writer.key(ContentTypeDefinitions.LABEL_ATTACHMENTS); final JSONWriter attachmentsWriter = writer.array(); for (final Resource attachment : attachments.getChildren()) { UGCExportHelper.extractAttachment(responseWriter, attachmentsWriter.object(), attachment); attachmentsWriter.endObject(); } writer.endArray(); } final Iterable<Resource> children = thisResource.getChildren(); for (final Resource child : children) { if (child.isResourceType("social/tally/components/hbs/voting") || child.isResourceType("social/tally/components/voting")) { writer.key(ContentTypeDefinitions.LABEL_TALLY); final JSONWriter voteObjects = writer.array(); UGCExportHelper.extractTally(voteObjects, child, "Voting"); writer.endArray(); } else if (child.getName().equals("translation")) { extractTranslation(writer, child); } } final Iterator<Post> posts = post.getPosts(); if (posts.hasNext()) { writer.key(ContentTypeDefinitions.LABEL_REPLIES); final JSONWriter replyWriter = writer.object(); while (posts.hasNext()) { Post childPost = posts.next(); replyWriter.key(childPost.getId()); extractTopic( replyWriter.object(), childPost, resolver, childResourceType, childResourceType, responseWriter); replyWriter.endObject(); } writer.endObject(); } }