List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:com.mycompany.FacebookManager.java
@Override public void postMessageOnFacebook(FacebookClient client, String fileName) throws FileNotFoundException, IOException { byte[] image; Path path = Paths.get(fileName); image = Files.readAllBytes(path); client.publish("me/photos", FacebookType.class, BinaryAttachment.with("composite.png", image), Parameter.with("message", blameMessage)); }
From source file:com.example.dlp.Redact.java
private static void redactImage(String filePath, Likelihood minLikelihood, List<InfoType> infoTypes, String outputPath) throws Exception { // [START dlp_redact_image] // Instantiate the DLP client try (DlpServiceClient dlpClient = DlpServiceClient.create()) { // The path to a local file to inspect. Can be a JPG or PNG image file. // filePath = 'path/to/image.png' // detect file mime type, default to application/octet-stream String mimeType = URLConnection.guessContentTypeFromName(filePath); if (mimeType == null) { mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filePath); }/*from w w w.java2 s . com*/ if (mimeType == null) { mimeType = "application/octet-stream"; } byte[] data = Files.readAllBytes(Paths.get(filePath)); // The minimum likelihood required before redacting a match // minLikelihood = 'LIKELIHOOD_UNSPECIFIED' // The infoTypes of information to redact // infoTypes = [{ name: 'EMAIL_ADDRESS' }, { name: 'PHONE_NUMBER' }] // The local path to save the resulting image to. // outputPath = 'result.png' InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes) .setMinLikelihood(minLikelihood).build(); ContentItem contentItem = ContentItem.newBuilder().setType(mimeType).setData(ByteString.copyFrom(data)) .build(); List<ImageRedactionConfig> imageRedactionConfigs = new ArrayList<>(); for (InfoType infoType : infoTypes) { // clear the specific info type if detected in the image // use .setRedactionColor to color detected info type without clearing ImageRedactionConfig imageRedactionConfig = ImageRedactionConfig.newBuilder().setInfoType(infoType) .clearTarget().build(); imageRedactionConfigs.add(imageRedactionConfig); } RedactContentRequest redactContentRequest = RedactContentRequest.newBuilder() .setInspectConfig(inspectConfig).addAllImageRedactionConfigs(imageRedactionConfigs) .addItems(contentItem).build(); RedactContentResponse contentResponse = dlpClient.redactContent(redactContentRequest); for (ContentItem responseItem : contentResponse.getItemsList()) { // redacted image data ByteString redactedImageData = responseItem.getData(); FileOutputStream outputStream = new FileOutputStream(outputPath); outputStream.write(redactedImageData.toByteArray()); outputStream.close(); } // [END dlp_redact_image] } }
From source file:by.creepid.docsreporter.AbstractDocsReporterIT.java
protected byte[] getFileBytes(String path) { File fi = new File(path); try {/*from ww w. jav a2 s .c o m*/ return Files.readAllBytes(fi.toPath()); } catch (IOException ex) { ex.printStackTrace(); } throw new RuntimeException("Cannot set the photo"); }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public byte[] export(String name) throws IOException, FileNotFoundException { Path configurationPath = getConfigurationPath(name); if (Files.exists(configurationPath) && !Files.isDirectory(configurationPath)) { return Files.readAllBytes(configurationPath); } else {/* w w w . j av a 2s . c o m*/ throw new FileNotFoundException(configurationPath.toString()); } }
From source file:de.siegmar.securetransfer.component.Cryptor.java
private byte[] initSalt(final Path baseDir) { final Path saltFile = baseDir.resolve("salt"); try {/* w w w . j a v a 2 s .c om*/ if (Files.exists(saltFile)) { return Files.readAllBytes(saltFile); } final byte[] newSalt = newRandom(SALT_SIZE); Files.write(saltFile, newSalt, StandardOpenOption.CREATE_NEW); LOG.info("Initialized instance salt at {}", saltFile); return newSalt; } catch (final IOException e) { throw new UncheckedIOException(e); } }
From source file:br.pucminas.ri.jsearch.rest.controller.ApiController.java
private static Object evalTests(Request req, Response res) { try {//from w w w.ja va 2 s . c om Searcher.performTests("result/queries.txt"); String[] command = { "./tests.sh" }; Process p = Runtime.getRuntime().exec(command); p.waitFor(); Path path = Paths.get("result/output.txt"); res.header("Content-Disposition", "attachment; filename=output.txt"); res.type("application/force-download"); byte[] data = null; try { data = Files.readAllBytes(path); } catch (Exception e1) { e1.printStackTrace(); } res.raw().getOutputStream().write(data); try { res.raw().getOutputStream().write(data); res.raw().getOutputStream().flush(); res.raw().getOutputStream().close(); } catch (Exception e) { e.printStackTrace(); } return res.raw(); } catch (IOException | InterruptedException e) { e.printStackTrace(); return "Error on execute tests."; } }
From source file:com.ubershy.streamsis.project.ProjectSerializator.java
/** * Deserialize(load) {@link CuteProject} from file. * * @param path//from w w w . j a v a2 s . c o m * the path of the file to deserialize * @return {@link CuteProject} * @throws IOException * Signals that an I/O exception has occurred. */ public static CuteProject deSerializeFromFile(String path) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true); CuteProject project = null; try { project = mapper.readValue(Files.readAllBytes(Paths.get(path)), CuteProject.class); } catch (JsonGenerationException e) { logger.error("CuteProject opening fail: JsonGeneration error"); e.printStackTrace(); throw e; } catch (JsonMappingException e) { logger.error( "CuteProject opening fail: mapping error. Can't deserialize Project file. It has different or outdated format " + path); e.printStackTrace(); throw e; } catch (IOException e) { logger.error("CuteProject opening fail: IO error " + path); throw e; } logger.info("CuteProject opening success"); return project; }
From source file:org.segator.plex.cloud.transcoding.TranscoderBO.java
public synchronized TranscoderMachine getFreeTranscoderMachine(PlexUserSession plexUserSession) throws DigitalOceanException, RequestUnsuccessfulException, InterruptedException, UnsupportedEncodingException, IOException { Thread.sleep(3000);/*from w w w . jav a 2 s .c o m*/ long now = new Date().getTime(); for (TranscoderMachine transcoderMachine : new ArrayList<TranscoderMachine>( storerMachine.getTranscoderMachines())) { //If the user have same session as the VM seems that he are seeking to the same movie so he have preferency to take this VM if (plexUserSession.getSession().equals(transcoderMachine.getPlexUserSession().getSession())) { return transcoderMachine; } //In case the VM is in idle state it seems nobody is using it so we assign to the user. if (transcoderMachine.getStatusTranscoding().equals("idle")) { transcoderMachine.setStatusTranscoding("assigned"); transcoderMachine.setPlexUserSession(plexUserSession); transcoderMachine.setLastUsage(now); return transcoderMachine; } //In case the VM was assigned but not used in 2min we automatically assign to the new session long diference = new Date().getTime() - transcoderMachine.getLastUsage(); if (transcoderMachine.getStatusTranscoding().equals("assigned") && diference > 120 * 1000) { System.out.println("The VM" + transcoderMachine.getName() + " was assigned but not used, reasigning to " + plexUserSession.getSession()); transcoderMachine.setPlexUserSession(plexUserSession); transcoderMachine.setLastUsage(now); return transcoderMachine; } } //No Empty Machines let's create new one, but only if exist an image if (applicationParams.getDOImageID() == null) { return null; } String VMName = TranscoderConstants.DROPLET_BASE_NAME + System.currentTimeMillis(); System.out.println("We are going to create a droplet " + VMName); Droplet newMachine = applicationParams.getBasicDroplet(VMName); File entryPointDigitalOcean = new File(TranscoderConstants.DROPLET_ENTRY_POINT_FILE_NAME); String provisionTemplate = new String( Files.readAllBytes(Paths.get(entryPointDigitalOcean.getAbsolutePath())), "UTF-8"); String provisionFile = applicationParams.parseScriptTemplate(provisionTemplate); provisionFile = provisionFile.replace(":", "\\:"); newMachine.setUserData(provisionFile); newMachine = applicationParams.getDOClient().createDroplet(newMachine); TranscoderMachine transcoderMachine = new TranscoderMachine(newMachine.getId(), newMachine.getName()); transcoderMachine.setDroplet(newMachine); transcoderMachine.setPlexUserSession(plexUserSession); storerMachine.getTranscoderMachines().add(transcoderMachine); return transcoderMachine; }
From source file:org.mcplissken.repository.models.content.Content.java
public void writeAsFile(File result) throws IOException { Path path = Paths.get(result.getPath()); byte[] bytes = Files.readAllBytes(path); data = ByteBuffer.wrap(bytes); }
From source file:net.arccotangent.pacchat.filesystem.KeyManager.java
public static PublicKey loadKeyByIP(String ip_address) { km_log.i("Loading public key for " + ip_address); try {// w w w.j av a 2 s.c om File pubFile = new File(installationPath + File.separator + ip_address + ".pub"); byte[] pubEncoded = Files.readAllBytes(pubFile.toPath()); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decodeBase64(pubEncoded)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(pubSpec); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { km_log.e("Error while loading public key for " + ip_address + "!"); e.printStackTrace(); } return null; }