List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:edu.usu.sdl.openstorefront.service.SystemServiceImpl.java
@Override public String errorTicketInfo(String errorTicketId) { String ticketData = null;/*from w w w . j a va2s. c o m*/ ErrorTicket errorTicket = persistenceService.findById(ErrorTicket.class, errorTicketId); if (errorTicket != null) { Path path = Paths.get(FileSystemManager.getDir(FileSystemManager.ERROR_TICKET_DIR).getPath() + "/" + errorTicket.getTicketFile()); try { byte data[] = Files.readAllBytes(path); ticketData = new String(data); } catch (IOException io) { //We don't want to throw an error here if there something going on with the system. ticketData = "Unable to retrieve ticket information. (Check log for more details) Message: " + io.getMessage(); log.log(Level.WARNING, ticketData, io); } } return ticketData; }
From source file:com.netscape.cmstools.client.ClientCertImportCLI.java
public void importPKCS7(String pkcs7Path, String nickname, String trustAttributes) throws Exception { if (nickname == null) { throw new Exception("Missing certificate nickname."); }// ww w . j av a 2s. c o m if (verbose) System.out.println("Loading PKCS #7 data from " + pkcs7Path); String str = new String(Files.readAllBytes(Paths.get(pkcs7Path))).trim(); PKCS7 pkcs7 = new PKCS7(str); java.security.cert.X509Certificate[] certs = pkcs7.getCertificates(); if (certs == null || certs.length == 0) { if (verbose) System.out.println("No certificates to import"); return; } // sort certs from leaf to root certs = CryptoUtil.sortCertificateChain(certs, true); CryptoManager manager = CryptoManager.getInstance(); // Import certs with preferred nicknames. // NOTE: JSS/NSS may assign different nickname. List<X509Certificate> importedCerts = new ArrayList<>(); int i = 0; for (java.security.cert.X509Certificate cert : certs) { String preferredNickname = nickname + (i == 0 ? "" : " #" + (i + 1)); if (verbose) System.out.println("Importing certificate " + preferredNickname + ": " + cert.getSubjectDN()); X509Certificate importedCert = manager.importCertPackage(cert.getEncoded(), preferredNickname); importedCerts.add(importedCert); String importedNickname = importedCert.getNickname(); if (verbose) System.out.println("Certificate imported as " + importedNickname); if (importedNickname.equals(preferredNickname)) { // Cert was imported with preferred nickname, increment counter. i++; } } X509Certificate cert = importedCerts.get(0); if (verbose) { System.out.println("Leaf cert: " + cert.getNickname()); } if (trustAttributes != null) { if (verbose) { System.out.println("Setting trust attributes to " + trustAttributes); } setTrustAttributes(cert, trustAttributes); } X509Certificate[] chain = manager.buildCertificateChain(cert); if (chain.length == 1 && trustAttributes != null) { // Cert has no parent cert and is already trusted. return; } // Trust root cert. X509Certificate root = chain[chain.length - 1]; if (verbose) { System.out.println("Root cert: " + root.getNickname()); System.out.println("Setting trust attributes to CT,C,C"); } setTrustAttributes(root, "CT,C,C"); MainCLI.printMessage("Imported certificate \"" + nickname + "\""); }
From source file:de.ingrid.interfaces.csw.tools.FileUtils.java
/** * Read a file into a string./*from w w w . ja v a2 s .c om*/ * * @param path * @param encoding * @return * @throws IOException */ public static String readFile(Path path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(path); return new String(encoded, encoding); }
From source file:com.ontotext.s4.service.S4ServiceClient.java
/** * Classifies the contents of a single file returning an * {@link InputStream} from which the classification information can be read */*from w w w . j a v a 2 s . c o m*/ * @param documentContent the file which will be classified * @param documentEncoding the encoding of the file which will be classified * @param documentMimeType the MIME type of the file which will be classified * * @return Service response raw content * * @throws IOException if there are problems reading the contents of the file * @throws S4ServiceClientException */ public InputStream classifyFileContentsAsStream(File documentContent, Charset documentEncoding, SupportedMimeType documentMimeType) throws IOException, S4ServiceClientException { Path documentPath = documentContent.toPath(); if (!Files.isReadable(documentPath)) { throw new IOException("File " + documentPath.toString() + " is not readable."); } ByteBuffer buff; buff = ByteBuffer.wrap(Files.readAllBytes(documentPath)); String content = documentEncoding.decode(buff).toString(); return classifyDocumentAsStream(content, documentMimeType); }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void testCopyFile() throws IOException { tmp.newFolder("foo"); Path file = tmp.newFile("foo/bar.txt"); String content = "Hello, World!"; Files.write(file, content.getBytes(UTF_8)); filesystem.copyFile(Paths.get("foo/bar.txt"), Paths.get("foo/baz.txt")); assertEquals(content, new String(Files.readAllBytes(tmp.getRoot().resolve("foo/baz.txt")), UTF_8)); }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java
/** * attach log using run id/*from ww w. j a v a 2s. c o m*/ * * @param token * - token generate using username and password * @param projectID * @param releaseID * @param cycleID * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID, long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:femr.business.services.system.PhotoService.java
private void saveNewEncounterImage(File image, PatientEncounterItem patientEncounter, String descriptionText) { try {/*from w w w . j a v a 2 s .co m*/ String imageFileName = "N/A"; //Create photo record: IPhoto pPhoto = photoRepository.createPhoto(descriptionText, "", null); //this is redundant...? IPhoto editPhoto = photoRepository.retrievePhotoById(pPhoto.getId()); if (!_bUseDbPhotoStorage) { //Build the filepath for the image imageFileName = "Patient_" + patientEncounter.getPatientItem().getId() + "_Enc_" + patientEncounter.getId() + "_Photo_" + editPhoto.getId(); } //Since the photo ID is part of the file name // I am setting the filePath field after the record is created photoRepository.updatePhotoFilePath(editPhoto.getId(), imageFileName); //Link photo record in photoEncounter table photoRepository.createEncounterPhoto(editPhoto.getId(), patientEncounter.getId()); if (!_bUseDbPhotoStorage) { photoRepository.createPhotoOnFilesystem(image, this._encounterPhotoPath + imageFileName); } else { //Read image data, update blob field: byte[] imgData = Files.readAllBytes(Paths.get(image.getAbsolutePath())); photoRepository.updatePhotoData(pPhoto.getId(), imgData); } } catch (Exception ex) { String test = "uh oh"; } }
From source file:co.cask.cdap.etl.tool.UpgradeTool.java
private static ClientConfig getClientConfig(CommandLine commandLine) throws IOException { String uriStr = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "localhost:10000"; if (!uriStr.contains("://")) { uriStr = "http://" + uriStr; }/*from w ww. j a va 2 s. co m*/ URI uri = URI.create(uriStr); String hostname = uri.getHost(); int port = uri.getPort(); boolean sslEnabled = "https".equals(uri.getScheme()); ConnectionConfig connectionConfig = ConnectionConfig.builder().setHostname(hostname).setPort(port) .setSSLEnabled(sslEnabled).build(); int readTimeout = commandLine.hasOption("t") ? Integer.parseInt(commandLine.getOptionValue("t")) : DEFAULT_READ_TIMEOUT_MILLIS; ClientConfig.Builder clientConfigBuilder = ClientConfig.builder().setDefaultReadTimeout(readTimeout) .setConnectionConfig(connectionConfig); if (commandLine.hasOption("a")) { String tokenFilePath = commandLine.getOptionValue("a"); File tokenFile = new File(tokenFilePath); if (!tokenFile.exists()) { throw new IllegalArgumentException("Access token file " + tokenFilePath + " does not exist."); } if (!tokenFile.isFile()) { throw new IllegalArgumentException("Access token file " + tokenFilePath + " is not a file."); } String tokenValue = new String(Files.readAllBytes(tokenFile.toPath()), StandardCharsets.UTF_8).trim(); AccessToken accessToken = new AccessToken(tokenValue, 82000L, "Bearer"); clientConfigBuilder.setAccessToken(accessToken); } return clientConfigBuilder.build(); }
From source file:edu.usu.sdl.openstorefront.service.AttributeServiceImpl.java
@Override public ArticleView getArticle(AttributeCodePk attributeCodePk) { ArticleView article = null;//from w ww. j a v a 2 s . c o m Objects.requireNonNull(attributeCodePk, "AttributeCodePk is required."); Objects.requireNonNull(attributeCodePk.getAttributeType(), "Type is required."); Objects.requireNonNull(attributeCodePk.getAttributeCode(), "Code is required."); AttributeCode attributeCode = persistenceService.findById(AttributeCode.class, attributeCodePk); if (attributeCode != null) { if (attributeCode.getArticle() != null) { File articleDir = FileSystemManager.getDir(FileSystemManager.ARTICLE_DIR); try { byte data[] = Files.readAllBytes(Paths .get(articleDir.getPath() + "/" + attributeCode.getArticle().getArticleFilename())); article = ArticleView.toViewHtml(attributeCode, new String(data)); } catch (IOException e) { throw new OpenStorefrontRuntimeException( "Unable to find article for type: " + attributeCodePk.getAttributeType() + " code: " + attributeCodePk.getAttributeCode(), "Contact system admin to confirm file exists and is not corrupt.", e); } } } return article; }
From source file:com.pentaho.ctools.issues.cda.CDAExportToXls.java
/** * ############################### Test Case 2 ############################### * * Test Case Name:/* w w w .ja v a 2 s . c o m*/ * Asserting that export to excel works when exporting query with more then 10 parameters * Description: * The test pretends validate the CDA-112 issue, asserting that export to excel works when exporting query with more then 10 parameters. * * Steps: * 1. Select "sqlDummyTWELVE" on "dataAccessSelector" * 2. Wait for and assert elements and text on page * 3. Export file and assure it has same md5 as expected * */ @Test public void tc02_CdaFileViewer_ExportMultiParams() { this.log.info("tc02_CdaFileViewer_ExportMultiParams"); /* * ## Step 1 */ //Open Issue Sample driver.get(baseUrl + "plugin/cda/api/previewQuery?path=/public/Issues/CDA/CDA-112/cda112.cda"); //wait for invisibility of waiting pop-up this.elemHelper.WaitForElementInvisibility(driver, By.xpath("//div[@class='busy-indicator-container waitPopup']"), 180); //Wait for buttons: button, Cache This AND Query URL WebElement DataSelector = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.id("dataAccessSelector")); assertNotNull(DataSelector); Select select = new Select(this.elemHelper.FindElement(driver, By.id("dataAccessSelector"))); select.selectByValue("sqlDummyTWELVE"); this.elemHelper.FindElement(driver, By.cssSelector("div.blockUI.blockOverlay")); this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"), 180); WebElement cacheButton = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//button[@id='cachethis']")); assertNotNull(cacheButton); WebElement queryButton = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//button[@id='queryUrl']")); assertNotNull(queryButton); WebElement refreshButton = this.elemHelper.WaitForElementPresenceAndVisible(driver, By.xpath("//button[@id='button']")); assertNotNull(refreshButton); /* * ## Step 2 */ //wait to render page this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay")); //Check the 12 parameters were applied WebElement elemStatus = this.elemHelper.FindElement(driver, By.id("p1")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p2")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p3")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p4")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p5")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p6")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p7")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p8")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p9")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p10")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p11")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); elemStatus = this.elemHelper.FindElement(driver, By.id("p12")); assertEquals("Alpha Cognac", elemStatus.getAttribute("value")); //Check text on table String columnOneRowOne = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//table[@id='contents']/tbody/tr/td")); String columnTwoRowOne = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//table[@id='contents']/tbody/tr/td[2]")); assertEquals("242", columnOneRowOne); assertEquals("Alpha Cognac", columnTwoRowOne); /* * ## Step 3 */ WebElement buttonExport = this.elemHelper.FindElement(driver, By.id("export")); assertNotNull(buttonExport); try { //Delete the existence if exist new File(this.exportFilePath).delete(); //Click to export buttonExport.click(); //Wait for file to be created in the destination dir DirectoryWatcher dw = new DirectoryWatcher(); dw.WatchForCreate(downloadDir); Thread.sleep(5000); //Check if the file really exist File exportFile = new File(this.exportFilePath); assertTrue(exportFile.exists()); //Wait for the file to be downloaded totally for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms long nSize = FileUtils.sizeOf(exportFile); //Since the file always contents the same data, we wait for the expected bytes if (nSize >= 13824) { break; } Thread.sleep(100); } //Check if the file downloaded is the expected String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath())); assertEquals(md5, "f84e5cd4a4a8ffc4499f2e69f62cbcc7"); //The delete file DeleteFile(); } catch (Exception e) { this.log.error(e.getMessage()); } }