Example usage for java.nio.file Files readAllBytes

List of usage examples for java.nio.file Files readAllBytes

Introduction

In this page you can find the example usage for java.nio.file Files readAllBytes.

Prototype

public static byte[] readAllBytes(Path path) throws IOException 

Source Link

Document

Reads all the bytes from a file.

Usage

From source file:com.googlesource.gerrit.plugins.xdocs.formatter.FormatterUtil.java

/**
 * Returns the CSS from the file/*from   ww w  .  j  av a  2  s  .c  o m*/
 * "<review-site>/data/<plugin-name>/css/<name>.css".
 *
 * @param name the name of the CSS file without the ".css" file extension
 * @return the CSS from the file; HTML characters are escaped;
 *         <code>null</code> if the file doesn't exist
 * @throws IOException thrown in case of an I/O Error while reading the CSS
 *         file
 */
public String getGlobalCss(String name) throws IOException {
    Path p = Paths.get(baseDir.getAbsolutePath(), "css", name + ".css");
    if (Files.exists(p)) {
        byte[] css = Files.readAllBytes(p);
        return escapeHtml(new String(css, UTF_8));
    }
    return null;
}

From source file:com.ibm.iotf.connector.Connector.java

private static void updateJaasConfiguration(MessageHubCredentials credentials) throws IOException {
    String templatePath = resourceDir + File.separator + "templates" + File.separator + "jaas.conf.template";
    String path = resourceDir + File.separator + "jaas.conf";
    OutputStream jaasStream = null;

    logger.log(Level.INFO, "Updating JAAS configuration");

    try {// w ww  .  ja va2 s . c  o m
        String templateContents = new String(Files.readAllBytes(Paths.get(templatePath)));
        jaasStream = new FileOutputStream(path, false);

        // Replace username and password in template and write
        // to jaas.conf in resources directory.
        String fileContents = templateContents.replace("$USERNAME", credentials.getUser()).replace("$PASSWORD",
                credentials.getPassword());

        jaasStream.write(fileContents.getBytes(Charset.forName("UTF-8")));
    } catch (final IOException e) {
        logger.log(Level.FATAL, "Error while reading/updating JAAS configuration file: " + e.getMessage(), e);
        throw e;
    } finally {
        if (jaasStream != null) {
            try {
                jaasStream.close();
            } catch (final Exception e) {
                logger.log(Level.WARN, "Error closing JAAS config file: " + e.getMessage(), e);
            }
        }
    }

}

From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java

@RequestMapping(path = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadFile(@PathVariable("id") long id) {
    try {//from www  .  ja v  a2  s  .  c o m

        Dokument document = dokumentService.findOne(id);

        HttpHeaders header = new HttpHeaders();
        //header.setContentType(MediaType.valueOf(document.getFajlTip()));

        String nazivfajla = document.getFajl();
        int li = nazivfajla.lastIndexOf('\\');
        String subsnaziv = nazivfajla.substring(li + 1, nazivfajla.length());
        header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + subsnaziv);
        File file = new File(nazivfajla);

        Path path = file.toPath();

        byte[] outputByte = Files.readAllBytes(path);

        String fajltype = Files.probeContentType(path);
        System.out.println(fajltype + " je tip");

        header.setContentType(MediaType.valueOf(fajltype));

        header.setContentLength(outputByte.length);

        return new ResponseEntity<>(outputByte, header, HttpStatus.OK);
    } catch (Exception e) {
        return null;
    }
}

From source file:it.polimi.diceH2020.launcher.controller.LaunchAnalysis.java

