Example usage for java.net URLConnection getFileNameMap

List of usage examples for java.net URLConnection getFileNameMap

Introduction

In this page you can find the example usage for java.net URLConnection getFileNameMap.

Prototype

public static FileNameMap getFileNameMap() 

Source Link

Document

Loads filename map (a mimetable) from a data file.

Usage

From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java

private String getMimeType(File file) {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    return fileNameMap.getContentTypeFor(file.toString());
}

From source file:es.alvsanand.webpage.web.beans.admin.ImageBean.java

public void handleFileUpload(FileUploadEvent fileUploadEvent) {
    logger.info("Uploaded: {" + fileUploadEvent.getFile().getFileName() + "}");

    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent fileUploadComponent = FacesUtils.findComponent(context.getViewRoot(), "fileUpload");

    InputStream inputStream = null;
    try {//from   w w w .ja  v  a  2  s . c  om
        inputStream = fileUploadEvent.getFile().getInputstream();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] buf = new byte[1024];

        int length;

        while ((length = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, length);
        }

        inputStream.close();

        photoData = outputStream.toByteArray();

        outputStream.close();

        FileNameMap fileNameMap = URLConnection.getFileNameMap();

        photoMediaType = fileNameMap.getContentTypeFor(fileUploadEvent.getFile().getFileName());

        FacesMessage message = new FacesMessage();
        message.setDetail(MessageResources.getMessage(MessageResources.ADMIN_RESOURCE_BUNDLE_NAME,
                "admin.uploadedFile.message.detail", null));
        message.setSummary(MessageResources.getMessage(MessageResources.ADMIN_RESOURCE_BUNDLE_NAME,
                "admin.uploadedFile.message.summary", null));
        message.setSeverity(FacesMessage.SEVERITY_INFO);

        FacesContext.getCurrentInstance().addMessage(null, message);
    } catch (IOException ioException) {
        FacesMessage message = new FacesMessage();
        message.setDetail(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME,
                "error.form.validation.loadArticleBulkUpload.badFile.detail", null));
        message.setSummary(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME,
                "error.form.validation.loadArticleBulkUpload.badFile.summary", null));
        message.setSeverity(FacesMessage.SEVERITY_ERROR);

        FacesContext.getCurrentInstance().addMessage(fileUploadComponent.getClientId(context), message);
        return;
    } catch (Exception exception) {
        logger.error("Error uploading file:", exception);

        return;
    }
}

From source file:com.odoo.base.ir.Attachment.java

