List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:com.haulmont.restapi.service.filter.RestFilterParserTest.java
protected String readDataFromFile(String filePath) throws Exception { Path path = Paths.get(RestFilterParser.class.getResource(filePath).toURI()); byte[] data = Files.readAllBytes(path); return new String(data); }
From source file:com.netscape.cmstools.client.ClientCertRequestCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); String[] cmdArgs = cmd.getArgs(); if (cmd.hasOption("help")) { printHelp();/*from w ww . j a v a 2 s . co m*/ return; } if (cmdArgs.length > 1) { throw new Exception("Too many arguments specified."); } String certRequestUsername = cmd.getOptionValue("username"); String subjectDN; if (cmdArgs.length == 0) { if (certRequestUsername == null) { throw new Exception("Missing subject DN or request username."); } subjectDN = "UID=" + certRequestUsername; } else { subjectDN = cmdArgs[0]; } // pkcs10, crmf String requestType = cmd.getOptionValue("type", "pkcs10"); boolean attributeEncoding = cmd.hasOption("attribute-encoding"); // rsa, ec String algorithm = cmd.getOptionValue("algorithm", "rsa"); int length = Integer.parseInt(cmd.getOptionValue("length", "1024")); String curve = cmd.getOptionValue("curve", "nistp256"); boolean sslECDH = cmd.hasOption("ssl-ecdh"); boolean temporary = !cmd.hasOption("permanent"); String s = cmd.getOptionValue("sensitive"); int sensitive; if (s == null) { sensitive = -1; } else { if (!s.equalsIgnoreCase("true") && !s.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Invalid sensitive parameter: " + s); } sensitive = Boolean.parseBoolean(s) ? 1 : 0; } s = cmd.getOptionValue("extractable"); int extractable; if (s == null) { extractable = -1; } else { if (!s.equalsIgnoreCase("true") && !s.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Invalid extractable parameter: " + s); } extractable = Boolean.parseBoolean(s) ? 1 : 0; } String transportCertFilename = cmd.getOptionValue("transport"); String profileID = cmd.getOptionValue("profile"); if (profileID == null) { if (algorithm.equals("rsa")) { profileID = "caUserCert"; } else if (algorithm.equals("ec")) { profileID = "caECUserCert"; } } boolean withPop = !cmd.hasOption("without-pop"); AuthorityID aid = null; if (cmd.hasOption("issuer-id")) { String aidString = cmd.getOptionValue("issuer-id"); try { aid = new AuthorityID(aidString); } catch (IllegalArgumentException e) { throw new Exception("Invalid issuer ID: " + aidString, e); } } X500Name adn = null; if (cmd.hasOption("issuer-dn")) { String adnString = cmd.getOptionValue("issuer-dn"); try { adn = new X500Name(adnString); } catch (IOException e) { throw new Exception("Invalid issuer DN: " + adnString, e); } } if (aid != null && adn != null) { throw new Exception("--issuer-id and --issuer-dn options are mutually exclusive"); } MainCLI mainCLI = (MainCLI) parent.getParent(); File certDatabase = mainCLI.certDatabase; String password = mainCLI.config.getNSSPassword(); if (password == null) { throw new Exception("Missing security database password."); } String csr; PKIClient client; if ("pkcs10".equals(requestType)) { if ("rsa".equals(algorithm)) { csr = generatePkcs10Request(certDatabase, password, algorithm, Integer.toString(length), subjectDN); } else if ("ec".equals(algorithm)) { csr = generatePkcs10Request(certDatabase, password, algorithm, curve, subjectDN); } else { throw new Exception("Error: Unknown algorithm: " + algorithm); } // initialize database after PKCS10Client to avoid conflict mainCLI.init(); client = getClient(); } else if ("crmf".equals(requestType)) { // initialize database before CRMFPopClient to load transport certificate mainCLI.init(); client = getClient(); String encoded; if (transportCertFilename == null) { SystemCertClient certClient = new SystemCertClient(client, "ca"); encoded = certClient.getTransportCert().getEncoded(); } else { encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename))); } byte[] transportCertData = Cert.parseCertificate(encoded); CryptoManager manager = CryptoManager.getInstance(); X509Certificate transportCert = manager.importCACertPackage(transportCertData); // get archival and key wrap mechanisms from CA String kwAlg = CRMFPopClient.getKeyWrapAlgotihm(client); KeyWrapAlgorithm keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg); csr = generateCrmfRequest(transportCert, subjectDN, attributeEncoding, algorithm, length, curve, sslECDH, temporary, sensitive, extractable, withPop, keyWrapAlgorithm); } else { throw new Exception("Unknown request type: " + requestType); } if (verbose) { System.out.println("CSR:"); System.out.println(csr); } CAClient caClient = new CAClient(client); CACertClient certClient = new CACertClient(caClient); if (verbose) { System.out.println("Retrieving " + profileID + " profile."); } CertEnrollmentRequest request = certClient.getEnrollmentTemplate(profileID); // Key Generation / Dual Key Generation for (ProfileInput input : request.getInputs()) { ProfileAttribute typeAttr = input.getAttribute("cert_request_type"); if (typeAttr != null) { typeAttr.setValue(requestType); } ProfileAttribute csrAttr = input.getAttribute("cert_request"); if (csrAttr != null) { csrAttr.setValue(csr); } } // parse subject DN and put the values in a map DN dn = new DN(subjectDN); Vector<?> rdns = dn.getRDNs(); Map<String, String> subjectAttributes = new HashMap<String, String>(); for (int i = 0; i < rdns.size(); i++) { RDN rdn = (RDN) rdns.elementAt(i); String type = rdn.getTypes()[0].toLowerCase(); String value = rdn.getValues()[0]; subjectAttributes.put(type, value); } ProfileInput sn = request.getInput("Subject Name"); if (sn != null) { if (verbose) System.out.println("Subject Name:"); for (ProfileAttribute attribute : sn.getAttributes()) { String name = attribute.getName(); String value = null; if (name.equals("subject")) { // get the whole subject DN value = subjectDN; } else if (name.startsWith("sn_")) { // get value from subject DN value = subjectAttributes.get(name.substring(3)); } else { // unknown attribute, ignore if (verbose) System.out.println(" - " + name); continue; } if (value == null) continue; if (verbose) System.out.println(" - " + name + ": " + value); attribute.setValue(value); } } if (certRequestUsername != null) { request.setAttribute("uid", certRequestUsername); } if (cmd.hasOption("password")) { Console console = System.console(); String certRequestPassword = new String(console.readPassword("Password: ")); request.setAttribute("pwd", certRequestPassword); } if (verbose) { System.out.println("Sending certificate request."); } CertRequestInfos infos = certClient.enrollRequest(request, aid, adn); MainCLI.printMessage("Submitted certificate request"); CACertCLI.printCertRequestInfos(infos); }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops moveShop(String shopName, String x, String y, String z, Player player) { try {//from w w w . j a va2 s .c o m String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONArray shopList = (JSONArray) jsonObj.get("shopsArray"); // Make sure that our array isn't empty if (shopList == null) { player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error\u00A7e>"); return this; } JSONObject shopObj = new JSONObject(); String shopName2; boolean foundShop = false; int index = 0; // Make sure the shop exists for (index = 0; index < shopList.size(); index++) { shopObj = (JSONObject) (shopList.get(index)); shopName2 = (String) shopObj.get("shopName"); if (shopName2.equals(shopName)) { shopList.remove(index); foundShop = true; break; } } if (!foundShop) { player.sendMessage("\u00a7aThat shop doesn't exist!"); return this; } // Update the coordinates in memory shopObj.put("x", x); shopObj.put("y", y); shopObj.put("z", z); shopObj.put("world", player.getWorld().getName()); shopObj.put("shopName", shopName); shopList.add(shopObj); // Update the entire JSON table in memory jsonObj.put("shopsArray", shopList); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop moved!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addShop()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addShop()"); e.printStackTrace(); } return this; }
From source file:SdkUnitTests.java
@Test public void EmbeddedSigningTest() { byte[] fileBytes = null; try {/* w w w . ja va 2 s . c o m*/ // String currentDir = new java.io.File(".").getCononicalPath(); String currentDir = System.getProperty("user.dir"); Path path = Paths.get(currentDir + SignTest1File); fileBytes = Files.readAllBytes(path); } catch (IOException ioExcp) { Assert.assertEquals(null, ioExcp); } // create an envelope to be signed EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.setEmailSubject("Please Sign my Java SDK Envelope (Embedded Signer)"); envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope."); // add a document to the envelope Document doc = new Document(); String base64Doc = Base64.getEncoder().encodeToString(fileBytes); doc.setDocumentBase64(base64Doc); doc.setName("TestFile.pdf"); doc.setDocumentId("1"); List<Document> docs = new ArrayList<Document>(); docs.add(doc); envDef.setDocuments(docs); // Add a recipient to sign the document Signer signer = new Signer(); signer.setEmail(UserName); String name = "Pat Developer"; signer.setName(name); signer.setRecipientId("1"); // this value represents the client's unique identifier for the signer String clientUserId = "2939"; signer.setClientUserId(clientUserId); // Create a SignHere tab somewhere on the document for the signer to sign SignHere signHere = new SignHere(); signHere.setDocumentId("1"); signHere.setPageNumber("1"); signHere.setRecipientId("1"); signHere.setXPosition("100"); signHere.setYPosition("100"); List<SignHere> signHereTabs = new ArrayList<SignHere>(); signHereTabs.add(signHere); Tabs tabs = new Tabs(); tabs.setSignHereTabs(signHereTabs); signer.setTabs(tabs); // Above causes issue envDef.setRecipients(new Recipients()); envDef.getRecipients().setSigners(new ArrayList<Signer>()); envDef.getRecipients().getSigners().add(signer); // send the envelope (otherwise it will be "created" in the Draft folder envDef.setStatus("sent"); try { ApiClient apiClient = new ApiClient(); apiClient.setBasePath(BaseUrl); String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey); apiClient.addDefaultHeader("X-DocuSign-Authentication", creds); Configuration.setDefaultApiClient(apiClient); AuthenticationApi authApi = new AuthenticationApi(); LoginInformation loginInfo = authApi.login(); Assert.assertNotSame(null, loginInfo); Assert.assertNotNull(loginInfo.getLoginAccounts()); Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0); List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts(); Assert.assertNotNull(loginAccounts.get(0).getAccountId()); String accountId = loginInfo.getLoginAccounts().get(0).getAccountId(); EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef); Assert.assertNotNull(envelopeSummary); Assert.assertNotNull(envelopeSummary.getEnvelopeId()); System.out.println("EnvelopeSummary: " + envelopeSummary); String returnUrl = "http://www.docusign.com/developer-center"; RecipientViewRequest recipientView = new RecipientViewRequest(); recipientView.setReturnUrl(returnUrl); recipientView.setClientUserId(clientUserId); recipientView.setAuthenticationMethod("email"); recipientView.setUserName(name); recipientView.setEmail(UserName); ViewUrl viewUrl = envelopesApi.createRecipientView(loginInfo.getLoginAccounts().get(0).getAccountId(), envelopeSummary.getEnvelopeId(), recipientView); Assert.assertNotNull(viewUrl); Assert.assertNotNull(viewUrl.getUrl()); // This Url should work in an Iframe or browser to allow signing System.out.println("ViewUrl is " + viewUrl); } catch (ApiException ex) { System.out.println("Exception: " + ex); Assert.assertEquals(null, ex); } }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void testCopyToPath() throws IOException { InputStream inputStream = new ByteArrayInputStream("Hello, world!".getBytes(UTF_8)); filesystem.copyToPath(inputStream, Paths.get("bytes.txt")); assertEquals("The bytes on disk should match those from the InputStream.", "Hello, world!", new String(Files.readAllBytes(tmp.getRoot().resolve("bytes.txt")), UTF_8)); }
From source file:it.infn.ct.jsaga.adaptor.tosca.job.ToscaJobControlAdaptor.java
private String submitTosca() throws IOException, ParseException, BadResource, NoSuccessException { StringBuilder orchestrator_result = new StringBuilder(""); StringBuilder postData = new StringBuilder(); postData.append("{ \"template\": \""); String tosca_template_content = ""; try {//from w w w . java 2s.co m tosca_template_content = new String(Files.readAllBytes(Paths.get(tosca_template))).replace("\n", "\\n"); postData.append(tosca_template_content); } catch (IOException ex) { log.error("Template '" + tosca_template + "'is not readable"); throw new BadResource("Template '" + tosca_template + "'is not readable; template:" + LS + "'" + tosca_template_content + "'"); } postData.append("\" }"); log.debug("JSON Data sent to the orchestrator: \n" + postData); HttpURLConnection conn; try { conn = (HttpURLConnection) endpoint.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("charset", "utf-8"); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postData.toString()); wr.flush(); wr.close(); log.debug("Orchestrator status code: " + conn.getResponseCode()); log.debug("Orchestrator status message: " + conn.getResponseMessage()); if (conn.getResponseCode() == 201) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); orchestrator_result = new StringBuilder(); String ln; while ((ln = br.readLine()) != null) { orchestrator_result.append(ln); } log.debug("Orchestrator result: " + orchestrator_result); String orchestratorDoc = orchestrator_result.toString(); tosca_UUID = getDocumentValue(orchestratorDoc, "uuid"); log.debug("Created resource has UUID: '" + tosca_UUID + "'"); return orchestratorDoc; } } catch (IOException ex) { log.error("Connection error with the service at " + endpoint.toString()); log.error(ex); throw new NoSuccessException("Connection error with the service at " + endpoint.toString()); } catch (ParseException ex) { log.error("Orchestrator response not parsable"); throw new NoSuccessException( "Orchestrator response not parsable:" + LS + "'" + orchestrator_result.toString() + "'"); } return tosca_UUID; }
From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java
@Test public void testAllCheckSections() throws Exception { final ModuleFactory moduleFactory = TestUtils.getPackageObjectFactory(); for (Path path : XdocUtil.getXdocsConfigFilePaths(XdocUtil.getXdocsFilePaths())) { final String fileName = path.getFileName().toString(); if ("config_reporting.xml".equals(fileName)) { continue; }/*from w w w. j a v a 2 s. c o m*/ final String input = new String(Files.readAllBytes(path), UTF_8); final Document document = XmlUtil.getRawXml(fileName, input, input); final NodeList sources = document.getElementsByTagName("section"); String lastSectionName = null; for (int position = 0; position < sources.getLength(); position++) { final Node section = sources.item(position); final String sectionName = section.getAttributes().getNamedItem("name").getNodeValue(); if ("Content".equals(sectionName) || "Overview".equals(sectionName)) { Assert.assertNull(fileName + " section '" + sectionName + "' should be first", lastSectionName); continue; } Assert.assertTrue(fileName + " section '" + sectionName + "' shouldn't end with 'Check'", !sectionName.endsWith("Check")); if (lastSectionName != null) { Assert.assertTrue( fileName + " section '" + sectionName + "' is out of order compared to '" + lastSectionName + "'", sectionName.toLowerCase(Locale.ENGLISH) .compareTo(lastSectionName.toLowerCase(Locale.ENGLISH)) >= 0); } validateCheckSection(moduleFactory, fileName, sectionName, section); lastSectionName = sectionName; } } }
From source file:com.eternitywall.ots.OtsCli.java
public static void verify(String argsOts, Hash hash, String argsFile) { try {/*from w w w.ja va 2 s .c om*/ Path pathOts = Paths.get(argsOts); byte[] byteOts = Files.readAllBytes(pathOts); DetachedTimestampFile detachedOts = DetachedTimestampFile.deserialize(byteOts); DetachedTimestampFile detached; HashMap<VerifyResult.Chains, VerifyResult> verifyResults; if (shasum == null) { // Read from file File file = new File(argsFile); System.out.println("Assuming target filename is '" + argsFile + "'"); detached = DetachedTimestampFile.from(new OpSHA256(), file); } else { // Read from hash option System.out.println("Assuming target hash is '" + Utils.bytesToHex(hash.getValue()) + "'"); detached = DetachedTimestampFile.from(hash); } try { verifyResults = OpenTimestamps.verify(detachedOts, detached); for (Map.Entry<VerifyResult.Chains, VerifyResult> entry : verifyResults.entrySet()) { String chain = ""; if (entry.getKey() == VerifyResult.Chains.BITCOIN) { chain = BitcoinBlockHeaderAttestation.chain; } else if (entry.getKey() == VerifyResult.Chains.LITECOIN) { chain = LitecoinBlockHeaderAttestation.chain; } else if (entry.getKey() == VerifyResult.Chains.ETHEREUM) { chain = EthereumBlockHeaderAttestation.chain; } System.out.println( "Success! " + Utils.toUpperFirstLetter(chain) + " " + entry.getValue().toString()); } } catch (Exception e) { System.out.println(e.getMessage()); return; } } catch (Exception e) { log.severe("No valid file"); } }
From source file:nc.noumea.mairie.appock.core.utility.AppockUtil.java
/** * Lit le contenu d'un fichier, et le convertit en base 64 * @param file fichier/* w w w. j a v a 2 s .c o m*/ * @return contenu base 64 * @throws IOException exception */ public static String readFileToBase64(File file) throws IOException { byte[] bytes; bytes = Files.readAllBytes(file.toPath()); StringBuilder sb = new StringBuilder(); sb.append("data:" + getMimeType(bytes) + ";base64,"); sb.append(org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.encodeBase64(bytes, false))); return sb.toString(); }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void testCopyToPathWithOptions() throws IOException { InputStream inputStream = new ByteArrayInputStream("hello!".getBytes(UTF_8)); filesystem.copyToPath(inputStream, Paths.get("replace_me.txt")); inputStream = new ByteArrayInputStream("hello again!".getBytes(UTF_8)); filesystem.copyToPath(inputStream, Paths.get("replace_me.txt"), StandardCopyOption.REPLACE_EXISTING); assertEquals("The bytes on disk should match those from the second InputStream.", "hello again!", new String(Files.readAllBytes(tmp.getRoot().resolve("replace_me.txt")), UTF_8)); }