本文整理汇总了Java中org.apache.sling.api.SlingHttpServletResponse.setContentType方法的典型用法代码示例。如果您正苦于以下问题:Java SlingHttpServletResponse.setContentType方法的具体用法?Java SlingHttpServletResponse.setContentType怎么用?Java SlingHttpServletResponse.setContentType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.sling.api.SlingHttpServletResponse
的用法示例。
在下文中一共展示了SlingHttpServletResponse.setContentType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException
{
final Timer.Context t = metrics.timer(getClass().getSimpleName()).time();
try {
// Output the count of our child nodes
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
final PrintWriter w = response.getWriter();
w.print(request.getResource().getPath());
w.print(" has ");
w.print(countChildren(request.getResource(), ID));
w.print(" descendant nodes with an '");
w.print(ID);
w.print("' property. Sling instance ID is ");
w.print(settings.getSlingId());
w.println(".");
w.flush();
} finally {
t.stop();
}
}
示例2: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Page currentPage = request.getResource().adaptTo(Page.class);
JSONWriter w = new JSONWriter(response.getWriter());
w.object();
w.key("name").value(currentPage.getTitle());
w.endObject();
} catch (Exception ex) {
log.error("Request failed", ex);
throw new ServletException(ex);
}
}
示例3: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException, ServletException {
log.trace("doGet");
String suffix = request.getRequestPathInfo().getSuffix();
if (StringUtils.isNotEmpty(suffix)) {
log.debug("Retrieving data layer for {}", suffix);
Resource resource = request.getResourceResolver().getResource(suffix);
if (resource != null) {
HttpServletRequest req = requestResponseFactory.createRequest("GET", suffix + ".html");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HttpServletResponse resp = requestResponseFactory.createResponse(baos);
requestProcessor.processRequest(req, resp, request.getResourceResolver());
DataLayer dataLayer = DataLayerUtil.getDataLayer(req);
if (dataLayer != null) {
response.setContentType("application/json");
response.getWriter().write(DataLayerUtil.toJSON(dataLayer));
} else {
log.warn("No Data Layer found for {}", suffix);
response.sendError(404, "No Data Layer found for " + suffix);
}
} else {
log.warn("No Resource found at {}", suffix);
response.sendError(404, "No Resource found at " + suffix);
}
} else {
response.sendError(400, "Missing Suffix");
}
}
示例4: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws IOException, ServletException {
//TODO: put all of the logic in a context processor (need to fix templating support filter bug first)
String transformName = BLANK;
if (PathInfoUtil.getSuffixSegments(request).length == 2) {
String firstSuffixSegment = PathInfoUtil.getFirstSuffixSegment(request);
if (this.namedImageTransformers.keySet().contains(firstSuffixSegment)) {
transformName = firstSuffixSegment;
}
}
//Adds the asset binary to the inputStream
try {
Resource assetResource = getAssetResource(request);
if (DamUtil.isAsset(assetResource)) {
Binary binary;
String mimeType = BLANK;
Asset asset = DamUtil.resolveToAsset(assetResource);
Resource original = asset.getOriginal();
Node assetNode = original.adaptTo(Node.class);
if (assetNode.hasNode(JCR_CONTENT)) {
Node assetInfo = assetNode.getNode(JCR_CONTENT);
if (assetInfo.hasProperty(JCR_MIMETYPE)) {
mimeType = assetInfo.getProperty(JCR_MIMETYPE).getString();
}
if (StringUtils.isNotBlank(mimeType)) {
response.setContentType(mimeType);
}
binary = assetInfo.getProperty(JCR_DATA).getBinary();
InputStream inputStream = binary.getStream();
OutputStream outputStream = response.getOutputStream();
boolean shouldTransform = StringUtils.isNotBlank(transformName);
if (shouldTransform && ImageUtils.isImage(assetResource)) {
double quality = 1;
double maxGifQuality = 255;
// Transform the image
final Layer layer = new Layer(inputStream, new Dimension(maxWidth, maxHeight));
Layer newLayer = null;
try {
final NamedImageTransformer namedImageTransformer = this.namedImageTransformers.get(transformName);
newLayer = namedImageTransformer.transform(layer);
if (StringUtils.isBlank(mimeType) || !ImageIO.getImageWritersByMIMEType(mimeType).hasNext()) {
mimeType = getImageMimeType(layer, asset.getName());
response.setContentType(mimeType);
}
// For GIF images the colors will be reduced according to the quality argument.
if (StringUtils.equals(mimeType, GIF_MIME_TYPE)) {
quality = quality * maxGifQuality;
}
newLayer.write(mimeType, quality, outputStream);
} finally {
if (layer != null) {
layer.dispose();
}
if (newLayer != null) {
newLayer.dispose();
}
}
} else {
ByteStreams.copy(inputStream, outputStream);
}
response.flushBuffer();
outputStream.close();
}
}
} catch (RepositoryException repoException) {
LOGGER.error("Repository Exception. ", repoException);
}
}
示例5: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
out.write("Annotation Demo Servlet - Felix - enabled: " + enabled + "\n");
out.write(sampleFelixService.getSettings());
}
示例6: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
out.write("Annotation Demo Servlet - OSGi - enabled: " + enabled + "\n");
out.write(sampleOsgiService.getSettings());
}
示例7: doPost
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException
{
final Timer.Context t = metrics.timer(getClass().getSimpleName()).time();
try {
final String id = UUID.randomUUID().toString();
Resource r = request.getResource();
final Map<String, Object> props = new HashMap<String, Object>();
r = addChild(r, getClass().getSimpleName(), props);
for(int i=0 ; i < 4; i+=2) {
r = addChild(r, id.substring(i, i+2), props);
}
props.put(RootGetServlet.ID, id);
r = addChild(r, id, props);
r.getResourceResolver().commit();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
final PrintWriter w = response.getWriter();
w.print("Added ");
w.println(r.getPath());
w.flush();
} finally {
t.stop();
}
}
示例8: doPost
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws ServletException, IOException {
String fileName = request.getParameter("filename");
String content = request.getParameter("content");
if (fileName == null || fileName.length() == 0) {
LOGGER.error("Parameter fileName is required");
return;
}
response.setContentType("application/octet-stream"); // Your content type
response.setHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream input = IOUtils.toInputStream(content);
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while ((read = input.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
input.close();
os.flush();
os.close();
}
示例9: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws ServletException, IOException {
LOG.info("Servlet GET Method requested");
// Write a standard text/html response
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("<html><body>Text to write to response</body></html>");
}
示例10: doPost
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
/**
* Save system properties on POST.
*
* @param request The Sling HTTP servlet request.
* @param response The Sling HTTP servlet response.
*/
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
final PrintWriter writer = response.getWriter();
final boolean allowWrite = userService.isAuthorable(request.getResourceResolver().adaptTo(Session.class));
response.setCharacterEncoding(CharEncoding.UTF_8);
response.setContentType("application/json");
if (allowWrite) {
final String blogName = request.getParameter(BLOG_NAME_PROPERTY);
final boolean extensionlessUrls = Boolean.parseBoolean(request.getParameter(EXTENSIONLESS_URLS_PROPERTY));
final String tempDir = request.getParameter(TEMPORARY_DIRECTORY_PROPERTY);
final Map<String, Object> properties = new HashMap<String, Object>();
properties.put(SystemSettingsService.SYSTEM_BLOG_NAME, blogName);
properties.put(SystemSettingsService.SYSTEM_EXTENSIONLESS_URLS, extensionlessUrls);
properties.put(SystemSettingsService.SYSTEM_TEMPORARY_DIRECTORY, tempDir);
boolean result = systemSettingsService.setProperties(properties);
if (result) {
response.setStatus(SlingHttpServletResponse.SC_OK);
sendResponse(writer, "OK", "Settings successfully updated.");
} else {
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendResponse(writer, "Error", "Settings failed to update.");
}
} else {
response.setStatus(SlingHttpServletResponse.SC_FORBIDDEN);
sendResponse(writer, "Error", "Current user not authorized.");
}
}
示例11: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
/**
* Return all comments on a GET request in order of newest to oldest.
*/
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
final PrintWriter writer = response.getWriter();
response.setCharacterEncoding(CharEncoding.UTF_8);
response.setContentType("application/json");
List<Resource> comments = commentService.getComments(request);
try {
JSONArray jsonArray = new JSONArray();
for (Resource comment : comments) {
final JSONObject json = new JSONObject();
final ValueMap properties = comment.getValueMap();
final Resource post = commentService.getParentPost(comment);
json.put(PublickConstants.COMMENT_PROPERTY_COMMENT,
properties.get(PublickConstants.COMMENT_PROPERTY_COMMENT, String.class));
json.put(JSON_ID, properties.get(JcrConstants.JCR_UUID, String.class));
json.put(JSON_EDITED, properties.get(PublickConstants.COMMENT_PROPERTY_EDITED, false));
json.put(JSON_REPLIES, commentService.numberOfReplies(comment));
json.put(JSON_SPAM, properties.get(PublickConstants.COMMENT_PROPERTY_SPAM, false));
json.put(JSON_POST, new JSONObject()
.put(JSON_POST_TEXT, post.getValueMap().get(PublickConstants.COMMENT_PROPERTY_TITLE, String.class))
.put(JSON_POST_LINK, linkRewriter.rewriteLink(post.getPath(), request.getServerName())));
jsonArray.put(json);
}
response.setStatus(SlingHttpServletResponse.SC_OK);
writer.write(jsonArray.toString());
} catch (JSONException e) {
LOGGER.error("Could not write JSON", e);
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
示例12: doPost
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
/**
* Send email on post to servlet. The submission is verified through the reCAPTCHA
* service before submitting. Upon completion, a JSON response is returned.
*
* @param request The Sling HTTP servlet request
* @param response The Sling HTTP servlet response
* @see <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-java.html">Sending an Email Through the Amazon SES SMTP Interface with Java</a>
*/
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
boolean notRobot = recaptchaService.validate(request);
if (notRobot) {
final String submitterName = request.getParameter("name");
final String submitterEmail = request.getParameter("email");
final String submitterMessage = request.getParameter("message");
if (StringUtils.isNotEmpty(submitterName)
&& StringUtils.isNotEmpty(submitterName)
&& StringUtils.isNotEmpty(submitterName)) {
final String body = String.format(BODY, submitterName, submitterEmail, submitterMessage);
final boolean result = emailService.sendMail(SUBJECT, body);
if (result) {
response.setStatus(SlingHttpServletResponse.SC_OK);
sendResponse(writer, SlingHttpServletResponse.SC_OK, "Email was sent successfully.");
} else {
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendResponse(writer, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error.");
}
} else {
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendResponse(writer, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Submission was missing the message, name or email.");
}
} else {
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendResponse(writer, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"The reCAPTCHA service determined that you were a robot.");
}
}
示例13: doGet
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
/**
* Add overrides for other SlingAllMethodsServlet here (doHead, doTrace, doPut, doDelete, etc.)
*/
@Override
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws
ServletException, IOException {
// Implement custom handling of GET requests
// This should be idempotent and not change underlying data in any meaningful way;
// To be safe, never modify data (add/update/delete) in the context of a GET request
// Set the response type; this might be JSON, etc.
// The repsonse type is usually closely correlated to the extension the servlet listens on
response.setContentType("text/html");
// Do some work
Resource resource = request.getResourceResolver().getResource("/content/world");
ValueMap properties = resource.adaptTo(ValueMap.class);
if (properties != null) {
// Writing HTML in servlets is usually inadvisable, and is better suited to be provided via a JSP/Sightly template
// This is just an example.
response.getWriter().write("<html><head></head><body>Hello "
+ properties.get("name", "World")
+ "!</body></html>");
// By Default the 200 HTTP Response status code is used; below explicitly sets it.
response.setStatus(SlingHttpServletResponse.SC_OK);
} else {
// Set HTTP Response Status code appropriately
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("ERROR");
}
}
示例14: activate
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
@Override
public void activate() {
SlingHttpServletRequest request = getRequest();
SlingHttpServletResponse response = getResponse();
ResourceResolver resolver = getResourceResolver();
isAnonymous = "anonymous".equals(resolver.adaptTo(Session.class).getUserID());
message = (String) request.getAttribute(SlingConstants.ERROR_MESSAGE);
Integer scObject = (Integer) request.getAttribute(SlingConstants.ERROR_STATUS);
code = (scObject != null) ? scObject.intValue() : response.SC_INTERNAL_SERVER_ERROR;
if (message == null) {
message = statusToString(code);
}
// Print stack trace only if the user is not anonymous
if (!isAnonymous) {
if (request.getAttribute(SlingConstants.ERROR_EXCEPTION) instanceof Throwable) {
Throwable throwable = (Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION);
printStackTrace(throwable);
}
}
response.setStatus(code);
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
}
示例15: stream
import org.apache.sling.api.SlingHttpServletResponse; //导入方法依赖的package包/类
private void stream(@Nonnull SlingHttpServletResponse response, @Nonnull InputStream inputStream, @Nonnull String contentType)
throws IOException {
response.setContentType(contentType);
try {
IOUtils.copy(inputStream, response.getOutputStream());
} finally {
IOUtils.closeQuietly(inputStream);
}
}