Skip to content

Instantly share code, notes, and snippets.

@techforum-repo
Last active May 11, 2022 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techforum-repo/1c269d4849c5126a889472329e6fc29a to your computer and use it in GitHub Desktop.
Save techforum-repo/1c269d4849c5126a889472329e6fc29a to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.propertytypes.ServiceDescription;
import com.google.gson.JsonObject;
@Component(service = Servlet.class,
property = {
"sling.servlet.methods=" + "GET",
"sling.servlet.paths=" + "/bin/fetchi18nvalues/search",
// "sling.servlet.paths=" + "/bin/fecthi18nvalues/search1",
"sling.servlet.extensions=" + "json",
"sling.servlet.paths.strict=" + true
})
@ServiceDescription("Component Limitor Servlet")
public class FecthI18nValuesServlet extends SlingSafeMethodsServlet {
/** http://localhost:4502/bin/fecthi18nvalues/search.bg.json **/
String[] languages = { "bg", "en", "fr", "de", "hr","it" };
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
resp.setHeader("Cache-Control","max-age=3600");
JsonObject i18n = new JsonObject();
try {
String baseName = req.getRequestPathInfo().getResourcePath().split("/")[3];
String[] selectors = req.getRequestPathInfo().getSelectors();
if (selectors.length > 0 && Arrays.stream(languages).anyMatch(selectors[0]::equals)) {
ResourceBundle resourceBundle = req.getResourceBundle(baseName, new Locale(selectors[0]));
Iterator<String> itr = resourceBundle.getKeys().asIterator();
itr.forEachRemaining(key -> i18n.addProperty(key, resourceBundle.getString(key)));
}
resp.getWriter().print(i18n.toString());
} catch (Exception e) {
resp.getWriter().print(i18n.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment