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

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

Introduction

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

Prototype

MediaType PLAIN_TEXT_UTF_8

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

Click Source Link

Usage

From source file:com.acme.ecards.api.email.impl.EmailSender.java

/**
 * Send an email message using the given email message and session.
 *
 * @param emailMessage email message context object
 * @param session java mail session object used to send the message.
 *///ww  w .  j a va  2s. com
public void send(EmailMessage emailMessage, Session session) {
    try {
        @SuppressWarnings("unchecked")
        Map<String, Map<String, String>> emailServices = (Map) config.get("email-services");
        Map<String, String> fromConfig = emailServices.get("from");
        Map<String, String> replyConfig = emailServices.get("reply");

        InternetAddress from = messageFactory.newInternetAddress(fromConfig.get("email"),
                fromConfig.get("personal"));

        InternetAddress reply = messageFactory.newInternetAddress(replyConfig.get("email"),
                replyConfig.get("personal"));

        InternetAddress to = messageFactory.newInternetAddress(emailMessage.getEmail(),
                emailMessage.getPersonal());

        EmailTemplate emailTemplate = templateFactory.load(emailMessage.getTemplateId());

        String subject = templateFactory.interpolate(emailTemplate.getSubject(), emailMessage);
        String plainContent = templateFactory.interpolate(emailTemplate.getPlain(), emailMessage);
        String htmlContent = templateFactory.interpolate(emailTemplate.getHtml(), emailMessage);

        MimeBodyPart plainPart = messageFactory.newBodyPart(plainContent, MediaType.PLAIN_TEXT_UTF_8);
        MimeBodyPart htmlPart = messageFactory.newBodyPart(htmlContent, MediaType.HTML_UTF_8);

        MimeMultipart content = messageFactory.newMultipart(plainPart, htmlPart);
        MimeMessage mimeMessage = messageFactory.newMessage(from, reply, to, subject, content);

        sessionService.send(session, mimeMessage);
    } catch (MessagingException e) {
        throw new EmailException("could not send email", e);
    } catch (IOException e) {
        throw new EmailException("could not load email template", e);
    }
}

From source file:org.haiku.haikudepotserver.operations.controller.MaintenanceController.java

/**
 * <p>This triggers hourly tasks.</p>
 *//* w w  w  .j  ava  2s.  c o  m*/

// TODO; remove "mediumterm".

@RequestMapping(path = { "/mediumterm", "/hourly" }, method = RequestMethod.GET)
public void hourly(HttpServletResponse response) throws IOException {

    // remove any jobs which are too old and are no longer required.

    jobService.clearExpiredJobs();

    // remove any expired password reset tokens.

    {
        if (UserPasswordResetToken.hasAny(serverRuntime.newContext())) {
            jobService.submit(new PasswordResetMaintenanceJobSpecification(),
                    JobSnapshot.COALESCE_STATUSES_QUEUED_STARTED);
        } else {
            LOGGER.debug("did not submit task for password reset maintenance as there are no tokens stored");
        }
    }

    LOGGER.info("did trigger hourly maintenance");

    response.setStatus(HttpServletResponse.SC_OK);
    response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString());
    response.getWriter().print("accepted request for hourly maintenance");

}

From source file:org.glowroot.ui.HttpServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    FullHttpRequest request = (FullHttpRequest) msg;
    if (request.decoderResult().isFailure()) {
        CommonResponse response = new CommonResponse(BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8,
                Strings.nullToEmpty(request.decoderResult().cause().getMessage()));
        sendResponse(ctx, request, response, false);
        return;/*  ww w.  j  a v  a  2 s  .c o  m*/
    }
    String uri = request.uri();
    logger.debug("channelRead(): request.uri={}", uri);
    Channel channel = ctx.channel();
    currentChannel.set(channel);
    try {
        String contextPath = contextPathSupplier.get();
        boolean keepAlive = HttpUtil.isKeepAlive(request);
        if (!uri.startsWith(contextPath)) {
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
            response.headers().set(HttpHeaderNames.LOCATION, contextPath);
            sendFullResponse(ctx, request, response, keepAlive);
            return;
        }
        QueryStringDecoder decoder = new QueryStringDecoder(stripContextPath(uri, contextPath));
        CommonRequest commonRequest = new NettyRequest(request, contextPath, decoder);
        CommonResponse response = commonHandler.handle(commonRequest);
        if (response.isCloseConnectionAfterPortChange()) {
            response.setHeader("Connection", "close");
            keepAlive = false;
        }
        sendResponse(ctx, request, response, keepAlive);
    } catch (Exception e) {
        logger.error("error handling request {}: {}", uri, e.getMessage(), e);
        CommonResponse response = CommonHandler.newHttpResponseWithStackTrace(e, INTERNAL_SERVER_ERROR, null);
        sendResponse(ctx, request, response, false);
    } finally {
        currentChannel.remove();
        request.release();
    }
}

