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:org.haiku.haikudepotserver.userrating.CreatedUserRatingSyndEntrySupplier.java
@Override public List<SyndEntry> generate(final FeedSpecification specification) { Preconditions.checkNotNull(specification); if (specification.getSupplierTypes().contains(FeedSpecification.SupplierType.CREATEDUSERRATING)) { if (null != specification.getPkgNames() && specification.getPkgNames().isEmpty()) { return Collections.emptyList(); }//from ww w. j av a2s .com ObjectSelect<UserRating> objectSelect = ObjectSelect.query(UserRating.class) .where(UserRating.ACTIVE.isTrue()).and(UserRating.PKG_VERSION.dot(PkgVersion.ACTIVE).isTrue()) .and(UserRating.PKG_VERSION.dot(PkgVersion.PKG).dot(Pkg.ACTIVE).isTrue()) .statementFetchSize(specification.getLimit()).orderBy(UserRating.CREATE_TIMESTAMP.desc()); if (null != specification.getPkgNames()) { objectSelect.and( UserRating.PKG_VERSION.dot(PkgVersion.PKG).dot(Pkg.NAME).in(specification.getPkgNames())); } List<UserRating> userRatings = objectSelect.select(serverRuntime.newContext()); return userRatings.stream().map(ur -> { SyndEntry entry = new SyndEntryImpl(); entry.setPublishedDate(ur.getCreateTimestamp()); entry.setUpdatedDate(ur.getModifyTimestamp()); entry.setAuthor(ur.getUser().getNickname()); entry.setUri(URI_PREFIX + Hashing.sha1() .hashUnencodedChars(String.format("%s_::_%s_::_%s_::_%s", this.getClass().getCanonicalName(), ur.getPkgVersion().getPkg().getName(), ur.getPkgVersion().toVersionCoordinates().toString(), ur.getUser().getNickname())) .toString()); entry.setLink(String.format("%s/#!/userrating/%s", baseUrl, ur.getCode())); entry.setTitle(messageSource.getMessage( "feed.createdUserRating.atom.title", new Object[] { ur.getPkgVersion().toStringWithPkgAndArchitecture(), ur.getUser().getNickname() }, new Locale(specification.getNaturalLanguageCode()))); String contentString = ur.getComment(); if (null != contentString && contentString.length() > CONTENT_LENGTH) { contentString = contentString.substring(0, CONTENT_LENGTH) + "..."; } // if there is a rating then express this as a string using unicode // characters. if (null != ur.getRating()) { contentString = buildRatingIndicator(ur.getRating()) + (Strings.isNullOrEmpty(contentString) ? "" : " -- " + contentString); } SyndContentImpl content = new SyndContentImpl(); content.setType(MediaType.PLAIN_TEXT_UTF_8.type()); content.setValue(contentString); entry.setDescription(content); return entry; }).collect(Collectors.toList()); } return Collections.emptyList(); }
From source file:org.haiku.haikudepotserver.pkg.controller.PkgSearchController.java
/** * <p>This method will try to find the identified package. If it finds it then it will redirect to a view of * that package. If it does not find it then it will redirect to a search page querying that expression.</p> *//*from w ww . j a v a2s .c o m*/ @RequestMapping(value = "search", method = RequestMethod.GET) public void handleSearch(HttpServletResponse response, @RequestParam(value = KEY_QUERY, required = false) String query) throws IOException { if (null != query) { query = query.trim().toLowerCase(); } UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl); Optional<PkgVersion> pkgVersionOptional = Optional.empty(); if (!Strings.isNullOrEmpty(query) && Pkg.PATTERN_NAME.matcher(query).matches()) { ObjectContext context = serverRuntime.newContext(); Optional<Pkg> pkgOptional = Pkg.tryGetByName(context, query); if (pkgOptional.isPresent()) { pkgVersionOptional = pkgService.getLatestPkgVersionForPkg(context, pkgOptional.get(), Repository.getByCode(context, Repository.CODE_DEFAULT), // TODO - user interface for choosing? Collections .singletonList(Architecture.tryGetByCode(context, defaultArchitectureCode).get())); } } if (pkgVersionOptional.isPresent()) { PkgVersion pv = pkgVersionOptional.get(); builder.pathSegment("#!", "pkg", pv.getPkg().getName()); pv.toVersionCoordinates().appendPathSegments(builder); builder.pathSegment(pv.getArchitecture().getCode()); } else { builder.path("#!/"); builder.queryParam(KEY_QUERY, query); } String uri = builder.build().toUriString(); response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setHeader(HttpHeaders.LOCATION, uri); response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); PrintWriter printWriter = response.getWriter(); printWriter.print(uri); printWriter.flush(); }
From source file:com.linecorp.armeria.server.http.Http2RequestDecoder.java
private void writeErrorResponse(ChannelHandlerContext ctx, int streamId, HttpResponseStatus status) { final byte[] content = status.toString().getBytes(StandardCharsets.UTF_8); writer.writeHeaders(ctx, streamId,/*from w w w . j ava 2 s . com*/ new DefaultHttp2Headers(false).status(status.codeAsText()) .set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()) .setInt(HttpHeaderNames.CONTENT_LENGTH, content.length), 0, false, ctx.voidPromise()); writer.writeData(ctx, streamId, Unpooled.wrappedBuffer(content), 0, true, ctx.voidPromise()); }
From source file:brooklyn.util.net.Urls.java
/** as {@link #asDataUrlBase64(String)} with plain text */ public static String asDataUrlBase64(String data) { return asDataUrlBase64(MediaType.PLAIN_TEXT_UTF_8, data.getBytes()); }
From source file:com.linecorp.armeria.server.http.Http1RequestDecoder.java
private void fail(ChannelHandlerContext ctx, HttpResponseStatus status) { discarding = true;/* w w w. j ava2 s . c o m*/ req = null; final ChannelFuture future; if (receivedRequests <= sentResponses) { // Just close the connection if sending an error response will make the number of the sent // responses exceed the number of the received requests, which doesn't make sense. future = ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); } else { final ByteBuf content = Unpooled.copiedBuffer(status.toString(), StandardCharsets.UTF_8); final FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content); final HttpHeaders headers = res.headers(); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8); headers.setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); future = ctx.writeAndFlush(res); } future.addListener(ChannelFutureListener.CLOSE); }
From source file:com.linecorp.armeria.server.http.HttpResponseSubscriber.java
private void failAndRespond(Throwable cause, HttpStatus status, Http2Error error) { final State state = this.state; fail(cause);//from w w w . j a v a 2 s. co m final int id = req.id(); final int streamId = req.streamId(); if (wroteNothing(state)) { // Did not write anything yet; we can send an error response instead of resetting the stream. final HttpData content = status.toHttpData(); responseEncoder.writeHeaders(ctx, id, streamId, HttpHeaders.of(status).set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()) .setInt(HttpHeaderNames.CONTENT_LENGTH, content.length()), false); responseEncoder.writeData(ctx, id, streamId, content, true); } else { // Wrote something already; we have to reset/cancel the stream. responseEncoder.writeReset(ctx, id, streamId, error); } ctx.flush(); }
From source file:com.linecorp.armeria.server.thrift.ThriftServiceCodec.java
private static DefaultFullHttpResponse errorResponse(HttpResponseStatus status) { final DefaultFullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(status.toString(), StandardCharsets.UTF_8)); res.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()); return res;/* w ww.j a va2 s.c o m*/ }
From source file:com.mastfrog.acteur.ActeurFactory.java
/** * Reject the request unless certain URL parameters are present * * @param names The parameter names//from w w w. j a va 2 s.c o m * @return An acteur */ public Acteur requireParameters(final String... names) { @Description("Requires specific parameters") class RequireParameters extends Acteur { @Override public com.mastfrog.acteur.State getState() { HttpEvent event = deps.getInstance(HttpEvent.class); for (String nm : names) { String val = event.getParameter(nm); if (val == null) { add(Headers.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.withCharset(charset)); return new RespondWith(Err.badRequest("Missing URL parameter '" + nm + "'\n")); } } return new ConsumedState(); } @Override public String toString() { return "Require Parameters " + Arrays.asList(names); } @Override public void describeYourself(Map<String, Object> into) { into.put("requiredParameters", names); } } return new RequireParameters(); }
From source file:com.google.zxing.web.DecodeServlet.java
private static void processImage(BufferedImage image, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<>(1); try {/* www. j av a2s .c o m*/ Reader reader = new MultiFormatReader(); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { throw savedException == null ? NotFoundException.getNotFoundInstance() : savedException; } catch (FormatException | ChecksumException e) { log.info(e.getMessage()); errorResponse(request, response, "format"); } catch (ReaderException e) { // Including NotFoundException log.info(e.getMessage()); errorResponse(request, response, "notfound"); } return; } } catch (RuntimeException re) { // Call out unexpected errors in the log clearly log.log(Level.WARNING, "Unexpected exception from library", re); throw new ServletException(re); } String fullParameter = request.getParameter("full"); boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter); if (minimalOutput) { response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
From source file:net.myrrix.client.ClientRecommender.java
private void doSetOrRemove(String path, long unnormalizedID, float value, boolean set) throws TasteException { boolean sendValue = value != 1.0f; Map<String, String> requestProperties; byte[] bytes; if (sendValue) { requestProperties = Maps.newHashMapWithExpectedSize(2); bytes = Float.toString(value).getBytes(Charsets.UTF_8); requestProperties.put(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()); requestProperties.put(HttpHeaders.CONTENT_LENGTH, Integer.toString(bytes.length)); } else {/*from ww w .j av a 2 s .c om*/ requestProperties = null; bytes = null; } TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(unnormalizedID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, path, set ? "POST" : "DELETE", sendValue, false, requestProperties); if (sendValue) { OutputStream out = connection.getOutputStream(); out.write(bytes); out.close(); } // Should not be able to return Not Available status if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } return; } catch (TasteException te) { log.info("Can't access {} at {}: ({})", path, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", path, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }