List of usage examples for com.google.common.net MediaType PLAIN_TEXT_UTF_8
MediaType PLAIN_TEXT_UTF_8
To view the source code for com.google.common.net MediaType PLAIN_TEXT_UTF_8.
Click Source Link
From source file:google.registry.tools.DeleteEntityCommand.java
@Override protected String execute() throws Exception { String rawKeysJoined = Joiner.on(",").join(rawKeyStrings); return connection.send(DeleteEntityAction.PATH, ImmutableMap.of(DeleteEntityAction.PARAM_RAW_KEYS, rawKeysJoined), MediaType.PLAIN_TEXT_UTF_8, new byte[0]); }
From source file:org.pentaho.di.trans.dataservice.optimization.cache.ResetCacheServlet.java
@Override public void handleRequest(CarteRequest request) throws IOException { Collection<String> names = request.getParameters().get(NAME_PARAMETER); if (names == null || names.isEmpty()) { request.respond(400).withMessage(NAME_PARAMETER + " not specified"); return;/* w ww. ja v a 2s .c om*/ } final Set<Cache> cacheSet = FluentIterable.from(names).transform(new Function<String, Cache>() { @Override public Cache apply(String name) { return factory.getCache(name).orNull(); } }).filter(Predicates.notNull()).toSet(); for (Cache cache : cacheSet) { cache.clear(); } request.respond(200).with(MediaType.PLAIN_TEXT_UTF_8.toString(), new WriterResponse() { @Override public void write(PrintWriter writer) throws IOException { if (cacheSet.isEmpty()) { writer.println("No matching caches to flush."); } for (Cache cache : cacheSet) { writer.println("Cleared cache: " + cache.getName()); } writer.println("Done"); } }); }
From source file:org.haiku.haikudepotserver.operations.controller.MaintenanceController.java
/** * <p>This triggers daily tasks.</p> *//*from ww w .j a v a 2 s. c o m*/ @RequestMapping(value = "/daily", method = RequestMethod.GET) public void daily(HttpServletResponse response) throws IOException { // go through all of the repositories and fetch them. This is essentially a mop-up // task for those repositories that are unable to trigger a refresh. { ObjectContext context = serverRuntime.newContext(); for (Repository repository : Repository.getAllActive(context)) { jobService.submit(new RepositoryHpkrIngressJobSpecification(repository.getCode()), JobSnapshot.COALESCE_STATUSES_QUEUED); } } LOGGER.info("did trigger daily maintenance"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()); response.getWriter().print("accepted request for daily maintenance"); }
From source file:com.linecorp.armeria.server.grpc.GrpcService.java
@Override protected void doPost(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) throws Exception { if (!verifyContentType(req.headers())) { res.respond(HttpStatus.BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Missing or invalid Content-Type header."); return;// w w w .j a va 2 s .co m } String methodName = determineMethod(ctx); if (methodName == null) { res.respond(HttpStatus.BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Invalid path."); return; } ArmeriaGrpcServerStream stream = new ArmeriaGrpcServerStream(res, maxMessageSize); ServerMethodDefinition<?, ?> method = registry.lookupMethod(methodName); if (method == null) { stream.close(Status.UNIMPLEMENTED.withDescription("Method not found: " + methodName), EMPTY_METADATA); return; } Metadata metadata = new Metadata(convertHeadersToArray(req.headers())); ServerStreamListener listener = startCall(stream, methodName, method, metadata); stream.transportState().setListener(listener); req.subscribe(stream.messageReader()); }
From source file:io.bazel.rules.closure.http.filter.Transmitter.java
/** Handles HTTP request and returns {@code true} if connection can be re-used. */ @Override//from www . j ava 2s. c om public void handle() throws IOException { if (!SUPPORTED_VERSIONS.contains(request.getVersion())) { ByteStreams.copy(response.setStatus(505).setHeader("Connection", "close").openStream(), output); return; } try { delegate.handle(); } catch (InterruptedIOException e) { throw e; } catch (InterruptedException | ClosedByInterruptException e) { throw new InterruptedIOException(); } catch (Exception t) { logger.log(Level.SEVERE, "HTTP handling failed", t); response.setHeader("Connection", "close"); ByteStreams.copy(request.newResponse().setStatus(500).setHeader("Connection", "close") .setContentType(MediaType.PLAIN_TEXT_UTF_8) .setPayload("500 Error :(".getBytes(StandardCharsets.UTF_8)).openStream(), output); return; } ByteStreams.exhaust(request.getPayload()); ByteStreams.copy(response.openStream(), output); }
From source file:rapture.mail.Mailer.java
public static void email(String[] recipients, String subject, String message) throws MessagingException { final SMTPConfig config = getSMTPConfig(); Session session = getSession(config); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getFrom())); InternetAddress[] address = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) address[i] = new InternetAddress(recipients[i]); msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject);/*from w w w . j a v a 2s.c o m*/ msg.setContent(message, MediaType.PLAIN_TEXT_UTF_8.toString()); msg.setSentDate(new Date()); Transport.send(msg); }
From source file:google.registry.tools.CreateRegistrarGroupsCommand.java
@Override protected String execute() throws IOException { for (Registrar registrar : registrars) { connection.send(CreateGroupsAction.PATH, ImmutableMap.of(CreateGroupsAction.CLIENT_ID_PARAM, registrar.getClientId()), MediaType.PLAIN_TEXT_UTF_8, new byte[0]); }/* w ww. ja v a 2 s . c o m*/ // Note: If any of the calls fail, then a 5XX response code is returned inside of send(), which // throws an exception yielding a stack trace. If we get to this next line then we succeeded. return "Success!"; }
From source file:google.registry.tools.ListObjectsCommand.java
@Override public void run() throws Exception { ImmutableMap.Builder<String, Object> params = new ImmutableMap.Builder<>(); if (fields != null) { params.put(FIELDS_PARAM, fields); }/*from w ww . j ava2 s. c om*/ if (printHeaderRow != null) { params.put(PRINT_HEADER_ROW_PARAM, printHeaderRow); } if (fullFieldNames) { params.put(FULL_FIELD_NAMES_PARAM, Boolean.TRUE); } ImmutableMap<String, Object> extraParams = getParameterMap(); if (extraParams != null) { params.putAll(extraParams); } // Call the server and get the response data. String response = connection.send(getCommandPath(), params.build(), MediaType.PLAIN_TEXT_UTF_8, new byte[0]); // Parse the returned JSON and make sure it's a map. Object obj = JSONValue.parse(response.substring(JSON_SAFETY_PREFIX.length())); if (!(obj instanceof Map<?, ?>)) { throw new VerifyException("Server returned unexpected JSON: " + response); } @SuppressWarnings("unchecked") Map<String, Object> responseMap = (Map<String, Object>) obj; // Get the status. obj = responseMap.get("status"); if (obj == null) { throw new VerifyException("Server returned no status"); } if (!(obj instanceof String)) { throw new VerifyException("Server returned non-string status"); } String status = (String) obj; // Handle errors. if (status.equals("error")) { obj = responseMap.get("error"); if (obj == null) { throw new VerifyException("Server returned no error message"); } System.out.println(obj); // Handle success. } else if (status.equals("success")) { obj = responseMap.get("lines"); if (obj == null) { throw new VerifyException("Server returned no response data"); } if (!(obj instanceof List<?>)) { throw new VerifyException("Server returned unexpected response data"); } for (Object lineObj : (List<?>) obj) { System.out.println(lineObj); } // Handle unexpected status values. } else { throw new VerifyException("Server returned unexpected status"); } }
From source file:google.registry.export.ExportSnapshotServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException { try {/*from ww w.ja va 2 s . c o m*/ // Use a unique name for the snapshot so we can explicitly check its completion later. String snapshotName = SNAPSHOT_PREFIX + clock.nowUtc().toString("YYYYMMdd_HHmmss"); backupService.launchNewBackup(QUEUE, snapshotName, RegistryConfig.getSnapshotsBucket(), ExportConstants.getBackupKinds()); // Enqueue a poll task to monitor the backup and load reporting-related kinds into bigquery. checkSnapshotServlet.enqueuePollTask(snapshotName, ExportConstants.getReportingKinds()); String message = "Datastore backup started with name: " + snapshotName; logger.info(message); rsp.setStatus(SC_OK); rsp.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); rsp.getWriter().write("OK\n\n" + message); } catch (Throwable e) { logger.severe(e, e.toString()); rsp.sendError(e instanceof IllegalArgumentException ? SC_BAD_REQUEST : SC_INTERNAL_SERVER_ERROR, htmlEscaper().escape(firstNonNull(e.getMessage(), e.toString()))); } }
From source file:google.registry.export.CheckSnapshotServlet.java
@Override public void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException { try {/*from ww w . jav a 2 s . c om*/ rsp.setStatus(SC_OK); rsp.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); rsp.getWriter().write("OK\n\n"); super.service(req, rsp); } catch (Throwable e) { logger.severe(e, e.toString()); rsp.sendError(e instanceof IllegalArgumentException ? SC_BAD_REQUEST : SC_INTERNAL_SERVER_ERROR, htmlEscaper().escape(firstNonNull(e.getMessage(), e.toString()))); } }