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:caillou.company.clonemanager.gui.customComponent.results.ResultController.java

@Subscribe
public void handleMouseOverRow(MouseEnteredRowEvent mouseEnteredRowEvent) {

    if (popOver != null) {
        popOver.hide();//from   w w w  .j a  v  a  2 s. co  m
    }
    if (mouseEnteredRowEvent.getRow().getItem() == null) {
        return;
    }
    ApplicationFile myFileFX = mouseEnteredRowEvent.getRow().getItem();
    String mimeType = null;
    try {
        mimeType = Files.probeContentType(new File(myFileFX.getAbsolutePath()).toPath());
    } catch (IOException ex) {
        log.error(ErrorMessage.IOEXCEPTION_WHILE_MIMETYPE + myFileFX.getAbsolutePath());
    }

    if (mimeType != null && mimeType.startsWith("image/")) {
        try {
            ImageView imageView = new ImageView(
                    new File(myFileFX.getAbsolutePath()).toURI().toURL().toString());
            imageView.setFitWidth(100);
            imageView.setFitHeight(100);
            popOver = new PopOver();
            popOver.setContentNode(imageView);
            popOver.show(mouseEnteredRowEvent.getRow());
        } catch (MalformedURLException ex) {
            log.error(ErrorMessage.MALFORMEDURLEXCEPTION_WHILE_CREATINGIMAGE + myFileFX.getAbsolutePath());
        }
    }

}

From source file:com.github.riccardove.easyjasub.EasyJaSubInputFromCommand.java

private static String probeContentType(File file) {
    try {/*from  www. j a v  a 2  s  .  c om*/
        return Files.probeContentType(file.toPath());
    } catch (IOException ex) {
        return null;
    }
}

From source file:org.asamk.signal.Manager.java

private static SignalServiceAttachment createAttachment(String attachment) throws IOException {
    File attachmentFile = new File(attachment);
    InputStream attachmentStream = new FileInputStream(attachmentFile);
    final long attachmentSize = attachmentFile.length();
    String mime = Files.probeContentType(Paths.get(attachment));
    return new SignalServiceAttachmentStream(attachmentStream, mime, attachmentSize, null);
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static String getMimeType(File file) {

    String mimetype = null;//  w  ww . j  a  va  2  s.  com
    try {
        mimetype = Files.probeContentType(file.toPath());
    } catch (IOException ex) {

    }

    if (mimetype == null) {
        mimetype = "unknown";
    }
    return mimetype;
}

From source file:gdt.jgui.entity.folder.JFolderFacetOpenItem.java

private static boolean isTextFile(File file) {
    try {//from   w  w  w.  j  a va2 s .c om
        String mime$ = Files.probeContentType(file.toPath());
        //System.out.println("FileOpenItem: isTextFile:mime="+mime$);
        if (mime$.equals("text/plain"))
            return true;
        return false;
    } catch (Exception e) {
        Logger.getLogger(JFileOpenItem.class.getName()).info(e.toString());
        return false;
    }
}

From source file:io.cloudex.cloud.impl.google.GoogleCloudServiceImpl.java

/**
 * Upload the provided file into cloud storage
 * THis is what Google returns:// ww w .  ja va  2 s  .c o  m
 * <pre>
 * CONFIG: {
 "kind": "storage#object",
 "id": "ecarf/umbel_links.nt_out.gz/1397227987451000",
 "selfLink": "https://www.googleapis.com/storage/v1beta2/b/ecarf/o/umbel_links.nt_out.gz",
 "name": "umbel_links.nt_out.gz",
 "bucket": "ecarf",
 "generation": "1397227987451000",
 "metageneration": "1",
 "contentType": "application/x-gzip",
 "updated": "2014-04-11T14:53:07.339Z",
 "storageClass": "STANDARD",
 "size": "8474390",
 "md5Hash": "UPhXcZZGbD9198OhQcdnvQ==",
 "owner": {
  "entity": "user-00b4903a97e56638621f0643dc282444442a11b19141d3c7b425c4d17895dcf6",
  "entityId": "00b4903a97e56638621f0643dc282444442a11b19141d3c7b425c4d17895dcf6"
 },
 "crc32c": "3twYkA==",
 "etag": "CPj48u7X2L0CEAE="
}
  </pre>
 * @param filename
 * @param bucket
 * @throws IOException
 */
@Override
public io.cloudex.framework.cloud.entities.StorageObject uploadFileToCloudStorage(String filename,
        String bucket, Callback callback) throws IOException {

    FileInputStream fileStream = new FileInputStream(filename);
    String contentType;
    boolean gzipDisabled;

    if (GzipUtils.isCompressedFilename(filename)) {
        contentType = Constants.GZIP_CONTENT_TYPE;
        gzipDisabled = true;

    } else {
        contentType = Files.probeContentType((new File(filename)).toPath());
        if (contentType == null) {
            contentType = Constants.BINARY_CONTENT_TYPE;
        }
        gzipDisabled = false;
    }

    InputStreamContent mediaContent = new InputStreamContent(contentType, fileStream);

    // Not strictly necessary, but allows optimization in the cloud.
    mediaContent.setLength(fileStream.available());

    Storage.Objects.Insert insertObject = getStorage().objects()
            .insert(bucket,
                    new StorageObject().setName(
                            StringUtils.substringAfterLast(filename, FileUtils.PATH_SEPARATOR)),
                    mediaContent)
            .setOauthToken(this.getOAuthToken());

    insertObject.getMediaHttpUploader().setProgressListener(new UploadProgressListener(callback))
            .setDisableGZipContent(gzipDisabled);
    // For small files, you may wish to call setDirectUploadEnabled(true), to
    // reduce the number of HTTP requests made to the server.
    if (mediaContent.getLength() > 0 && mediaContent.getLength() <= 4 * FileUtils.ONE_MB /* 2MB */) {
        insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
    }

    StorageObject object = null;

    try {
        object = insertObject.execute();

    } catch (IOException e) {

        log.error("Error whilst uploading file", e);

        ApiUtils.block(5);
        // try again
        object = insertObject.execute();
    }

    return this.getCloudExStorageObject(object, bucket);
}

From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java

private void testUploadKeystore(String keystoreFormat, String filePath, String keyAlias, String storePassword)
        throws Exception {
    ClientRepresentation client = getClient(testRealm.getRealm(), app3.getId()).toRepresentation();
    final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR);

    // Load the keystore file
    URL fileUrl = (getClass().getClassLoader().getResource(filePath));
    if (fileUrl == null) {
        throw new IOException("File not found: " + filePath);
    }/*from  w w w  . j  a  v a 2 s  .co  m*/
    File keystoreFile = new File(fileUrl.getFile());
    ContentType keystoreContentType = ContentType.create(Files.probeContentType(keystoreFile.toPath()));

    // Get admin access token, no matter it's master realm's admin
    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.doGrantAccessTokenRequest(AuthRealm.MASTER,
            AuthRealm.ADMIN, AuthRealm.ADMIN, null, "admin-cli", null);
    assertEquals(200, accessTokenResponse.getStatusCode());

    final String url = suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/realms/"
            + testRealm.getRealm() + "/clients/" + client.getId()
            + "/certificates/jwt.credential/upload-certificate";

    // Prepare the HTTP request
    FileBody fileBody = new FileBody(keystoreFile, keystoreContentType);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody)
            .addTextBody("keystoreFormat", keystoreFormat).addTextBody("keyAlias", keyAlias)
            .addTextBody("storePassword", storePassword).addTextBody("keyPassword", "undefined").build();
    HttpPost httpRequest = new HttpPost(url);
    httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenResponse.getAccessToken());
    httpRequest.setEntity(entity);

    // Send the request
    HttpClient httpClient = HttpClients.createDefault();
    HttpResponse httpResponse = httpClient.execute(httpRequest);
    assertEquals(200, httpResponse.getStatusLine().getStatusCode());

    client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
    String pem;

    // Assert the uploaded certificate
    if (!keystoreFormat.equals(CERTIFICATE_PEM)) {
        InputStream keystoreIs = new FileInputStream(keystoreFile);
        KeyStore keyStore = getKeystore(keystoreIs, storePassword, keystoreFormat);
        keystoreIs.close();
        pem = KeycloakModelUtils.getPemFromCertificate((X509Certificate) keyStore.getCertificate(keyAlias));
    } else {
        pem = new String(Files.readAllBytes(keystoreFile.toPath()));
    }

    assertCertificate(client, certOld, pem);
}