@RequestMapping(value = "/simulationSetup", method = RequestMethod.GET)
public String showSimulationsManagerForm(SessionStatus sessionStatus, Model model,
        @ModelAttribute("instanceDataMultiProvider") String instanceDataMultiProviderPath,
        @ModelAttribute("pathList") ArrayList<String> pathList,
        @ModelAttribute("scenario") String scenarioString, RedirectAttributes redirectAttrs) {

    Scenarios scenario = Scenarios.valueOf(scenarioString);
    model.addAttribute("scenario", scenario);
    redirectAttrs.addAttribute("scenario", scenario);

    if (pathList.size() == 0) {
        deleteUploadedFiles(pathList);/*w  w  w  .  j a va  2 s .co  m*/
        redirectAttrs.addAttribute("message", "You haven't submitted any file!");
        return "redirect:/launchRetry";
    }
    if (instanceDataMultiProviderPath == null) {
        deleteUploadedFiles(pathList);
        redirectAttrs.addAttribute("message", "Select a Json file!");
        return "redirect:/launchRetry";
    }

    Optional<InstanceDataMultiProvider> idmp = validator
            .readInstanceDataMultiProvider(Paths.get(instanceDataMultiProviderPath));

    if (idmp.isPresent()) {
        if (!idmp.get().validate()) {
            deleteUploadedFiles(pathList);
            model.addAttribute("message", idmp.get().getValidationError());
            return "redirect:/launchRetry";
        }
    } else {
        model.addAttribute("message", "Error with InstanceDataMultiProvider");
        deleteUploadedFiles(pathList);
        return "redirect:/launchRetry";
    }

    InstanceDataMultiProvider instanceDataMultiProvider = idmp.get();

    String check = scenarioValidation(instanceDataMultiProvider, scenario);
    if (!check.equals("ok")) {
        deleteUploadedFiles(pathList);
        redirectAttrs.addAttribute("message", check);
        return "redirect:/launchRetry";
    }

    List<InstanceDataMultiProvider> inputList = JsonSplitter
            .splitInstanceDataMultiProvider(instanceDataMultiProvider, scenario);

    if (inputList.size() > 1) {
        List<String> providersList = inputList.stream().map(InstanceDataMultiProvider::getProvider)
                .collect(Collectors.toList());
        if (!minNumTxt(providersList, pathList)) {
            deleteUploadedFiles(pathList);
            model.addAttribute("message",
                    "Not enough TXT files selected.\nFor each provider in your JSON there must be 2 TXT files containing in their name the provider name.");
            return "redirect:/launchRetry";
        }
    }

    List<SimulationsManager> simManagerList = initializeSimManagers(inputList);
    List<String> txtFoldersList = new ArrayList<>();

    for (SimulationsManager sm : simManagerList) {
        sm.setInputFileName(Paths.get(instanceDataMultiProviderPath).getFileName().toString());
        InstanceDataMultiProvider input = sm.getInputData();
        String txtFolder = new String();
        try {
            txtFolder = fileUtility.createInputSubFolder();
            txtFoldersList.add(txtFolder);
        } catch (Exception e) {
            deleteUploadedFiles(pathList);
            deleteUploadedFiles(txtFoldersList);
            redirectAttrs.addAttribute("message",
                    "Too many folders for TXTs with the same name have been created!");
            return "redirect:/launchRetry";
        }
        for (Entry<String, Map<String, Map<String, JobProfile>>> jobIDs : input.getMapJobProfiles()
                .getMapJobProfile().entrySet()) {
            for (Entry<String, Map<String, JobProfile>> provider : jobIDs.getValue().entrySet()) {
                for (Entry<String, JobProfile> typeVMs : provider.getValue().entrySet()) {

                    String secondPartOfTXTName = getSecondPartOfReplayersName(jobIDs.getKey(),
                            provider.getKey(), typeVMs.getKey());

                    List<String> txtToBeSaved = pathList.stream().filter(s -> s.contains(secondPartOfTXTName))
                            .filter(s -> s.contains(input.getId())).collect(Collectors.toList());
                    if (txtToBeSaved.isEmpty()) {
                        deleteUploadedFiles(pathList);
                        deleteUploadedFiles(txtFoldersList);
                        model.addAttribute("message",
                                "Missing TXT file for Instance:" + input.getId() + ", Job: " + jobIDs.getKey()
                                        + ", Provider:" + provider.getKey() + ", TypeVM:" + typeVMs.getKey());
                        return "redirect:/launchRetry";
                    }

                    for (String srcPath : txtToBeSaved) {
                        File src = new File(srcPath);

                        String fileContent = new String();
                        try {
                            fileContent = new String(Files.readAllBytes(Paths.get(srcPath)));
                            FileOutputStream fooStream = new FileOutputStream(src, false); // true to append
                            // false to overwrite.
                            byte[] myBytes = Compressor.compress(fileContent).getBytes();
                            fooStream.write(myBytes);
                            fooStream.close();

                            fileUtility.copyFile(srcPath, txtFolder + src.getName());

                        } catch (IOException e) {
                            deleteUploadedFiles(pathList);
                            deleteUploadedFiles(txtFoldersList);
                            model.addAttribute("message",
                                    "Problem with TXT paths. [TXT file for Instance:" + input.getId()
                                            + ", Job: " + jobIDs.getKey() + ", Provider:" + provider.getKey()
                                            + ", TypeVM:" + typeVMs.getKey() + "]");
                            return "redirect:/launchRetry";
                        }
                        if (fileContent.length() == 0) {
                            deleteUploadedFiles(pathList);
                            deleteUploadedFiles(txtFoldersList);
                            model.addAttribute("message",
                                    "Missing TXT file for Instance:" + input.getId() + ", Job: "
                                            + jobIDs.getKey() + ", Provider:" + provider.getKey() + ", TypeVM:"
                                            + typeVMs.getKey());
                            return "redirect:/launchRetry";
                        }
                        sm.addInputFolder(txtFolder);
                        sm.setNumCompletedSimulations(0);
                        sm.buildExperiments();
                    }
                }
            }
        }
    }
    deleteUploadedFiles(pathList);

    for (SimulationsManager sm : simManagerList) {
        ds.simulation(sm);
    }
    model.addAttribute("simManagersList", simManagerList);
    return "redirect:/";
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read pem private key./*ww  w . ja v  a2 s .  co  m*/
 *
 * @param file
 *            the file
 * @param securityProvider
 *            the security provider
 * @return the private key
 * @throws Exception
 *             is thrown if if a security error occur
 */
public static PrivateKey readPemPrivateKey(final File file, final SecurityProvider securityProvider)
        throws Exception {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());

    final String privateKeyAsString = new String(keyBytes).replace(BEGIN_RSA_PRIVATE_KEY_PREFIX, "")
            .replace(END_RSA_PRIVATE_KEY_SUFFIX, "").trim();

    final byte[] decoded = new Base64().decode(privateKeyAsString);

    return readPrivateKey(decoded, securityProvider);
}