From source file:org.glowroot.ui.GlowrootLogHttpService.java

@Override
public CommonResponse handleRequest(CommonRequest request, Authentication authentication) throws Exception {
    List<String> maxLinesParams = request.getParameters("max-lines");
    if (maxLinesParams.isEmpty()) {
        CommonResponse response = new CommonResponse(FOUND);
        response.setHeader(HttpHeaderNames.LOCATION, "log?max-lines=" + DEFAULT_MAX_LINES);
        return response;
    }/*from   w w  w  .  ja  va2s .  co  m*/
    int maxLines = Integer.parseInt(maxLinesParams.get(0));

    File[] list = logDir.listFiles();
    if (list == null) {
        throw new IllegalStateException("Could not list directory: " + logDir.getAbsolutePath());
    }
    List<File> files = Lists.newArrayList();
    for (File file : list) {
        if (file.isFile() && logFileNamePattern.matcher(file.getName()).matches()) {
            files.add(file);
        }
    }
    files = byLastModified.reverse().sortedCopy(files);
    List<String> lines = Lists.newArrayList();
    for (File file : files) {
        // don't read entire file into memory at once, even though rollover may be 10mb, a flood
        // of logging can create a much much much larger file before rollover occurs
        // (see ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy call to isTooSoon())

        // logback writes logs in default charset
        // "+ 1" is to read extra line to know whether to add "[earlier log entries truncated]"
        Collection<String> olderLines = Files.readLines(file, Charset.defaultCharset(),
                new ReadLastNLines(maxLines + 1 - lines.size()));
        lines.addAll(0, olderLines);
        if (lines.size() > maxLines) {
            break;
        }
    }
    List<ChunkSource> chunkSources = Lists.newArrayList();
    if (lines.size() > maxLines) {
        // return last 'maxLines' lines from aggregated log files
        lines = lines.subList(lines.size() - maxLines, lines.size());
        chunkSources.add(ChunkSource.wrap("[earlier log entries truncated]\n\n"));
    }
    for (String line : lines) {
        chunkSources.add(ChunkSource.wrap(line + '\n'));
    }
    return new CommonResponse(OK, MediaType.PLAIN_TEXT_UTF_8, ChunkSource.concat(chunkSources));
}

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

@Override
protected String execute() throws Exception {
    System.err.println("Initiating load test...");

    ImmutableMap<String, Object> params = new ImmutableMap.Builder<String, Object>().put("tld", tld)
            .put("clientId", clientId).put("successfulHostCreates", successfulHostCreates)
            .put("successfulDomainCreates", successfulDomainCreates)
            .put("successfulContactCreates", successfulContactCreates).put("hostInfos", hostInfos)
            .put("domainInfos", domainInfos).put("contactInfos", contactInfos).put("runSeconds", runSeconds)
            .build();//  w ww .ja  v  a  2  s.c o  m

    return connection.send(LoadTestAction.PATH, params, MediaType.PLAIN_TEXT_UTF_8, new byte[0]);
}

From source file:com.mastfrog.acteur.server.EventImpl.java

@Override
public String getContentAsString() throws IOException {
    MediaType type = getHeader(Headers.CONTENT_TYPE);
    if (type == null) {
        type = MediaType.PLAIN_TEXT_UTF_8;
    }//from   w w w.j  a va  2  s  .  co m
    Charset encoding;
    if (type.charset().isPresent()) {
        encoding = type.charset().get();
    } else {
        encoding = CharsetUtil.UTF_8;
    }
    return converter.toString(getContent(), encoding);
}

From source file:com.mastfrog.tinymavenproxy.GetActeur.java