@SuppressWarnings("deprecation")
private Notification setFileIntent(Uri uri) {
    Log.v(TAG, "setFileIntent()");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    FileNameMap mime = URLConnection.getFileNameMap();
    String mimeType = mime.getContentTypeFor(uri.getPath());
    intent.setDataAndType(uri, mimeType);
    mNotificationResultIntent = PendingIntent.getActivity(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationBuilder.addAction(R.drawable.ic_odoo_o, "Download attachment", mNotificationResultIntent);
    mNotificationBuilder.setOngoing(false);
    mNotificationBuilder.setAutoCancel(true);
    mNotificationBuilder.setContentTitle("Attachment downloaded");
    mNotificationBuilder.setContentText("Download Complete");
    mNotificationBuilder.setProgress(0, 0, false);
    mNotification = mNotificationBuilder.build();
    mNotification.setLatestEventInfo(mContext, "Attachment downloaded", "Download complete",
            mNotificationResultIntent);//w  ww.  j a v  a2s. c o  m
    return mNotification;

}

From source file:com.openerp.base.ir.Attachment.java

@SuppressWarnings("deprecation")
private Notification setFileIntent(Uri uri) {
    Log.v(TAG, "setFileIntent()");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    FileNameMap mime = URLConnection.getFileNameMap();
    String mimeType = mime.getContentTypeFor(uri.getPath());
    intent.setDataAndType(uri, mimeType);
    mNotificationResultIntent = PendingIntent.getActivity(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationBuilder.addAction(R.drawable.ic_oe_notification, "Download attachment",
            mNotificationResultIntent);//from   www.  ja  va  2s  .c om
    mNotificationBuilder.setOngoing(false);
    mNotificationBuilder.setAutoCancel(true);
    mNotificationBuilder.setContentTitle("Attachment downloaded");
    mNotificationBuilder.setContentText("Download Complete");
    mNotificationBuilder.setProgress(0, 0, false);
    mNotification = mNotificationBuilder.build();
    mNotification.setLatestEventInfo(mContext, "Attachment downloaded", "Download complete",
            mNotificationResultIntent);
    return mNotification;

}

From source file:org.pentaho.metaverse.api.analyzer.kettle.KettleAnalyzerUtil.java

/**
 * Builds a {@link IDocument} given the provided details.
 *
 * @param builder   the {@link IMetaverseBuilder}
 * @param meta      the {@link AbstractMeta} (trans or job)
 * @param id        the meta id (filename)
 * @param namespace the {@link INamespace}
 * @return a new {@link IDocument}//from w w  w . j  a  v a 2  s. c om
 */
public static IDocument buildDocument(final IMetaverseBuilder builder, final AbstractMeta meta, final String id,
        final INamespace namespace) {

    if (builder == null || builder.getMetaverseObjectFactory() == null) {
        log.warn(Messages.getString("WARN.UnableToBuildDocument"));
        return null;
    }

    final IDocument metaverseDocument = builder.getMetaverseObjectFactory().createDocumentObject();
    if (metaverseDocument == null) {
        log.warn(Messages.getString("WARN.UnableToBuildDocument"));
        return null;
    }

    metaverseDocument.setNamespace(namespace);
    metaverseDocument.setContent(meta);
    metaverseDocument.setStringID(id);
    metaverseDocument.setName(meta.getName());
    metaverseDocument.setExtension(meta.getDefaultExtension());
    metaverseDocument.setMimeType(URLConnection.getFileNameMap()
            .getContentTypeFor(meta instanceof TransMeta ? "trans.ktr" : "job.kjb"));
    metaverseDocument.setContext(new AnalysisContext(DictionaryConst.CONTEXT_RUNTIME));
    String normalizedPath = KettleAnalyzerUtil.normalizeFilePathSafely(id);
    metaverseDocument.setProperty(DictionaryConst.PROPERTY_NAME, meta.getName());
    metaverseDocument.setProperty(DictionaryConst.PROPERTY_PATH, normalizedPath);
    metaverseDocument.setProperty(DictionaryConst.PROPERTY_NAMESPACE, namespace.getNamespaceId());

    return metaverseDocument;
}

From source file:com.openerp.base.ir.Attachment.java

private void requestIntent(Uri uri) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    FileNameMap mime = URLConnection.getFileNameMap();
    String mimeType = mime.getContentTypeFor(uri.getPath());
    intent.setDataAndType(uri, mimeType);
    mContext.startActivity(intent);/*from  ww w  . jav a2  s . c o  m*/
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good file request with specific "Accept" header
 * Expected: Status 200//from  w  w  w .  j av a 2 s.  c  o m
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestSpecificAcceptHeader() throws IOException {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", REQUEST_STRING);
    MockHttpServletResponse res = new MockHttpServletResponse();
    final int lowContentLength = 4;
    final int highContentLength = 8;
    String expectedMimeType = URLConnection.getFileNameMap().getContentTypeFor(dataFileOne.getName());

    //run the handle request
    fileController.handleFileGetRequest("foo", expectedMimeType, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertTrue("Content Length out of bounds: " + res.getContentLength(),
            res.getContentLength() > lowContentLength && res.getContentLength() < highContentLength);
    byte[] originalContent = DATA_FILE_ONE_CONTENT.getBytes();
    assertEquals(new String(originalContent), new String(res.getContentAsByteArray()).trim());
}

From source file:es.alvsanand.webpage.web.beans.session.RegistrationBean.java

public void handleFileUpload(FileUploadEvent fileUploadEvent) {
    logger.info("Uploaded: {" + fileUploadEvent.getFile().getFileName() + "}");

    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent fileUploadComponent = FacesUtils.findComponent(context.getViewRoot(), "fileUpload");

    InputStream inputStream = null;
    try {//w  ww  .  ja  va2s  .  co m
        inputStream = fileUploadEvent.getFile().getInputstream();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] buf = new byte[1024];

        int length;

        while ((length = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, length);
        }

        inputStream.close();

        photoData = outputStream.toByteArray();

        outputStream.close();

        FileNameMap fileNameMap = URLConnection.getFileNameMap();

        photoMediaType = fileNameMap.getContentTypeFor(fileUploadEvent.getFile().getFileName());

        showFileUpload = false;
    } catch (IOException e1) {
        FacesMessage message = new FacesMessage();
        message.setDetail(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME,
                "error.modifyPersonalData.fileUpload.detail", null));
        message.setSummary(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME,
                "error.modifyPersonalData.fileUpload.summary", null));
        message.setSeverity(FacesMessage.SEVERITY_ERROR);

        FacesContext.getCurrentInstance().addMessage(fileUploadComponent.getClientId(context), message);

        showFileUpload = false;
        return;
    }
}