From source file:org.wso2.carbon.appmgt.rest.api.util.utils.RestApiUtil.java

public static String readFileContentType(String filePath) throws AppManagementException {
    String fileContentType = null;
    try {/* w w  w . ja  va 2s.c  o m*/
        fileContentType = Files.probeContentType(Paths.get(filePath));
    } catch (IOException e) {
        throw new AppManagementException("Error occurred while reading file details from file " + filePath);
    }
    return fileContentType;
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void handleFileElement(String pid, int itemIndex, Element fileElement)
        throws URISyntaxException, IOException, FedoraClientException, XPathExpressionException {
    Node tempFile = fileElement.getElementsByTagName("TempFile").item(0);
    Node pathName = fileElement.getElementsByTagName("PathName").item(0);
    if (tempFile == null || pathName == null) {
        return;//from w w w  .jav  a  2 s  .co  m
    }

    String id = pid.substring("qucosa:".length());
    String tmpFileName = tempFile.getTextContent();
    String targetFilename = pathName.getTextContent();
    URI fileUri = fileHandlingService.copyTempfileToTargetFileSpace(tmpFileName, targetFilename, id);

    Node labelNode = fileElement.getElementsByTagName("Label").item(0);
    String label = (labelNode != null) ? labelNode.getTextContent() : "";

    final Path filePath = new File(fileUri).toPath();

    String detectedContentType = Files.probeContentType(filePath);
    if (!(Boolean) xPath.evaluate("MimeType[text()!='']", fileElement, XPathConstants.BOOLEAN)) {
        if (detectedContentType != null) {
            Element mimeTypeElement = fileElement.getOwnerDocument().createElement("MimeType");
            mimeTypeElement.setTextContent(detectedContentType);
            fileElement.appendChild(mimeTypeElement);
        }
    }

    if (!(Boolean) xPath.evaluate("FileSize[text()!='']", fileElement, XPathConstants.BOOLEAN)) {
        Element fileSizeElement = fileElement.getOwnerDocument().createElement("FileSize");
        fileSizeElement.setTextContent(String.valueOf(Files.size(filePath)));
        fileElement.appendChild(fileSizeElement);
    }

    String dsid = DSID_QUCOSA_ATT + (itemIndex);
    String state = determineDatastreamState(fileElement);
    DatastreamProfile dsp = fedoraRepository.createExternalReferenceDatastream(pid, dsid, label, fileUri,
            detectedContentType, state);
    fileElement.setAttribute("id", String.valueOf(itemIndex));
    addHashValue(fileElement, dsp);

    fileElement.removeChild(tempFile);
}