Example usage for com.google.common.net MediaType toString

List of usage examples for com.google.common.net MediaType toString

Introduction

In this page you can find the example usage for com.google.common.net MediaType toString.

Prototype

String toString

To view the source code for com.google.common.net MediaType toString.

Click Source Link

Usage

From source file:com.bennavetta.appsite.processor.GroovyTemplateProcessor.java

@Override
public boolean canProcess(String path, MediaType type, Request request, Response response) {
    if (path.endsWith(".gtpl")) // is there an official extension?
        return true;
    if (type.toString().contains("groovy") && type.toString().contains("template"))
        return true;
    return false;
}

From source file:com.acme.ecards.api.email.support.MessageFactory.java

/**
 * Crate a new MimeBodyPart instance./*from  w  w  w .j a  v  a  2  s .c om*/
 *
 * @param content
 * @param type
 * @return
 * @throws MessagingException
 */
public MimeBodyPart newBodyPart(String content, MediaType type) throws MessagingException {
    MimeBodyPart bodyPart = bodyPartProvider.get();
    bodyPart.setContent(content, type.toString());

    return bodyPart;
}

From source file:google.registry.storage.drive.DriveConnection.java

/**
 * Updates the file with the given id in place, setting the title, content, and mime type to
 * the newly specified values.//  w  w w.ja  v a  2s.c  o m
 *
 * @returns the file id.
 */
public String updateFile(String fileId, String title, MediaType mimeType, byte[] bytes) throws IOException {
    File file = new File().setTitle(title);
    return drive.files().update(fileId, file, new ByteArrayContent(mimeType.toString(), bytes)).execute()
            .getId();
}

From source file:org.opentestsystem.delivery.testreg.rest.TemplateDownloadController.java

@RequestMapping(value = "/template/{filename:.+}", method = RequestMethod.GET)
@Secured({ "ROLE_Template Download" })
public void templatePage(@PathVariable final String filename, HttpServletResponse response) throws Exception {

    MediaType mediaType = determineMediaType(filename);
    if (mediaType != null) {
        response.setHeader(CONTENT_DISPOSITION, "attachment; filename=" + getTemplateFilename(filename));
        response.setContentType(mediaType.toString());

        FormatType formatType = FormatType.valueOf(getBaseName(filename).toUpperCase());
        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(templateDownloadCreators.get(FileType.findByFilename(filename)).createTemplate(formatType),
                out);/*from  w w w . j  ava  2  s .  c  o  m*/
        out.flush();

    } else {
        response.setStatus(UNSUPPORTED_MEDIA_TYPE.value());
    }
}

From source file:org.jclouds.rackspace.cloudfiles.v1.options.UpdateCDNContainerOptions.java

/**
 * Sets the directory marker type for the Static Website.
 *//*from   w  w w .j  av  a  2 s  .  co  m*/
public UpdateCDNContainerOptions staticWebsiteDirectoryType(MediaType directoryType) {
    checkNotNull(directoryType, "directoryType cannot be null");
    headers.put(STATIC_WEB_DIRECTORY_TYPE, directoryType.toString());
    return this;
}

From source file:com.kolich.curacao.entities.mediatype.AbstractBinaryContentTypeCuracaoEntity.java

public AbstractBinaryContentTypeCuracaoEntity(final int statusCode, final MediaType mediaType,
        final byte[] data) {
    this(statusCode,
            // Only pass the converted media type (content type) to the parent
            // class if the incoming media type was non-null.
            (mediaType == null) ? null : mediaType.toString(), data);
}

From source file:google.registry.storage.drive.DriveConnection.java

/**
 * Creates a file with the given parent.
 *
 * @returns the file id.//from   www. java  2  s.  co m
 */
public String createFile(String title, MediaType mimeType, String parentFolderId, byte[] bytes)
        throws IOException {
    return drive.files().insert(createFileReference(title, mimeType, parentFolderId),
            new ByteArrayContent(mimeType.toString(), bytes)).execute().getId();
}

From source file:com.bennavetta.appsite.file.ResourceService.java