private static MediaType findMimeType(Path path) {
    if (path.size() == 0) {
        return MediaType.ANY_APPLICATION_TYPE;
    }/*  w  ww.  j a  v  a 2  s . c  o  m*/
    String file = path.getLastElement().toString();
    int ix = file.lastIndexOf(".");
    if (ix < 0) {
        return MediaType.ANY_APPLICATION_TYPE;
    }
    String ext = file.substring(ix + 1);
    switch (ext) {
    case "html":
        return MediaType.HTML_UTF_8;
    case "jar":
        return MediaType.parse("application/java-archive");
    case "xml":
    case "pom":
        return MediaType.XML_UTF_8;
    case "sha1":
    default:
        return MediaType.PLAIN_TEXT_UTF_8;
    }
}

From source file:com.mastfrog.acteur.ActeurFactory.java

/**
 * Reject the request if it is not an allowed HTTP method, optionally
 * including information in the response, or simply rejecting the request
 * and allowing the next page a crack at it.
 *
 * @param notSupp If true, respond with METHOD_NOT_ALLOWED and the ALLOW
 * header set/*from   w  w  w .j a  v  a2 s. c o m*/
 * @param methods The http methods which are allowed
 * @return An Acteur
 */
public Acteur matchMethods(final boolean notSupp, final Method... methods) {
    class MatchMethods extends Acteur {

        @Override
        public com.mastfrog.acteur.State getState() {
            HttpEvent event = deps.getInstance(HttpEvent.class);
            boolean hasMethod = Arrays.asList(methods).contains(event.getMethod());
            add(Headers.ALLOW, methods);
            if (notSupp && !hasMethod) {
                add(Headers.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.withCharset(charset));
                return new RespondWith(new Err(HttpResponseStatus.METHOD_NOT_ALLOWED,
                        "405 Method " + event.getMethod() + " not allowed.  Accepted methods are "
                                + Headers.ALLOW.toString(methods) + "\n"));
            }
            com.mastfrog.acteur.State result = hasMethod ? new ConsumedState() : new RejectedState();
            return result;
        }

        @Override
        public String toString() {
            return "Match Methods " + Arrays.asList(methods);
        }

        @Override
        public void describeYourself(Map<String, Object> into) {
            into.put("Methods", methods);
        }
    }
    return new MatchMethods();
}

From source file:org.haiku.haikudepotserver.pkg.CreatedPkgVersionSyndEntrySupplier.java

@Override
public List<SyndEntry> generate(final FeedSpecification specification) {
    Preconditions.checkNotNull(specification);

    if (specification.getSupplierTypes().contains(FeedSpecification.SupplierType.CREATEDPKGVERSION)) {

        if (null != specification.getPkgNames() && specification.getPkgNames().isEmpty()) {
            return Collections.emptyList();
        }/*from   w w w.j  a va2s  .c o  m*/

        ObjectSelect<PkgVersion> objectSelect = ObjectSelect.query(PkgVersion.class)
                .where(PkgVersion.ACTIVE.isTrue()).and(PkgVersion.PKG.dot(Pkg.ACTIVE).isTrue())
                .orderBy(PkgVersion.CREATE_TIMESTAMP.desc()).limit(specification.getLimit());

        if (null != specification.getPkgNames()) {
            objectSelect.and(PkgVersion.PKG.dot(Pkg.NAME).in(specification.getPkgNames()));
        }

        ObjectContext context = serverRuntime.newContext();

        NaturalLanguage naturalLanguage = Strings.isBlank(specification.getNaturalLanguageCode())
                ? NaturalLanguage.getEnglish(context)
                : NaturalLanguage.getByCode(context, specification.getNaturalLanguageCode())
                        .orElseThrow(() -> new IllegalStateException(
                                "unable to find natural language; " + specification.getNaturalLanguageCode()));

        List<PkgVersion> pkgVersions = objectSelect.select(context);

        return pkgVersions.stream().map(pv -> {
            SyndEntry entry = new SyndEntryImpl();

            entry.setPublishedDate(pv.getCreateTimestamp());
            entry.setUpdatedDate(pv.getModifyTimestamp());
            entry.setUri(URI_PREFIX + Hashing.sha1()
                    .hashUnencodedChars(String.format("%s_::_%s_::_%s", this.getClass().getCanonicalName(),
                            pv.getPkg().getName(), pv.toVersionCoordinates().toString()))
                    .toString());

            {
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl).pathSegment("#",
                        "pkg");
                pv.appendPathSegments(builder);
                entry.setLink(builder.build().toUriString());
            }

            entry.setTitle(messageSource.getMessage("feed.createdPkgVersion.atom.title",
                    new Object[] { pv.toStringWithPkgAndArchitecture() },
                    new Locale(specification.getNaturalLanguageCode())));

            {
                ResolvedPkgVersionLocalization resolvedPkgVersionLocalization = pkgLocalizationService
                        .resolvePkgVersionLocalization(context, pv, null, naturalLanguage);

                SyndContent content = new SyndContentImpl();
                content.setType(MediaType.PLAIN_TEXT_UTF_8.type());
                content.setValue(resolvedPkgVersionLocalization.getSummary());
                entry.setDescription(content);
            }

            return entry;
        }).collect(Collectors.toList());

    }

    return Collections.emptyList();
}

