Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

created template and added related hash tags component #2

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions core/src/main/java/it/codeland/academy/core/models/HashTags.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package it.codeland.academy.core.models;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import java.util.*;



@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class HashTags {
private String[] allTags;
private List <HashMap> tagsHashMap = new ArrayList<>();

@Inject
private String[] tags;

@PostConstruct
protected void init() throws PersistenceException {

if(tags!=null){
allTags = new String[tags.length];
for(int i=0; i<tags.length; i++){
HashMap<String,String> tg = new HashMap();


String[] splitedTag = tags[i].split(":");
if(splitedTag.length == 2){
allTags[i] = splitedTag[1];
tg.put("tag", splitedTag[1]);
}else{
allTags[i] = splitedTag[0];
tg.put("tag", splitedTag[0]);
}
tg.put("old", tags[i]);
tagsHashMap.add(tg);
}
}
}

// get all tags
public String[] getAllTags() {
return allTags;
}
// get tags
public String[] getTags() {
return tags;
}
// tagsHashMap

public List<HashMap>getTagsHashMap(){
return tagsHashMap;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package it.codeland.academy.core.servlets;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.propertytypes.ServiceDescription;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.apache.sling.jcr.api.SlingRepository;
import java.util.HashMap;
import com.google.gson.*;

@Component(service = { Servlet.class })
@SlingServletPaths(
value={"/bin/hashtags"})
@ServiceDescription("Related hashtags component api")
public class HashTagServlet extends SlingSafeMethodsServlet {

private static final long serialVersionUID = 1L;
private List<Node>foundNodes = new ArrayList<>();
protected Session session;

@Reference
protected SlingRepository repository;


@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {

ArrayList<HashMap>articles = new ArrayList<>();
final String tag = req.getParameter("tag");
try {
session = repository.loginAdministrative(null);
Workspace workspace = session.getWorkspace();

QueryManager queryManager = workspace.getQueryManager();
String maxLen = req.getParameter("max") == null ? "20" : req.getParameter("max");

String rawQuery="SELECT * FROM [cq:PageContent] AS magazines WHERE ISDESCENDANTNODE ([/content/ucs-exercise-renepromesse/magazine]) AND magazines.[tags] = '"+tag+"' ORDER BY [jcr:created] ASC";

Query query = queryManager.createQuery(rawQuery, Query.JCR_SQL2);
query.setLimit(Integer.parseInt(maxLen));
QueryResult result = query.execute();

NodeIterator magazineIterator = result.getNodes();

while (magazineIterator.hasNext()) {
Node currentNode = (Node)magazineIterator.next();
if(!foundNodes.contains(currentNode)) {
foundNodes.add(currentNode);
}
}
SimpleDateFormat sdf = new SimpleDateFormat("E dd MMM yyyy");

for (Node node : foundNodes) {
HashMap<String, String> map = new HashMap<>();
map.put("title", node.getProperty("jcr:title").getString());
map.put("link", node.getParent().getPath().concat(".html"));
// slit the tag with :
String[] tags = tag.split(":");
map.put("hashtag", tags[1]);
map.put("date",sdf.format(node.getProperty("jcr:created").getDate().getTime()));
map.put("image", node.getProperty("image").getString());
map.put("text", node.getProperty("text").getString());
articles.add(map);

}
foundNodes.clear();
Gson gson = new Gson();
String json = gson.toJson(articles);
articles.removeAll(articles);
resp.setContentType("application/json");
resp.getWriter().println(json);
} catch (Exception e) {
resp.setContentType("application/json");
resp.getWriter().write(e.getMessage());
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package it.codeland.academy.core.servlets;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.json.JSONObject;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.propertytypes.ServiceDescription;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;

/**
* Servlet that writes some sample content into the response. It is mounted for
* all resources of a specific Sling resource type. The
* {@link SlingSafeMethodsServlet} shall be used for HTTP methods that are
* idempotent. For write operations use the {@link SlingAllMethodsServlet}.
*/
@Component(service = { Servlet.class })
@SlingServletResourceTypes(
resourceTypes="cq:Page",
methods=HttpConstants.METHOD_GET,
selectors="export",
extensions="json")
@ServiceDescription("Export page properties")
public class PageToJsonServlet extends SlingSafeMethodsServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
final Resource resource = req.getResource();
JsonObject simpleObj = new JsonObject();

Resource jcrContent = resource.getChild("jcr:content");

// convert this value resource jcr:content into a valueMap
ValueMap thisArticle = jcrContent.adaptTo(ValueMap.class);

// get properties
String image = thisArticle.get("image", String.class);
String text = thisArticle.get("text", String.class);
String title = thisArticle.get("jcr:title", String.class);
String tags = thisArticle.get("tags", String.class);
String date = thisArticle.get("date", String.class);

//simpleObj.addProperty("title", resource.getName());
simpleObj.addProperty("title", title);
simpleObj.addProperty("abstract", text);
simpleObj.addProperty("image", image);
simpleObj.addProperty("link", resource.getPath().toString() + ".html");
simpleObj.addProperty("tags", tags);
simpleObj.addProperty("date", date);

/**
* {
"title": "My article title",
"abstract": "This is a long article abstract...."
"image": "/content/dam/whatever.jpg"
"link": "/content/site/articles/article-1.html"
"tags": ["tag-1","tag-2"]
}
*/

String output = new String();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
output = gson.toJson(simpleObj);
resp.setContentType("application/json");
resp.getWriter().write(output);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
article test 1, article-test-1, /content/dam/ucs-exercise-renepromesse/hero_mobile.png, uni-credit:talent, This is a test page 1
article test 2, article-test-2, /content/dam/ucs-exercise-renepromesse/hero_mobile.png, uni-credit:peoplestory, This is a test page 2
article test 3, article-test-3, /content/dam/ucs-exercise-renepromesse/hero_mobile.png, uni-credit:talent, This is a test page 3

Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@
-ms-flex-align: center;
align-items: center;
}
.shuffle-container{
display: flex;
align-items: center;
justify-content: space-around;
}
.shuffle-container span{
padding-left: 4px;
}
@media only screen and (max-width: 1024px) {
.relatedHashtag__bar {
-webkit-flex-direction: column;
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ heroBanner__welcome.js
moment.min.js
relatedHashtag.js
tags.js
myHashTags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("This is my hastag");
Original file line number Diff line number Diff line change
@@ -1,6 +1,35 @@
$(document).ready(function () {
var windowRelatedHash = $(window).width();
var dataHashtag;
var shuffleAll;

// shuffle the cards
function shuffle(array) {
let currentIndex = array.length, randomIndex;

// While there remain elements to shuffle...
while (currentIndex != 0) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;

// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}

return array;
}

$(document).on('click', '#shuffle', function () {
if(shuffleAll === 'true || false'){
setSwiperStructure(dataHashtag);
}

});



// Hashtag Click
$(document).on("click", ".relatedHashtag .bar__item", function () {
Expand All @@ -10,15 +39,17 @@ $(document).ready(function () {
$(".relatedHashtag__result").fadeIn();
var parm = $(this).attr("data-hashtag");
var max = $(this).attr("data-maxarticle");
var shuffleAtt = $(this).attr("data-shuffle");
shuffleAll = shuffleAtt;
getResult(parm, max);
}
});

// Close Click
$(document).on("click", ".relatedHashtag .close", function () {
$(".icon-close").click(function () {
$(".relatedHashtag__result").fadeOut();
$(".relatedHashtag .bar__item").removeClass("bar__item--active");
});
})

//RESIZE MANAGEMENT
$(window).on("resize", function () {
Expand Down Expand Up @@ -70,6 +101,9 @@ $(document).ready(function () {
}

function setSwiperStructure(data) {
if(shuffleAll === 'true || false'){
data = shuffle(data);
}
$(".relatedHashtag__result .swiper-slide").remove();
if (data) {
$(".result__number .number").text(data.length);
Expand Down Expand Up @@ -124,11 +158,11 @@ $(document).ready(function () {

addBg($(window).width());

lastCard.find(".card__hashtag").text(cardData.tags[0]);
lastCard.find(".card__hashtag").text("#" + cardData.hashtag);

lastCard.find(".card__date").text(cardData.date);

lastCard.find(".card__desc").text(cardData.articleAbstract);
lastCard.find(".card__desc").text(cardData.text);

counter = counter + 1;
if (counter > numberOfSlider) {
Expand All @@ -150,12 +184,12 @@ $(document).ready(function () {
$(".relatedHashtag__result .swiper-slide").remove();

$.ajax({
url: `/bin/hashtag?tag=${parm}&max=${max}`,
url: `/bin/hashtags?tag=${parm}&max=${max}`,
type: "GET",
success: function (res) {
dataHashtag = res;
},
complete: function () {
complete: function () {
setSwiperStructure(dataHashtag);
cardsSwiper();
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@

<div>
<sly id="home-slider-testS" data-sly-resource="${'home-slider-test' @ resourceType='ucs-exercise-renepromesse/components/home-slider-test'}"></sly>
<sly id="home-slider-test" data-sly-resource="${'home-slider-test' @ resourceType='ucs-exercise-renepromesse/components/home-slider-test'}"></sly>
</div>
<div>
<sly id="home-hash-tags" data-sly-resource="${'home-hash-tags' @ resourceType='ucs-exercise-renepromesse/components/home-hash-tags'}"></sly>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="cq:Component"
jcr:title="home-hash-tags"
sling:resourceSuperType="foundation/components/parbase"
componentGroup="ucs-renepromesse"/>

Loading