Example usage for java.nio.file Files probeContentType

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

Introduction

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

Prototype

public static String probeContentType(Path path) throws IOException 

Source Link

Document

Probes the content type of a file.

Usage

From source file:at.medevit.elexis.ehc.core.internal.EhcCoreServiceImpl.java

@Override
public String createXdmContainer(Patient patient, Mandant mandant, List<File> attachments, String xdmPath) {
    if (patient != null && mandant != null && attachments != null && xdmPath != null) {
        ConvenienceCommunication conCom = new ConvenienceCommunication();
        org.ehealth_connector.common.Patient ehealthPatient = EhcCoreMapper.getEhcPatient(patient);
        StringBuilder retInfo = new StringBuilder();
        retInfo.append(xdmPath);/*from   w  w  w  .ja  va 2s.  c o m*/
        for (File f : attachments) {
            try {
                if (f.exists()) {
                    String attachmentPath = f.getAbsolutePath();
                    DocumentDescriptor dc = null;
                    if (attachmentPath.toLowerCase().endsWith("xml")) {
                        if (isCdaDocument(f)) {
                            dc = DocumentDescriptor.CDA_R2;
                        } else {
                            dc = DocumentDescriptor.XML;
                        }
                    } else if (attachmentPath.toLowerCase().endsWith("pdf")) {
                        dc = DocumentDescriptor.PDF;
                    } else {
                        dc = new DocumentDescriptor(FilenameUtils.getExtension(attachmentPath),
                                Files.probeContentType(f.toPath()));
                    }

                    FileInputStream in = FileUtils.openInputStream(f);
                    DocumentMetadata metaData = conCom.addDocument(dc, in);
                    metaData.setPatient(ehealthPatient);
                    IOUtils.closeQuietly(in);
                    retInfo.append(":::");
                    retInfo.append(attachmentPath);

                } else {
                    LoggerFactory.getLogger(EhcCoreService.class).warn(
                            "creating xdm - patient [{}] - file does not exists [{}]", patient.getId(),
                            f.getAbsolutePath());
                }
            } catch (IOException e) {
                LoggerFactory.getLogger(EhcCoreService.class).error(
                        "creating xdm - patient [{}] - cannot add file [{}]", patient.getId(),
                        f.getAbsolutePath(), e);
            }
        }
        try {
            conCom.createXdmContents(xdmPath);
            if (retInfo.toString().contains(":::")) {
                return retInfo.toString();
            }
        } catch (Exception e) {
            LoggerFactory.getLogger(EhcCoreService.class)
                    .error("creating xdm - patient [{}] - cannot create xdm contents", patient.getId(), e);
        }
    }
    return null;
}