From source file:org.haiku.haikudepotserver.pkg.controller.PkgDownloadController.java

@RequestMapping(value = { "/" + SEGMENT_PKGDOWNLOAD + PATH }, method = RequestMethod.GET)
public void download(HttpServletResponse response, @PathVariable(value = KEY_PKGNAME) String pkgName,
        @PathVariable(value = KEY_REPOSITORYCODE) String repositoryCode,
        @PathVariable(value = KEY_MAJOR) String major, @PathVariable(value = KEY_MINOR) String minor,
        @PathVariable(value = KEY_MICRO) String micro, @PathVariable(value = KEY_PRERELEASE) String prerelease,
        @PathVariable(value = KEY_REVISION) String revisionStr,
        @PathVariable(value = KEY_ARCHITECTURECODE) String architectureCode)
        throws IOException, RequestObjectNotFound {

    Preconditions.checkArgument(null != response, "the response is required");

    ObjectContext context = serverRuntime.newContext();

    Pkg pkg = Pkg.tryGetByName(context, pkgName).orElseThrow(() -> {
        LOGGER.info("unable to find the package; {}", pkgName);
        return new RequestObjectNotFound();
    });//from ww  w .  j  av a 2s.  c  om

    Repository repository = Repository.tryGetByCode(context, repositoryCode).orElseThrow(() -> {
        LOGGER.info("unable to find the repository; {}", repositoryCode);
        return new RequestObjectNotFound();
    });

    Architecture architecture = Architecture.tryGetByCode(context, architectureCode).orElseThrow(() -> {
        LOGGER.info("unable to find the architecture; {}", architectureCode);
        return new RequestObjectNotFound();
    });

    revisionStr = hyphenToNull(revisionStr);

    VersionCoordinates versionCoordinates = new VersionCoordinates(hyphenToNull(major), hyphenToNull(minor),
            hyphenToNull(micro), hyphenToNull(prerelease),
            null == revisionStr ? null : Integer.parseInt(revisionStr));

    PkgVersion pkgVersion = PkgVersion.getForPkg(context, pkg, repository, architecture, versionCoordinates)
            .orElseThrow(() -> {
                LOGGER.info("unable to find the pkg version; {}, {}", pkgName, versionCoordinates);
                return new RequestObjectNotFound();
            });

    Optional<URL> urlOptional = pkgVersion.tryGetHpkgURL();

    if (!urlOptional.isPresent()) {
        LOGGER.info("unable to allow download of the hpkg data as no url was able to be generated");
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        URL url = urlOptional.get();

        // if it is an HTTP URL then it should be possible to redirect the browser to that URL
        // instead of piping it through the application server.

        if (ImmutableSet.of("http", "https").contains(url.getProtocol())) {
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader(HttpHeaders.LOCATION, url.toString());
            response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString());

            PrintWriter writer = response.getWriter();
            writer.print(url.toString());
            writer.flush();
        } else {
            response.setContentType(MediaType.OCTET_STREAM.toString());
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    String.format("attachment; filename=\"%s\"", pkgVersion.getHpkgFilename()));

            try (InputStream inputStream = url.openStream()) {
                LOGGER.info("downloaded package version; {} - {}", pkg.getName(), pkgVersion);
                ByteStreams.copy(inputStream, response.getOutputStream());
            } catch (IOException ioe) {
                // logged without a stack trace because it happens fairly often that a robot will initiate the download and then drop it.
                LOGGER.error("unable to relay data to output stream from '{}'; {} -- {}", url.toString(),
                        ioe.getClass().getSimpleName(), ioe.getMessage());
            }
        }
    }
}