List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:grakn.core.rule.GraknTestServer.java
protected File buildCassandraConfigWithRandomPorts() throws IOException { byte[] bytes = Files.readAllBytes(originalCassandraConfigPath); String configString = new String(bytes, StandardCharsets.UTF_8); configString = configString + "\nstorage_port: " + storagePort; configString = configString + "\nnative_transport_port: " + nativeTransportPort; configString = configString + "\nrpc_port: " + rpcPort; InputStream configStream = new ByteArrayInputStream(configString.getBytes(StandardCharsets.UTF_8)); String directory = "target/embeddedCassandra"; org.apache.cassandra.io.util.FileUtils.createDirectory(directory); Path copyName = Paths.get(directory, "cassandra-embedded.yaml"); // Create file in directory we just created and copy the stream content into it. Files.copy(configStream, copyName); return copyName.toFile(); }
From source file:com.juancarlosroot.threads.SimulatedUser.java
private String firmarImagen(int fileName) throws IOException { String result = ""; try {/*from w w w .ja v a 2s . c o m*/ Path currentRelativePath = Paths.get(""); String s = currentRelativePath.toAbsolutePath().toString(); String theFolder = s + "/" + "archivos"; FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg"; File image = new File(file1Name); ZipEntry zipEntry = new ZipEntry(image.getName()); zos.putNextEntry(zipEntry); FileInputStream fileInputStream = new FileInputStream(image); byte[] buf = new byte[2048]; int bytesRead; while ((bytesRead = fileInputStream.read(buf)) > 0) { zos.write(buf, 0, bytesRead); } zos.closeEntry(); zos.close(); fos.close(); Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileName) + ".zip"); byte[] data = Files.readAllBytes(path); byte[] byteArray = Base64.encodeBase64(data); String b64 = new String(byteArray); result = firma(b64, Integer.toString(fileName), "pruebita"); System.out.println("User : " + idSimulatedUser + " ENVIADO"); nFilesSend++; } catch (FileNotFoundException ex) { Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex); } catch (WriterException_Exception ex) { Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException_Exception ex) { Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException_Exception ex) { Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException_Exception ex) { Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex); } return "http://" + result; }
From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java
/*************************************************** * URL: /upload/jqueryUpload upload(): receives files * // w ww .j ava2 s . c om * @param request * : MultipartHttpServletRequest auto passed * @param response * : HttpServletResponse auto passed * @return LinkedList<FileMeta> as json format ****************************************************/ @ResponseBody @RequestMapping(value = "/jqueryUpload", method = RequestMethod.POST) public FileMetaList jqueryUpload(@RequestParam final Long albumId, final MultipartHttpServletRequest request, final HttpServletResponse response) throws Exception { Assert.notNull(albumId, "No Album Id supplied !"); final FileMetaList files = new FileMetaList(); // 1. build an iterator final Iterator<String> itr = request.getFileNames(); // 2. get each file while (itr.hasNext()) { // 2.1 get next MultipartFile final MultipartFile mpf = request.getFile(itr.next()); // Here the file is uploaded final String originalFilename = mpf.getOriginalFilename(); final String contentType = mpf.getContentType(); final Matcher zipMatcher = UploadPicturesController.ZIP_CONTENT_TYPE_PATTERN.matcher(contentType); if (zipMatcher.find()) { // 2.3 create new fileMeta final FileMeta zipMeta = new FileMeta(); zipMeta.setFileName(originalFilename); zipMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); zipMeta.setFileType(mpf.getContentType()); final List<Path> picturesPaths = this.processArchive(mpf); final Collection<Future<Void>> futures = new ArrayList<>(picturesPaths.size()); final ExecutorService executorService = Executors .newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (final Path picturePath : picturesPaths) { final Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { final String pictureFileName = picturePath.getName(picturePath.getNameCount() - 1) .toString(); final byte[] pictureContents = Files.readAllBytes(picturePath); final FileMeta pictureMeta = new FileMeta(); try { final Picture picture = UploadPicturesController.this.createPicture(albumId, pictureFileName.toString(), pictureContents); final Long imageId = picture.getImage().getId(); final Long thumbnailId = picture.getThumbnail().getId(); pictureMeta.setFileName(pictureFileName); pictureMeta.setFileSize(pictureContents.length / 1024 + " Kb"); pictureMeta.setFileType(Files.probeContentType(picturePath)); pictureMeta.setUrl( response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId)); pictureMeta.setThumbnailUrl(response .encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId)); } catch (final PictureAlreadyExistsException e) { // Picture already exists ! pictureMeta.setError( UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG + e.getFilename()); } catch (final UnsupportedPictureTypeException e) { // Picture already exists ! pictureMeta.setError( UploadPicturesController.UNSUPPORTED_PICTURE_TYPE_MSG + e.getFilename()); } files.add(pictureMeta); return null; } }); futures.add(future); } for (final Future<Void> future : futures) { future.get(); } files.add(zipMeta); } final Matcher imgMatcher = UploadPicturesController.IMG_CONTENT_TYPE_PATTERN.matcher(contentType); if (imgMatcher.find()) { // 2.3 create new fileMeta final FileMeta fileMeta = new FileMeta(); try { final byte[] fileContents = mpf.getBytes(); final Picture picture = this.createPicture(albumId, originalFilename, fileContents); final Long imageId = picture.getImage().getId(); final Long thumbnailId = picture.getThumbnail().getId(); fileMeta.setFileName(originalFilename); fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); fileMeta.setFileType(mpf.getContentType()); fileMeta.setBytes(fileContents); fileMeta.setUrl(response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId)); fileMeta.setThumbnailUrl( response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId)); // 2.4 add to files files.add(fileMeta); } catch (final PictureAlreadyExistsException e) { // Picture already exists ! fileMeta.setError(UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG); } } } // result will be like this // {files:[{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]} return files; }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
private void writeSha1(Path file, boolean corrupt) throws IOException { String sha1Hex = MessageDigests.toHexString(MessageDigests.sha1().digest(Files.readAllBytes(file))); try (BufferedWriter out = Files.newBufferedWriter(file.resolveSibling(file.getFileName() + ".sha1"), StandardCharsets.UTF_8)) { out.write(sha1Hex);/*from ww w . j ava2 s. co m*/ if (corrupt) { out.write("bad"); } } }
From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java
@Test public void testAllXmlExamples() throws Exception { for (Path path : XdocUtil.getXdocsFilePaths()) { final String input = new String(Files.readAllBytes(path), UTF_8); final String fileName = path.getFileName().toString(); final Document document = XmlUtil.getRawXml(fileName, input, input); final NodeList sources = document.getElementsByTagName("source"); for (int position = 0; position < sources.getLength(); position++) { final String unserializedSource = sources.item(position).getTextContent().replace("...", "").trim(); if (unserializedSource.charAt(0) != '<' || unserializedSource.charAt(unserializedSource.length() - 1) != '>' // no dtd testing yet || unserializedSource.contains("<!")) { continue; }//from w w w .j av a 2 s . co m buildAndValidateXml(fileName, unserializedSource); } } }
From source file:co.kuali.rice.krad.service.impl.S3AttachmentServiceImpl.java
@Override public InputStream retrieveAttachmentContents(Attachment attachment) throws IOException { if (!isS3IntegrationEnabled()) { return super.retrieveAttachmentContents(attachment); }//from www .j av a 2 s . c o m try { final Object s3File = riceS3FileService.retrieveFile(attachment.getAttachmentIdentifier()); byte[] s3Bytes = null; byte[] fsBytes = null; if (s3File != null) { if (LOG.isDebugEnabled()) { final Method getFileMetaData = s3File.getClass() .getMethod(RiceAttachmentDataS3Constants.GET_FILE_META_DATA_METHOD); LOG.debug("data found in S3, existing id: " + attachment.getAttachmentIdentifier() + " metadata: " + getFileMetaData.invoke(s3File)); } final Method getFileContents = s3File.getClass() .getMethod(RiceAttachmentDataS3Constants.GET_FILE_CONTENTS_METHOD); final InputStream fileContents = (InputStream) getFileContents.invoke(s3File); s3Bytes = IOUtils.toByteArray(fileContents); } if (s3Bytes == null || isS3DualRetrieveEnabled()) { String parentDirectory = ""; if (attachment.getNote() != null && attachment.getNote().getRemoteObjectIdentifier() != null) { parentDirectory = attachment.getNote().getRemoteObjectIdentifier(); } final Path path = Paths.get(getDocumentDirectory(parentDirectory), attachment.getAttachmentIdentifier()); try { fsBytes = Files.readAllBytes(path); } catch (NoSuchFileException e) { LOG.info("file not found at path " + path); } } if (s3Bytes != null && fsBytes != null) { final String s3MD5 = DigestUtils.md5Hex(s3Bytes); final String dbMD5 = DigestUtils.md5Hex(fsBytes); if (!Objects.equals(s3MD5, dbMD5)) { LOG.error("S3 data MD5: " + s3MD5 + " does not equal FS data MD5: " + dbMD5 + " for id: " + attachment.getAttachmentIdentifier()); } } return new ByteArrayInputStream(s3Bytes != null ? s3Bytes : fsBytes); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IOException e) { throw new RuntimeException(e); } }
From source file:dyco4j.instrumentation.internals.CLI.java
private static void processCommandLine(final CommandLine cmdLine) throws IOException { final Path _srcRoot = Paths.get(cmdLine.getOptionValue(IN_FOLDER_OPTION)); final Path _trgRoot = Paths.get(cmdLine.getOptionValue(OUT_FOLDER_OPTION)); final Predicate<Path> _nonClassFileSelector = p -> !p.toString().endsWith(".class") && Files.isRegularFile(p); final BiConsumer<Path, Path> _fileCopier = (srcPath, trgPath) -> { try {/*from w w w .j a v a 2 s .c om*/ Files.copy(srcPath, trgPath); } catch (final IOException _ex) { throw new RuntimeException(_ex); } }; processFiles(_srcRoot, _trgRoot, _nonClassFileSelector, _fileCopier); final CommandLineOptions _cmdLineOptions = new CommandLineOptions( cmdLine.hasOption(TRACE_ARRAY_ACCESS_OPTION), cmdLine.hasOption(TRACE_FIELD_ACCESS_OPTION), cmdLine.hasOption(TRACE_METHOD_ARGUMENTS_OPTION), cmdLine.hasOption(TRACE_METHOD_CALL_OPTION), cmdLine.hasOption(TRACE_METHOD_RETURN_VALUE_OPTION)); final Set<Path> _filenames = getFilenames(_srcRoot); final Path _programDataFile = Paths.get(PROGRAM_DATA_FILE_NAME); final ProgramData _programData = ProgramData.loadData(_programDataFile); getMemberId2NameMapping(_filenames, _programData); final Predicate<Path> _classFileSelector = p -> p.toString().endsWith(".class"); final String _methodNameRegex = cmdLine.getOptionValue(METHOD_NAME_REGEX_OPTION, METHOD_NAME_REGEX); final BiConsumer<Path, Path> _classInstrumenter = (srcPath, trgPath) -> { try { final ClassReader _cr = new ClassReader(Files.readAllBytes(srcPath)); final ClassWriter _cw = new ClassWriter(_cr, ClassWriter.COMPUTE_FRAMES); final Map<String, String> _shortFieldName2Id = Collections .unmodifiableMap(_programData.shortFieldName2Id); final Map<String, String> _shortMethodName2Id = Collections .unmodifiableMap(_programData.shortMethodName2Id); final Map<String, String> _class2superClass = Collections .unmodifiableMap(_programData.class2superClass); final ClassVisitor _cv1 = new LoggerInitializingClassVisitor(CLI.ASM_VERSION, _cw); final ClassVisitor _cv2 = new TracingClassVisitor(_cv1, _shortFieldName2Id, _shortMethodName2Id, _class2superClass, _methodNameRegex, _cmdLineOptions); _cr.accept(_cv2, ClassReader.SKIP_FRAMES); Files.write(trgPath, _cw.toByteArray()); } catch (final IOException _ex) { throw new RuntimeException(_ex); } }; processFiles(_srcRoot, _trgRoot, _classFileSelector, _classInstrumenter); ProgramData.saveData(_programData, _programDataFile); }
From source file:io.druid.storage.hdfs.HdfsDataSegmentPullerTest.java
@Test public void testGZ() throws IOException, SegmentLoadingException { final Path zipPath = new Path("/tmp/testZip.gz"); final File outTmpDir = com.google.common.io.Files.createTempDir(); final File outFile = new File(outTmpDir, "testZip"); outFile.delete();/* w ww . j a va2 s. co m*/ final URI uri = URI.create(uriBase.toString() + zipPath.toString()); try (final OutputStream outputStream = miniCluster.getFileSystem().create(zipPath); final OutputStream gzStream = new GZIPOutputStream(outputStream); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, gzStream); } try { Assert.assertFalse(outFile.exists()); puller.getSegmentFiles(new Path(uri), outTmpDir); Assert.assertTrue(outFile.exists()); Assert.assertArrayEquals(pathByteContents, Files.readAllBytes(outFile.toPath())); } finally { if (outFile.exists()) { outFile.delete(); } if (outTmpDir.exists()) { outTmpDir.delete(); } } }
From source file:io.druid.segment.loading.HdfsDataSegmentPullerTest.java
@Test public void testGZ() throws IOException, SegmentLoadingException { final Path zipPath = new Path("/tmp/testZip.gz"); final File outTmpDir = com.google.common.io.Files.createTempDir(); final File outFile = new File(outTmpDir, "testZip"); outFile.delete();/* w w w . j ava2 s. co m*/ final URI uri = URI.create(uriBase.toString() + zipPath.toString()); try (final OutputStream outputStream = miniCluster.getFileSystem().create(zipPath); final OutputStream gzStream = new GZIPOutputStream(outputStream); final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) { ByteStreams.copy(inputStream, gzStream); } try { Assert.assertFalse(outFile.exists()); puller.getSegmentFiles(uri, outTmpDir); Assert.assertTrue(outFile.exists()); Assert.assertArrayEquals(pathByteContents, Files.readAllBytes(outFile.toPath())); } finally { if (outFile.exists()) { outFile.delete(); } if (outTmpDir.exists()) { outTmpDir.delete(); } } }
From source file:io.syndesis.github.GitHubServiceITCase.java
@Test public void testProjectCommit() throws IOException, IllegalStateException, GitAPIException, URISyntaxException { URL url = this.getClass().getResource(PROJECT_DIR); System.out.println("Reading sample project from " + url); //Read from classpath sample-github-project into map Map<String, byte[]> files = new HashMap<>(); Files.find(Paths.get(url.getPath()), Integer.MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile()) .forEach(filePath -> {/*from w ww . j a va2 s .c om*/ if (!filePath.startsWith(".git")) { byte[] content; try { content = Files.readAllBytes(filePath); String file = filePath.toString() .substring(filePath.toString().indexOf(PROJECT_DIR) + PROJECT_DIR.length() + 1); files.put(file, content); } catch (IOException e) { throw new RuntimeException(e); } } }); User user = githubService.getApiUser(); String cloneURL = githubService.createOrUpdateProjectFiles(REPO_NAME, user, "my itcase initial message" + UUID.randomUUID().toString(), files, null); Assertions.assertThat(cloneURL).isNotNull().isNotBlank(); File tmpDir = Files.createTempDirectory(testName.getMethodName()).toFile(); tmpDir.deleteOnExit(); Git clone = Git.cloneRepository().setDirectory(tmpDir).setURI(cloneURL).call(); PersonIdent author = clone.log().call().iterator().next().getAuthorIdent(); Assertions.assertThat(author).isNotNull(); Assertions.assertThat(author.getName()).isNotNull().isNotBlank(); }