Untitled
unknown
java
2 years ago
3.3 kB
24
Indexable
package com.trilha03.core.models; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.models.annotations.Default; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.injectorspecific.InjectionStrategy; import org.apache.sling.models.annotations.injectorspecific.SlingObject; import org.apache.sling.models.annotations.injectorspecific.ValueMapValue; import javax.annotation.PostConstruct; @Model(adaptables = { Resource.class, SlingHttpServletRequest.class }) public class ModelTeste { @ValueMapValue(name = "sling:resourceType", injectionStrategy = InjectionStrategy.OPTIONAL) @Default(values = "No resourceType") protected String resourceType; @SlingObject private Resource currentResource; @SlingObject private ResourceResolver resourceResolver; private String name; private int age; @PostConstruct protected void init() { if (currentResource != null) { ModifiableValueMap valueMap = currentResource.adaptTo(ModifiableValueMap.class); if (valueMap != null) { // Get values or set defaults name = valueMap.get("name", String.class); age = valueMap.get("age", 0); // Other initialization logic... // Add debug statements System.out.println("Name: " + name); System.out.println("Age: " + age); } else { System.err.println("Failed to adapt currentResource to ModifiableValueMap"); } } else { System.err.println("Current resource is null during init"); } } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; updateProperties(); } public void setAge(int age) { this.age = age; updateProperties(); } public ResourceResolver getResourceResolver() { return resourceResolver; } public void updateProperties() { if (currentResource != null && resourceResolver != null) { ModifiableValueMap valueMap = currentResource.adaptTo(ModifiableValueMap.class); if (valueMap != null) { if (name != null) { valueMap.put("name", name); } valueMap.put("age", age); // Commit the changes (highlighted part) try { resourceResolver.commit(); } catch (PersistenceException e) { // Handle or log the exception e.printStackTrace(); } } else { System.err.println("Failed to adapt currentResource to ModifiableValueMap during update"); } } else { System.err.println("Current resource or ResourceResolver is null during update"); } } }
Editor is loading...
Leave a Comment