List of usage examples for com.google.common.net MediaType ZIP
MediaType ZIP
To view the source code for com.google.common.net MediaType ZIP.
Click Source Link
From source file:org.pathirage.ptovrhttp.Main.java
public static void main(String[] args) { Options options = new Options(); new JCommander(options, args); log.info("Starting PairTreeOverHTTP with pairtree root: " + options.pairTreeRoot); port(options.port);//from w w w. jav a2s . c o m post("/volumes", "application/json", (request, response) -> { try { List<String> volumeZips = new ArrayList<String>(); VolumesRequest requestedVolumes = gson.fromJson(request.body(), VolumesRequest.class); for (String vol : requestedVolumes.getVolumes()) { int indexOfFirstPeriod = vol.indexOf('.'); String volId; if (!requestedVolumes.isClean()) { volId = pairtree.cleanId(vol.substring(indexOfFirstPeriod + 1)); } else { volId = vol.substring(indexOfFirstPeriod + 1); } String library = vol.substring(0, indexOfFirstPeriod); volumeZips.add(String.format("%s/%s/pairtree_root/%s/%s/%s.zip", options.pairTreeRoot, library, Joiner.on("/").join(volId.split("(?<=\\G.{2})")), volId, volId)); } response.header("Content-Disposition", String.format("attachment; filename=\"%s\"", "volumes.zip")); response.type(MediaType.ZIP.toString()); response.status(200); ZipOutputStream zos = new ZipOutputStream( new BufferedOutputStream(response.raw().getOutputStream())); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(0); byte[] buffer = new byte[1024]; for (String f : volumeZips) { File srcFile = new File(f); try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f))) { // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(srcFile.getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); } } zos.flush(); zos.close(); } catch (Exception e) { log.error("Cannot create zip.", e); halt(405, "Server Error: " + e.getMessage()); } return response.raw(); }); }
From source file:org.glowroot.local.ui.ConditionalHttpContentCompressor.java
@Override protected @Nullable Result beginEncode(HttpResponse response, String acceptEncoding) throws Exception { String contentType = response.headers().get(CONTENT_TYPE); if (contentType != null && contentType.equals(MediaType.ZIP.toString())) { // don't compress already zipped content return null; }//from w ww .j a v a 2s .c o m return super.beginEncode(response, acceptEncoding); }
From source file:org.glowroot.ui.ConditionalHttpContentCompressor.java
@Override protected @Nullable Result beginEncode(HttpResponse response, String acceptEncoding) throws Exception { String contentType = response.headers().getAsString(HttpHeaderNames.CONTENT_TYPE); if (contentType != null && contentType.equals(MediaType.ZIP.toString())) { // don't compress already zipped content return null; }/* w w w.j a va 2 s . c o m*/ return super.beginEncode(response, acceptEncoding); }
From source file:helper.ThumbnailGenerator.java
private static File generateMimeTypeImage(MediaType contentType, int size, String name) { File result = null;/* w ww . ja va 2 s. c o m*/ try { if (contentType.is(MediaType.ANY_AUDIO_TYPE)) { result = generateThumbnailFromImage(Play.application().resourceAsStream(AUDIO_PIC), size, "png", name); } else if (contentType.is(MediaType.ANY_IMAGE_TYPE)) { result = generateThumbnailFromImage(Play.application().resourceAsStream(IMAGE_PIC), size, "png", name); } else if (contentType.is(MediaType.ANY_TEXT_TYPE) || contentType.is(MediaType.OOXML_DOCUMENT) || contentType.is(MediaType.MICROSOFT_WORD)) { result = generateThumbnailFromImage(Play.application().resourceAsStream(TEXT_PIC), size, "png", name); } else if (contentType.is(MediaType.ANY_VIDEO_TYPE)) { result = generateThumbnailFromImage(Play.application().resourceAsStream(VIDEO_PIC), size, "png", name); } else if (contentType.is(MediaType.ZIP)) { result = generateThumbnailFromImage(Play.application().resourceAsStream(ZIP_PIC), size, "png", name); } else if (contentType.is(MediaType.PDF)) { result = generateThumbnailFromImage(Play.application().resourceAsStream(PDF_PIC), size, "png", name); } else { result = generateThumbnailFromImage(Play.application().resourceAsStream(MIMETYPE_NOT_FOUND_PIC), size, "png", name); } } catch (Throwable e) { play.Logger.warn("", e); result = generateThumbnailFromImage(Play.application().resourceAsStream(EXCEPTION_ON_APPLY_MIMETYPE), size, "png", name); } return result; }
From source file:org.glowroot.local.ui.TraceExportHttpService.java
@Override public @Nullable FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception { String uri = request.getUri(); String id = uri.substring(uri.lastIndexOf('/') + 1); logger.debug("handleRequest(): id={}", id); TraceExport export = traceCommonService.getExport(id); if (export == null) { logger.warn("no trace found for id: {}", id); return new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); }/*from ww w . j av a 2s .c o m*/ ChunkedInput<HttpContent> in = getExportChunkedInput(export); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); response.headers().set(CONTENT_TYPE, MediaType.ZIP.toString()); response.headers().set("Content-Disposition", "attachment; filename=" + getFilename(export.trace()) + ".zip"); boolean keepAlive = HttpHeaders.isKeepAlive(request); if (keepAlive && !request.getProtocolVersion().isKeepAliveDefault()) { response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); } HttpServices.preventCaching(response); ctx.write(response); ChannelFuture future = ctx.write(in); HttpServices.addErrorListener(future); if (!keepAlive) { HttpServices.addCloseListener(future); } // return null to indicate streaming return null; }
From source file:org.glowroot.ui.TraceExportHttpService.java
@Override public CommonResponse handleRequest(CommonRequest request, Authentication authentication) throws Exception { auditLogger.info("{} - GET {}", authentication.caseAmbiguousUsername(), request.getUri()); List<String> agentIds = request.getParameters("agent-id"); String agentId = agentIds.isEmpty() ? "" : agentIds.get(0); List<String> traceIds = request.getParameters("trace-id"); checkState(!traceIds.isEmpty(), "Missing trace id in query string: %s", request.getUri()); String traceId = traceIds.get(0); // check-live-traces is an optimization so the central collector only has to check with // remote agents when necessary List<String> checkLiveTracesParams = request.getParameters("check-live-traces"); boolean checkLiveTraces = !checkLiveTracesParams.isEmpty() && Boolean.parseBoolean(checkLiveTracesParams.get(0)); logger.debug("handleRequest(): agentId={}, traceId={}, checkLiveTraces={}", agentId, traceId, checkLiveTraces);//w ww. jav a 2 s. co m TraceExport traceExport = traceCommonService.getExport(agentId, traceId, checkLiveTraces); if (traceExport == null) { logger.warn("no trace found for id: {}", traceId); return new CommonResponse(NOT_FOUND); } ChunkSource chunkSource = render(traceExport); CommonResponse response = new CommonResponse(OK, MediaType.ZIP, chunkSource); response.setZipFileName(traceExport.fileName()); response.setHeader("Content-Disposition", "attachment; filename=" + traceExport.fileName() + ".zip"); return response; }
From source file:org.eclipse.che.ide.ext.svn.server.SubversionApi.java
/** * Perform an "svn export" based on the request. * * @param projectPath/* w w w . ja v a 2 s . co m*/ * project path * @param path * exported path * @param revision * specified revision to export * @return Response which contains hyperlink with download url * @throws IOException * if there is a problem executing the command * @throws ServerException * if there is an exporting issue */ public Response exportPath(String projectPath, String path, String revision) throws IOException, ServerException { final File project = new File(projectPath); final List<String> uArgs = defaultArgs(); if (!Strings.isNullOrEmpty(revision)) { addOption(uArgs, "--revision", revision); } uArgs.add("--force"); uArgs.add("export"); File tempDir = null; File zip = null; try { tempDir = Files.createTempDir(); final CommandLineResult result = runCommand(null, uArgs, project, Arrays.asList(path, tempDir.getAbsolutePath())); if (result.getExitCode() != 0) { LOG.warn("Svn export process finished with exit status {}", result.getExitCode()); throw new ServerException("Exporting was failed"); } zip = new File(Files.createTempDir(), "export.zip"); ZipUtils.zipDir(tempDir.getPath(), tempDir, zip, IoUtil.ANY_FILTER); } finally { if (tempDir != null) { IoUtil.deleteRecursive(tempDir); } } final Response.ResponseBuilder responseBuilder = Response .ok(new DeleteOnCloseFileInputStream(zip), MediaType.ZIP.toString()) .lastModified(new Date(zip.lastModified())) .header(HttpHeaders.CONTENT_LENGTH, Long.toString(zip.length())) .header("Content-Disposition", "attachment; filename=\"export.zip\""); return responseBuilder.build(); }
From source file:org.haiku.haikudepotserver.job.LocalJobServiceImpl.java
@Override public String deriveDataFilename(String jobDataGuid) { Preconditions.checkArgument(!Strings.isNullOrEmpty(jobDataGuid)); String descriptor = "jobdata"; String extension = "dat"; Optional<JobData> jobDataOptional = tryGetData(jobDataGuid); if (jobDataOptional.isPresent()) { JobData jobData = jobDataOptional.get(); Optional<? extends JobSnapshot> jobOptional = tryGetJobForData(jobDataGuid); if (jobOptional.isPresent()) { descriptor = jobOptional.get().getJobTypeCode(); }//from ww w .jav a 2s.c o m // TODO; get the extensions from a file etc... if (!Strings.isNullOrEmpty(jobData.getMediaTypeCode())) { if (jobData.getMediaTypeCode().startsWith(MediaType.CSV_UTF_8.withoutParameters().toString())) { extension = "csv"; } if (jobData.getMediaTypeCode().equals(MediaType.ZIP.withoutParameters().toString())) { extension = "zip"; } if (jobData.getMediaTypeCode().equals(MediaType.TAR.withoutParameters().toString())) { extension = "tgz"; } if (jobData.getMediaTypeCode().equals(MediaType.PLAIN_TEXT_UTF_8.withoutParameters().toString())) { extension = "txt"; } } } return String.format("hds_%s_%s_%s.%s", descriptor, DateTimeHelper.create14DigitDateTimeFormat().format(Instant.now()), jobDataGuid.substring(0, 4), extension); }
From source file:org.eclipse.che.plugin.svn.server.SubversionApi.java
/** * Perform an "svn export" based on the request. * * @param projectPath/*from w ww .j a va2 s. c om*/ * project path * @param path * exported path * @param revision * specified revision to export * @return Response which contains hyperlink with download url * @throws IOException * if there is a problem executing the command * @throws ServerException * if there is an exporting issue */ public Response exportPath(@NotNull final String projectPath, @NotNull final String path, String revision) throws IOException, ServerException, UnauthorizedException { final File project = new File(projectPath); final List<String> uArgs = defaultArgs(); if (!isNullOrEmpty(revision)) { addOption(uArgs, "--revision", revision); } uArgs.add("--force"); uArgs.add("export"); File tempDir = null; File zip = null; try { tempDir = Files.createTempDir(); final CommandLineResult result = runCommand(null, uArgs, project, Arrays.asList(path, tempDir.getAbsolutePath())); if (result.getExitCode() != 0) { LOG.warn("Svn export process finished with exit status {}", result.getExitCode()); throw new ServerException("Export failed"); } zip = new File(Files.createTempDir(), "export.zip"); ZipUtils.zipDir(tempDir.getPath(), tempDir, zip, IoUtil.ANY_FILTER); } finally { if (tempDir != null) { IoUtil.deleteRecursive(tempDir); } } final Response.ResponseBuilder responseBuilder = Response .ok(new DeleteOnCloseFileInputStream(zip), MediaType.ZIP.toString()) .lastModified(new Date(zip.lastModified())) .header(HttpHeaders.CONTENT_LENGTH, Long.toString(zip.length())) .header("Content-Disposition", "attachment; filename=\"export.zip\""); return responseBuilder.build(); }
From source file:rapture.kernel.PluginApiImpl.java
@Override public String exportPlugin(CallingContext context, String pluginName, String path) { String zipDirName = IDGenerator.getUUID(); String zipFileName = pluginName + ".zip"; RaptureURI blobUri = null;/* w w w . j a va2 s. c om*/ try { blobUri = new RaptureURI(path); if (blobUri.getScheme().equals(Scheme.BLOB)) { path = "/tmp/" + blobUri.getDocPath(); } else { blobUri = null; } } catch (RaptureException re) { log.debug(path + " is not a Blob URI"); } File zipDir = new File(path, zipDirName); if (!zipDir.mkdirs()) { log.error("Cannot create " + zipDirName); throw RaptureExceptionFactory.create(HttpStatus.SC_UNAUTHORIZED, "Cannot create " + zipFileName + ".zip in " + path); } PluginManifest fm = getPluginManifest(context, "//" + pluginName); int objectCount = 0; List<String> objectsNotAdded = new ArrayList<>(); File zipFile = new File(zipDir, zipFileName); try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))) { PluginConfig config = new PluginConfig(); config.setDepends(fm.getDepends()); config.setDescription(fm.getDescription()); config.setVersion(fm.getVersion()); config.setPlugin(pluginName); ZipEntry entry = new ZipEntry(PLUGIN_TXT); out.putNextEntry(entry); out.write(JacksonUtil.jsonFromObject(config).getBytes("UTF-8")); for (PluginManifestItem item : fm.getContents()) { String uri = item.getURI(); try { RaptureURI ruri = new RaptureURI(uri); PluginTransportItem pti = getPluginItem(context, uri); String filePath = PluginSandboxItem.calculatePath(ruri, null); ZipEntry zentry = new ZipEntry(filePath); out.putNextEntry(zentry); out.write(pti.getContent()); objectCount++; } catch (Exception e) { objectsNotAdded.add(uri); } } } catch (IOException e) { log.error("Cannot export " + pluginName); throw RaptureExceptionFactory.create(HttpStatus.SC_UNAUTHORIZED, "Cannot export " + pluginName, e); } String filePath = zipDirName + "/" + zipFileName; if (blobUri != null) { byte[] rawFileData = new byte[(int) zipFile.length()]; filePath = blobUri.toString(); try (FileInputStream fileInputStream = new FileInputStream(zipFile)) { fileInputStream.read(rawFileData); fileInputStream.close(); Kernel.getBlob().putBlob(context, filePath, rawFileData, MediaType.ZIP.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String user = Kernel.getUser().getWhoAmI(context).getUsername(); String[] fna = objectsNotAdded.toArray(new String[objectsNotAdded.size()]); Metadata metadata = new Metadata(zipFile, filePath, user, objectCount, fna); return JacksonUtil.jsonFromObject(metadata); }