From source file:de.elomagic.maven.http.HTTPMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {//from  www  .j a  va 2 s .c  o m
        Executor executor;

        if (httpsInsecure) {
            getLog().info("Accepting unsecure HTTPS connections.");
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustAllStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

                final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslsf).build();

                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                        sfr);
                connectionManager.setDefaultMaxPerRoute(100);
                connectionManager.setMaxTotal(200);
                connectionManager.setValidateAfterInactivity(1000);

                HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                        .build();

                executor = Executor.newInstance(httpClient);
            } catch (Exception ex) {
                throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex);
            }
        } else {
            executor = Executor.newInstance();
        }

        Settings settings = session.getSettings();
        if (StringUtils.isNotBlank(serverId)) {
            Server server = settings.getServer(serverId);
            if (server == null) {
                throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml");
            }
            getLog().debug("ServerId: " + serverId);
            executor.auth(server.getUsername(), server.getPassword());
        }

        Request request = createRequestMethod();

        request.setHeader("Accept", accept);

        if (httpHeaders != null) {
            for (Entry<String, String> entry : httpHeaders.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (formParams != null) {
            Form form = Form.form();
            for (Entry<String, String> entry : formParams.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (fromFile != null) {
            if (!fromFile.exists()) {
                throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist.");
            }

            if (StringUtils.isBlank(contentType)) {
                contentType = Files.probeContentType(fromFile.toPath());
            }

            getLog().debug("From file: " + fromFile);
            getLog().debug("Upload file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue()));
            getLog().debug("Content type: " + contentType);

            if (StringUtils.isBlank(contentType)) {
                request.body(new FileEntity(fromFile));
            } else {
                request.body(new FileEntity(fromFile, ContentType.create(contentType)));
            }
        }

        getLog().info(method + " " + url);

        Response response = executor.execute(request);
        handleResponse(response);
    } catch (Exception ex) {
        getLog().error(ex);
        if (failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            getLog().info("Fail on error is disabled. Continue execution.");
        }
    }

}

From source file:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java

private void downloadFile(HttpServletRequest request, HttpServletResponse response, UserManager user,
        String archiveId, String filePath) throws IOException {

    Archive archive = null;//w  w  w  .  ja  va  2 s. c  o m
    CombineArchive combineArchive = null;
    try {
        archive = user.getArchive(archiveId, true);
        combineArchive = archive.getArchive();
    } catch (FileNotFoundException | CombineArchiveWebException e) {
        LOGGER.warn(e, MessageFormat.format(
                "Archive FileNotFound Exception, while handling donwload request for File {2} in Archive {1} in Workspace {0}",
                user.getWorkingDir(), archive, filePath));
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    }

    // check if file exits in the archive
    ArchiveEntry entry = combineArchive.getEntry(filePath);
    if (entry == null) {
        LOGGER.warn(MessageFormat.format("File not found in archive {1} in Workspace {0} : file = {2}",
                user.getWorkingDir(), archiveId, filePath));
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found in archive.");

        if (archive != null)
            archive.close();
        return;
    }

    // set the filename of the response
    response.addHeader("Content-Disposition",
            MessageFormat.format("inline; filename=\"{0}\"", entry.getFileName()));

    // extract the file
    try {
        File tempFile = File.createTempFile(Fields.TEMP_FILE_PREFIX, entry.getFileName());
        entry.extractFile(tempFile);

        // set the mime type of the response
        response.setContentType(Files.probeContentType(tempFile.toPath()));

        OutputStream output = response.getOutputStream();
        InputStream input = new FileInputStream(tempFile);

        // copy the streams
        IOUtils.copy(input, output);

        // flush'n'close
        output.flush();
        output.close();
        input.close();

        response.flushBuffer();

        // remove the temp file
        tempFile.delete();
        if (archive != null)
            archive.close();
    } catch (IOException e) {
        LOGGER.warn(MessageFormat.format(
                "Error while extracting and serving file in archive {1} in Workspace {0} : file = {2}",
                user.getWorkingDir(), archiveId, filePath));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error while extracting and serving file.");

        if (archive != null)
            archive.close();
        return;
    }

}

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*  ww w  . j  a  va  2  s .  c  om*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:com.thoughtworks.go.http.mocks.MockServletContext.java

@Override
public String getMimeType(String filePath) {
    String extension = StringUtils.getFilenameExtension(filePath);
    if (this.mimeTypes.containsKey(extension)) {
        return this.mimeTypes.get(extension).toString();
    } else {//from  w w w .ja  v a 2  s. co  m
        try {
            return Optional.of(Files.probeContentType(Paths.get(filePath))).orElse("application/octet-stream");
        } catch (IOException e) {
            return "application/octet-stream";
        }
    }
}

From source file:com.o2o.util.WebUtils.java

public static String getContentType(String fileName) {
    Path path = Paths.get(fileName);
    String contentType = null;/*from w  w  w.ja va2s . com*/
    try {
        contentType = Files.probeContentType(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return contentType;
}

From source file:spdxedit.SpdxLogic.java

public static FileType[] getTypesForFile(Path path) {
    String extension = StringUtils
            .lowerCase(StringUtils.substringAfterLast(path.getFileName().toString(), "."));
    ArrayList<FileType> fileTypes = new ArrayList<>();
    if (sourceFileExtensions.contains(extension)) {
        fileTypes.add(SpdxFile.FileType.fileType_source);
    }/*from   w w w  .  j  av a2 s  .c o m*/
    if (binaryFileExtensions.contains(extension)) {
        fileTypes.add(FileType.fileType_binary);
    }
    if (textFileExtensions.contains(extension)) {
        fileTypes.add(FileType.fileType_text);
    }
    if (archiveFileExtensions.contains(extension)) {
        fileTypes.add(FileType.fileType_archive);
    }
    if ("spdx".equals(extension)) {
        fileTypes.add(FileType.fileType_spdx);
    }
    try {
        String mimeType = Files.probeContentType(path);
        if (StringUtils.startsWith(mimeType, MediaType.ANY_AUDIO_TYPE.type())) {
            fileTypes.add(FileType.fileType_audio);
        }
        if (StringUtils.startsWith(mimeType, MediaType.ANY_IMAGE_TYPE.type())) {
            fileTypes.add(FileType.fileType_image);
        }
        if (StringUtils.startsWith(mimeType, MediaType.ANY_APPLICATION_TYPE.type())) {
            fileTypes.add(FileType.fileType_application);
        }

    } catch (IOException ioe) {
        logger.warn("Unable to access file " + path.toString() + " to determine its type.", ioe);
    }
    return fileTypes.toArray(new FileType[] {});
}

From source file:org.dataconservancy.packaging.impl.PackageFileAnalyzer.java

private PackagedResource populateFileResource(final Resource fileResource, final Path extractDirectory,
        final Model model) throws URISyntaxException, IOException {

    // Handle the domain object first, then we'll get the binary content it describes.
    final URI binaryFileURI = new URI(fileResource.getURI());
    final BasicLdpResource binaryFileResource = new BasicLdpResource(binaryFileURI);
    binaryFileResource.setType(PackagedResource.Type.NONRDFSOURCE);

    final Path resourcePath = UriUtility.resolveBagUri(extractDirectory, binaryFileURI);
    String mimeType = Files.probeContentType(resourcePath);
    if (mimeType == null) {
        mimeType = APPLICATION_OCTETSTREAM;
    }/*from ww  w.  java2s  . c o m*/
    binaryFileResource.setMediaType(mimeType);
    binaryFileResource.setBody(new FileInputStream(resourcePath.toFile()));

    final BasicLdpResource domainObjectResource;

    final ResIterator nodeIterator = model.listResourcesWithProperty(DESCRIBES_PROPERTY, fileResource);
    if (!nodeIterator.hasNext()) {
        throw new RuntimeException("Could not find RDFSource for: " + binaryFileURI);
    } else {
        // There should be only one resource
        final Resource domainObject = nodeIterator.next();
        final URI domainObjectURI = new URI(domainObject.getURI());
        domainObjectResource = new BasicLdpResource(domainObjectURI);
        domainObjectResource.setType(PackagedResource.Type.RDFSOURCE);
        binaryFileResource.setDescription(domainObjectResource);

        final Path domainObjectResourcePath = UriUtility.resolveBagUri(extractDirectory, domainObjectURI);
        domainObjectResource.setMediaType(getDomainObjectMimeType(domainObjectResourcePath));
        domainObjectResource.setBody(new FileInputStream(domainObjectResourcePath.toFile()));
    }

    return binaryFileResource;

}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*from w  w w  . ja v a  2  s .c  o  m*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Streams the file specified by the path
 */// ww  w  .j a v  a2 s  . c om
@RequestMapping(value = "/file/{clientId}/{file:.*}", method = RequestMethod.GET)
public void streamFile(@PathVariable("clientId") String clientId, @PathVariable("file") String file,
        HttpServletResponse response) throws IOException {

    Path path = repoRoot.resolve(clientId).resolve(file);

    if (Files.notExists(path) || Files.isDirectory(path)) {
        log.log(Level.WARNING, "Failed streaming file: " + path);
        response.setStatus(404);
        return;
    }

    response.setContentType(Files.probeContentType(path));
    try (InputStream in = Files.newInputStream(path)) {
        IOUtils.copy(in, response.getOutputStream());
        response.flushBuffer();
    }
}