From source file:org.dataconservancy.ui.api.FileControllerTest.java

/**
 * Test handling a good non-text file request with specific "Accept" header
 * Expected: Status 200/*from ww  w. ja  v a  2 s  . c  om*/
 *           Etag header
 *           Content-Disposition header
 *           Content-Type header
 *           Content-Lenth header
 *           Last-modified header
 *           File bytestream
 * @throws IOException
 */
@Test
public void testGetFileRequestBinaryFile() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest("GET", "file/foo");
    MockHttpServletResponse res = new MockHttpServletResponse();

    java.io.File binaryFile = new java.io.File(FileControllerTest.class.getResource(FILES_ONLY_ZIP).toURI());
    byte fileContents[] = IOUtils.toByteArray(new FileInputStream(binaryFile));
    long expectedContentLength = binaryFile.length();
    DataFile binaryDataFile = new DataFile("foo", "ZipFileName.zip",
            binaryFile.toURI().toURL().toExternalForm(), "application/zip", binaryFile.getPath(),
            binaryFile.length(), new ArrayList<String>());

    FileBizService fileBizService = fileController.getFileBizService();
    when(fileBizService.getFile("foo", admin)).thenReturn(binaryDataFile);
    when(fileBizService.getLastModifiedDate("foo")).thenReturn(lastModifiedDate);
    RequestUtil requestUtil = fileController.getRequestUtil();
    when(requestUtil.buildRequestUrl(any(HttpServletRequest.class))).thenReturn("foo");

    String expectedMimeType = URLConnection.getFileNameMap().getContentTypeFor(binaryDataFile.getName());

    //run the handle request
    fileController.handleFileGetRequest("foo", null, null, req, res);
    //Test status code
    assertEquals(200, res.getStatus());
    //Test headers
    assertNotNull(res.getHeader(ETAG));
    assertNotNull(res.getHeader(CONTENT_DISPOSITION));
    assertNotNull(res.getContentType());
    assertEquals(expectedMimeType, res.getContentType());
    assertNotNull(res.getHeader(LAST_MODIFIED));
    assertEquals(rfcDateFormatter(lastModifiedDate), res.getHeader(LAST_MODIFIED));
    assertEquals(expectedContentLength, res.getContentLength());

    byte[] responseContent = res.getContentAsByteArray();
    assertArrayEquals(fileContents, responseContent);

}

From source file:org.soaplab.clients.spinet.ServiceController.java

/*************************************************************************
 * Get a suggested file extension and content (MIME) type for the
 * given result. Return a reasonable default if the real ones are
 * not specified.//w ww . java  2s  .c o m
 *************************************************************************/
public ResultInfo getResultTypes() throws SoaplabException {
    Map<String, Object> spec = getResultSpec();

    ResultInfo info = new ResultInfo();
    info.setContentType((String) spec.get(SoaplabConstants.MIME_TYPE));
    String extension = (String) spec.get(SoaplabConstants.FILE_EXT);
    if (StringUtils.isNotBlank(extension)) {
        if (!extension.startsWith("."))
            extension = "." + extension;
        info.setFileExtension(extension);
        if (StringUtils.isBlank(info.getContentType())) {
            info.setContentType(URLConnection.getFileNameMap().getContentTypeFor("x" + extension));
        }
    }

    // default values
    if (StringUtils.isBlank(info.getContentType())) {
        String type = (String) spec.get(SoaplabConstants.RESULT_TYPE);
        if (SoaplabConstants.TYPE_BINARY_SIMPLE.equals(type)
                || SoaplabConstants.TYPE_BINARY_ARRAY.equals(type)) {
            info.setContentType("application/octet-stream");
        } else {
            info.setContentType("text/plain");
        }
    }
    if (StringUtils.isBlank(info.getFileExtension()))
        info.setFileExtension("");

    if (log.isDebugEnabled()) {
        log.debug(getServiceName() + " RES: " + getResultName() + ", CT: " + info.getContentType() + ", EXT: "
                + info.getFileExtension());
    }
    return info;
}