From source file:com.sastix.cms.server.services.content.impl.ZipHandlerServiceImpl.java

public String findScormStartPage(final Path metadataPath) {
    Document doc;/*from w w  w .  j  a v a2s  . co  m*/
    try {
        doc = Jsoup.parse(new String(Files.readAllBytes(metadataPath), "UTF-8"), "", Parser.xmlParser());
    } catch (final IOException e) {
        throw new ResourceAccessError("Zip " + metadataPath.getFileName() + " cannot be read. ");
    }
    String startPage = null;
    for (Element e : doc.select("resources")) {
        startPage = e.select("resource").get(0).attr("href");
    }
    if (startPage == null) {
        throw new ResourceAccessError("Start page in Zip " + metadataPath.getFileName() + " cannot be found");
    }
    return startPage;
}

From source file:com.qspin.qtaste.testsuite.impl.TestDataImpl.java

private void loadFile(String key, String filename) throws QTasteDataException {
    Path filePath = Paths.get(filename);
    if (!filePath.isAbsolute()) {
        filePath = Paths.get(this.getTestCaseDirectory() + File.separator + filename);
    }//  ww  w . j av a 2s  . c om

    try {
        byte[] buffer = Files.readAllBytes(filePath);
        logger.debug("Loaded file: " + filePath.toString() + " size:" + buffer.length);
        hashFiles.put(key, buffer);
    } catch (IOException e) {
        throw new QTasteDataException(e.getMessage());
    }
}

From source file:com.facebook.buck.android.AndroidBinaryIntegrationTest.java

@Test
public void testPreprocessorForcesReDex() throws IOException {
    String target = "//java/com/preprocess:disassemble";
    Path outputFile = workspace.buildAndReturnOutput(target);
    String output = new String(Files.readAllBytes(outputFile), UTF_8);
    assertThat(output, containsString("content=2"));

    workspace.replaceFileContents("java/com/preprocess/convert.py", "content=2", "content=3");

    outputFile = workspace.buildAndReturnOutput(target);
    output = new String(Files.readAllBytes(outputFile), UTF_8);
    assertThat(output, containsString("content=3"));
}

From source file:com.frequentis.maritime.mcsr.web.rest.InstanceResourceIntTest.java

@PostConstruct
public void setup() throws IOException {
    MockitoAnnotations.initMocks(this);
    InstanceResource instanceResource = new InstanceResource();
    ReflectionTestUtils.setField(instanceResource, "instanceService", instanceService);
    ReflectionTestUtils.setField(instanceResource, "designService", designService);
    ReflectionTestUtils.setField(instanceResource, "instanceConverter", instanceConverter);
    this.restInstanceMockMvc = MockMvcBuilders.standaloneSetup(instanceResource)
            .setCustomArgumentResolvers(pageableArgumentResolver).setMessageConverters(jacksonMessageConverter)
            .build();/* w ww .java2 s  .  c om*/
    // Load XML
    Path path = appContext.getResource("classpath:dataload/xml/AddressForPersonLookupServiceInstance.xml")
            .getFile().toPath();
    addressForPersonLookupServiceInstanceXmlContent = new String(Files.readAllBytes(path));
}