public Resource create(String path, MediaType mime, ReadableByteChannel src) throws IOException {
    String normalized = PathUtils.normalize(path);
    log.debug("Creating resource {}", normalized);

    AppEngineFile file = fs.createNewBlobFile(mime.toString(), normalized);
    FileWriteChannel channel = fs.openWriteChannel(file, true);

    MessageDigest digest = null;/*from  w  ww . j  a v a 2  s.  c o  m*/
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 not available", e);
    }
    ByteBuffer buf = ByteBuffer.allocateDirect(bufferSize.get());
    while (src.read(buf) != -1 || buf.position() != 0) {
        buf.flip();
        int read = channel.write(buf);
        if (read != 0) {
            int origPos = buf.position();
            int origLimit = buf.limit();
            buf.position(origPos - read);
            buf.limit(origPos);
            digest.update(buf);
            buf.limit(origLimit);
            buf.position(origPos);
        }

        buf.compact();
    }

    channel.closeFinally();
    Resource resource = new Resource(normalized, fs.getBlobKey(file).getKeyString(), digest.digest(), mime);
    resource.save();
    return resource;
}

From source file:google.registry.tools.AppEngineConnection.java

@Override
public String send(String endpoint, Map<String, ?> params, MediaType contentType, byte[] payload)
        throws IOException {
    GenericUrl url = new GenericUrl(String.format("%s%s", getServerUrl(), endpoint));
    url.putAll(params);/*from   ww  w  . j ava  2  s. c o  m*/
    HttpRequest request = requestFactory.buildPostRequest(url,
            new ByteArrayContent(contentType.toString(), payload));
    HttpHeaders headers = request.getHeaders();
    headers.setCacheControl("no-cache");
    headers.put(X_CSRF_TOKEN, ImmutableList.of(xsrfToken.get()));
    headers.put(X_REQUESTED_WITH, ImmutableList.of("RegistryTool"));
    request.setHeaders(headers);
    request.setFollowRedirects(false);
    request.setThrowExceptionOnExecuteError(false);
    request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
        @Override
        public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
                throws IOException {
            String errorTitle = extractHtmlTitle(getErrorHtmlAsString(response));
            throw new IOException(String.format("Error from %s: %d %s%s", request.getUrl().toString(),
                    response.getStatusCode(), response.getStatusMessage(),
                    (errorTitle == null ? "" : ": " + errorTitle)));
        }
    });
    HttpResponse response = null;
    try {
        response = request.execute();
        return CharStreams.toString(new InputStreamReader(response.getContent(), UTF_8));
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
}

From source file:org.openqa.grid.web.servlet.DisplayHelpHandler.java

@Override
public void execute(HttpRequest req, HttpResponse resp) throws IOException {
    String resource = req.getUri();
    if (resource.contains(HELPER_SERVLET_ASSET_PATH_PREFIX)
            && !resource.replace(HELPER_SERVLET_ASSET_PATH_PREFIX, "").contains("/")
            && !resource.replace(HELPER_SERVLET_ASSET_PATH_PREFIX, "").equals("")) {
        // request is for an asset of the help page
        resource = resource.replace(HELPER_SERVLET_ASSET_PATH_PREFIX, "");
        int index = resource.lastIndexOf('.');
        MediaType type = HTML_UTF_8;
        if (index != -1) {
            String extension = resource.substring(index);
            type = TYPES.getOrDefault(extension, HTML_UTF_8);
        }//w ww.j a  va 2  s.c  o m

        resp.setHeader("Content-Type", type.toString());

        try (InputStream in = getResourceInputStream(resource)) {
            if (in == null) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            } else {
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.setContent(ByteStreams.toByteArray(in));
                return;
            }
        }
    } else {
        // request is for an unknown entity. show the help page
        try (InputStream in = getResourceInputStream(HELPER_SERVLET_TEMPLATE)) {
            if (in == null) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            } else {
                StringBuilder jsonBuilder = new StringBuilder();
                try (JsonOutput out = json.newOutput(jsonBuilder)) {
                    out.setPrettyPrint(false).write(servletConfig);
                }

                final String json = jsonBuilder.toString();

                final String htmlTemplate;
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8))) {
                    htmlTemplate = reader.lines().collect(Collectors.joining("\n"));
                }
                final String updatedTemplate = htmlTemplate.replace(HELPER_SERVLET_TEMPLATE_CONFIG_JSON_VAR,
                        json);
                if (resource.equals("/")) {
                    resp.setStatus(HttpServletResponse.SC_OK);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }

                resp.setHeader("Content-Type", HTML_UTF_8.toString());
                resp.setContent(updatedTemplate.getBytes(UTF_8));
            }
        }
    }
}