Java Code Examples for java.net.URLConnection#guessContentTypeFromStream()

The following examples show how to use java.net.URLConnection#guessContentTypeFromStream() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void contentTest() throws Exception {

    URL url = this.getClass().getResource("../../../../amazon-aws-logo.jpg");
    String tmpFileName = url.getFile();

    File file = new File(tmpFileName);
    String fileName = file.getName();
    InputStream is = url.openStream();
    String contentType = URLConnection.guessContentTypeFromStream(is);

    contentHelper.uploadContent(contentType, file.length(), bucketName, fileName, is);

    Thread.sleep(500);
    boolean doesObjectExist = s3Client.doesObjectExist(bucketName, fileName);
    Assert.assertTrue(doesObjectExist);

    S3ObjectInputStream inputStream = contentHelper.downloadContent(bucketName, fileName);
    Assert.assertNotNull(inputStream);

    contentHelper.deleteContent(bucketName, fileName);
    Thread.sleep(500);

    doesObjectExist = s3Client.doesObjectExist(bucketName, fileName);
    Assert.assertFalse(doesObjectExist);
}
 
Example 2
private Media uploadMedia(User _user) throws IOException {
    URL url = this.getClass().getResource("../../../../amazon-aws-logo.jpg");
    String tmpFileName = url.getFile();

    File file = new File(tmpFileName);
    String fileName = file.getName();
    InputStream is = url.openStream();
    String contentType = URLConnection.guessContentTypeFromStream(is);

    Comment comment = new Comment();
    comment.setText("My comment");
    Set<Comment> comments = new HashSet<>();
    comments.add(comment);

    Media tmpMedia = contentFacade.uploadPictureToS3(_user, fileName, is, contentType, comment);
    return tmpMedia;
}
 
Example 3
Source Project: smarthome   File: HttpUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Determine the content type from the data.
 *
 * @param data the data as a buffer of bytes
 * @return the MIME type of the content, null if the content type could not be found
 */
public static String guessContentTypeFromData(byte[] data) {
    String contentType = null;

    // URLConnection.guessContentTypeFromStream(input) is not sufficient to detect all JPEG files
    if (isJpeg(data)) {
        return "image/jpeg";
    }

    try (final ByteArrayInputStream input = new ByteArrayInputStream(data)) {
        try {
            contentType = URLConnection.guessContentTypeFromStream(input);
            if (contentType != null && contentType.isEmpty()) {
                contentType = null;
            }
        } catch (final IOException e) {
            LOGGER.debug("Failed to determine content type: {}", e.getMessage());
        }
    } catch (final IOException ex) {
        // Error on closing input stream -- nothing we can do here.
    }
    return contentType;
}
 
Example 4
private boolean checkFileType(MultipartFile file) throws IOException {
    byte[] content = file.getBytes();
    InputStream is = new BufferedInputStream(new ByteArrayInputStream(content));
    String mimeType = URLConnection.guessContentTypeFromStream(is);
    if(allowedTypes.contains(mimeType))
        return true;
    else
        return false;
}
 
Example 5
Source Project: htmlunit   File: WebClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to guess the content type of the file.<br>
 * This utility could be located in a helper class but we can compare this functionality
 * for instance with the "Helper Applications" settings of Mozilla and therefore see it as a
 * property of the "browser".
 * @param file the file
 * @return "application/octet-stream" if nothing could be guessed
 */
public String guessContentType(final File file) {
    final String fileName = file.getName();
    if (fileName.endsWith(".xhtml")) {
        // Java's mime type map returns application/xml in JDK8.
        return MimeType.APPLICATION_XHTML;
    }

    // Java's mime type map does not know these in JDK8.
    if (fileName.endsWith(".js")) {
        return MimeType.APPLICATION_JAVASCRIPT;
    }
    if (fileName.toLowerCase(Locale.ROOT).endsWith(".css")) {
        return MimeType.TEXT_CSS;
    }

    String contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType == null) {
        try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
            contentType = URLConnection.guessContentTypeFromStream(inputStream);
        }
        catch (final IOException e) {
            // Ignore silently.
        }
    }
    if (contentType == null) {
        contentType = MimeType.APPLICATION_OCTET_STREAM;
    }
    return contentType;
}
 
Example 6
Source Project: HtmlUnit-Android   File: WebClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to guess the content type of the file.<br>
 * This utility could be located in a helper class but we can compare this functionality
 * for instance with the "Helper Applications" settings of Mozilla and therefore see it as a
 * property of the "browser".
 * @param file the file
 * @return "application/octet-stream" if nothing could be guessed
 */
public String guessContentType(final File file) {
    final String fileName = file.getName();
    if (fileName.endsWith(".xhtml")) {
        // Java's mime type map returns application/xml in JDK8.
        return "application/xhtml+xml";
    }

    // Java's mime type map does not know these in JDK8.
    if (fileName.endsWith(".js")) {
        return "application/javascript";
    }
    if (fileName.toLowerCase(Locale.ROOT).endsWith(".css")) {
        return "text/css";
    }

    String contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType == null) {
        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
            contentType = URLConnection.guessContentTypeFromStream(inputStream);
        }
        catch (final IOException e) {
            // Ignore silently.
        }
    }
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    return contentType;
}
 
Example 7
@Nullable
@CheckReturnValue
public static String probeContentType(@Nonnull final byte[] bytes) {
    try(final ByteArrayInputStream stream = new ByteArrayInputStream(bytes);) {
        return URLConnection.guessContentTypeFromStream(stream);
    } catch(final IOException e) {
        return null;
    }
}
 
Example 8
/**
 * Determine the mime type for an Android resource.
 * @param context The context manager.
 * @param stream The opened input stream which to examine.
 * @param url The url from which the stream was opened.
 * @return The mime type or null if the type is unknown.
 */
// TODO(bulach): this should have either a throw clause, or
// handle the exception in the java side rather than the native side.
@CalledByNativeUnchecked
public static String getMimeType(Context context, InputStream stream, String url) {
    Uri uri = verifyUrl(url);
    if (uri == null) {
        return null;
    }
    String path = uri.getPath();
    // The content URL type can be queried directly.
    if (uri.getScheme().equals(CONTENT_SCHEME)) {
        return context.getContentResolver().getType(uri);
    // Asset files may have a known extension.
    } else if (uri.getScheme().equals(FILE_SCHEME) &&
               path.startsWith(nativeGetAndroidAssetPath())) {
        String mimeType = URLConnection.guessContentTypeFromName(path);
        if (mimeType != null) {
            return mimeType;
        }
    }
    // Fall back to sniffing the type from the stream.
    try {
        return URLConnection.guessContentTypeFromStream(stream);
    } catch (IOException e) {
        return null;
    }
}
 
Example 9
Source Project: springlets   File: EmbeddableImage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Utility method that obtains the format of the uploaded image using the
 * byte array.
 *
 * @return String with the format of the uploaded image.
 */
public String getFormat() {
  Assert.notNull(this.image, "ERROR: The provided image should have a valid image byte array.");
  try {
    String format =
        URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(this.image));
    if (format != null) {
      return format.replace("image/", "");
    }

  } catch (IOException e) {
    throw new EmbeddableImageException("Error identify image format", e);
  }
  return null;
}
 
Example 10
Source Project: junit-servers   File: Ios.java    License: MIT License 5 votes vote down vote up
private static String tryGuessContentTypeFromStream(Path path) {
	try (InputStream is = new BufferedInputStream(new FileInputStream(path.toFile()))) {
		return URLConnection.guessContentTypeFromStream(is);
	}
	catch (IOException ex) {
		log.warn(ex.getMessage(), ex);
		return null;
	}
}
 
Example 11
public String computePicture(final byte[] pictureData) {
    String pictureContent = new String(pictureData);
    if(pictureContent.toUpperCase().startsWith("HTTP")) {
        return pictureContent;
    }

    try {
        String contentType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(pictureData));
        if(contentType != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("data:");
            sb.append(contentType);
            sb.append(";base64,");
            sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(pictureData, false)));
            return sb.toString();
        } else {
            //null contentType means that pictureData is a String but doesn't starts with HTTP
            LOGGER.warn("Unable to compute the user picture from URL.");
        }

    } catch (IOException e) {
        LOGGER.warn("Problem while parsing picture", e);
    }

    return null;

}
 
Example 12
private String tryGuessContentTypeFromStream(File aFile) {
    try (final InputStream is = new BufferedInputStream(new FileInputStream(aFile))) {
        return URLConnection.guessContentTypeFromStream(is);
    } catch (IOException ex) {
        System.err.println(ex);
        return null;
    }
}
 
Example 13
Source Project: abelana   File: CloudStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Uploads an image to Google Cloud Storage.
 * @param url the upload url.
 * @param bitmap the image to upload.
 * @throws IOException if cannot upload the image.
 */
public static void uploadImage(String url, Bitmap bitmap)
        throws IOException {

    ByteArrayOutputStream bOS = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOS);
    byte[] bitmapData = bOS.toByteArray();

    InputStream stream = new ByteArrayInputStream(bitmapData);
        String contentType = URLConnection
                .guessContentTypeFromStream(stream);
        InputStreamContent content = new InputStreamContent(contentType,
                stream);

    MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");

   OkHttpClient client = new OkHttpClient();

    RequestBody requestBody = RequestBodyUtil.create(MEDIA_TYPE_JPEG,
            content.getInputStream());
    Request request = new Request.Builder()
            .url(url)
            .put(requestBody)
            .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    }
}
 
Example 14
Source Project: java-bot-sdk   File: MessagingApi.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Sending a file to peer
 *
 * @param peer - address peer
 * @param image - java file reference
 * @return UUID - message id
 */
public CompletableFuture<UUID> sendImage(@Nonnull final Peer peer, @Nonnull final File image) {
    if (!image.exists()) {
        new CompletableFuture<>().completeExceptionally(
                new FileNotFoundException("File not found: " + image.getPath()));
    }

    if (!image.isFile()) {
        new CompletableFuture<>().completeExceptionally(
                new FileNotFoundException("Path is not a file: " + image.getPath()));
    }

    String fileName = image.getName();
    int fileSize = (int) image.length();

    try (InputStream is = new BufferedInputStream(new FileInputStream(image))) {
        String mimeType = URLConnection.guessContentTypeFromStream(is);
        Dimension dimension = ImageUtils.getImageDimension(image);

        BufferedImage bufImage = ImageIO.read(image);

        BufferedImage resized = ImageUtils.resize(bufImage, 50, 50);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(resized, "jpg", baos);

        FastThumb fastThumb = FastThumb.newBuilder()
                .setThumb(ByteString.copyFrom(baos.toByteArray()))
                .setH(50)
                .setW(50)
                .build();

        DocumentExPhoto documentExPhoto = DocumentExPhoto.newBuilder()
                .setH(dimension.height)
                .setW(dimension.width)
                .build();

        DocumentEx documentEx = DocumentEx.newBuilder()
                .setPhoto(documentExPhoto)
                .build();

        return mediaAndFilesApi.uploadFile(image)
                .thenCompose(fileLocation -> {
                    DocumentMessage document = DocumentMessage
                            .newBuilder()
                            .setFileId(fileLocation.getFileId())
                            .setAccessHash(fileLocation.getAccessHash())
                            .setFileSize(fileSize)
                            .setName(fileName)
                            .setMimeType(mimeType)
                            .setThumb(fastThumb)
                            .setExt(documentEx)
                            .build();

                    MessageContent msg = MessageContent.newBuilder()
                            .setDocumentMessage(document)
                            .build();

                    return send(peer, msg, null);
                });
    } catch (IOException e) {
        CompletableFuture<UUID> resp = new CompletableFuture<>();
        resp.completeExceptionally(e);
        return resp;
    }
}
 
Example 15
Source Project: syndesis   File: ConnectorIconHandler.java    License: Apache License 2.0 4 votes vote down vote up
@POST
@Operation(description = "Updates the connector icon for the specified connector and returns the updated connector")
@ApiResponse(responseCode = "200", description = "Updated Connector icon")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@SuppressWarnings("PMD.CyclomaticComplexity")
public Connector create(MultipartFormDataInput dataInput) {
    if (dataInput == null || dataInput.getParts() == null || dataInput.getParts().isEmpty()) {
        throw new IllegalArgumentException("Multipart request is empty");
    }

    if (dataInput.getParts().size() != 1) {
        throw new IllegalArgumentException("Wrong number of parts in multipart request");
    }

    try {
        InputPart filePart = dataInput.getParts().iterator().next();
        try (InputStream result = filePart.getBody(InputStream.class, null)) {
            if (result == null) {
                throw new IllegalArgumentException("Can't find a valid 'icon' part in the multipart request");
            }

            try (BufferedInputStream iconStream = new BufferedInputStream(result)) {
                MediaType mediaType = filePart.getMediaType();
                if (!mediaType.getType().equals("image")) {
                    // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
                    // can continue to be used, rather than being consumed.
                    String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
                    if (!guessedMediaType.startsWith("image/")) {
                        throw new IllegalArgumentException("Invalid file contents for an image");
                    }
                    mediaType = MediaType.valueOf(guessedMediaType);
                }

                Icon.Builder iconBuilder = new Icon.Builder()
                                               .mediaType(mediaType.toString());

                Icon icon;
                String connectorIcon = connector.getIcon();
                if (connectorIcon != null && connectorIcon.startsWith("db:")) {
                    String connectorIconId = connectorIcon.substring(3);
                    iconBuilder.id(connectorIconId);
                    icon = iconBuilder.build();
                    getDataManager().update(icon);
                } else {
                    icon = getDataManager().create(iconBuilder.build());
                }
                //write icon to (Sql)FileStore
                iconDao.write(icon.getId().get(), iconStream);

                Connector updatedConnector = new Connector.Builder().createFrom(connector).icon("db:" + icon.getId().get()).build();
                getDataManager().update(updatedConnector);
                return updatedConnector;
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Error while reading multipart request", e);
    }
}
 
Example 16
Source Project: syndesis   File: CustomConnectorHandler.java    License: Apache License 2.0 4 votes vote down vote up
@POST
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Operation(description = "Creates a new Connector based on the ConnectorTemplate identified by the provided `id` and the data given in `connectorSettings` multipart part, plus optional `icon` file")
@ApiResponse(responseCode = "200", description = "Newly created Connector")
public Connector create(@MultipartForm CustomConnectorFormData customConnectorFormData) throws IOException {
    final ConnectorSettings connectorSettings = customConnectorFormData.getConnectorSettings();
    if (connectorSettings == null) {
        throw new IllegalArgumentException("Missing connectorSettings parameter");
    }

    final ConnectorSettings connectorSettingsToUse;
    if (connectorSettings.getConfiguredProperties().containsKey(SPECIFICATION)) {
        connectorSettingsToUse = connectorSettings;
    } else {
        final String specification;
        try (BufferedSource source = Okio.buffer(Okio.source(customConnectorFormData.getSpecification()))) {
            specification = source.readUtf8();
        }

        connectorSettingsToUse = new ConnectorSettings.Builder().createFrom(connectorSettings).putConfiguredProperty(SPECIFICATION, specification).build();
    }

    Connector generatedConnector = withGeneratorAndTemplate(connectorSettingsToUse.getConnectorTemplateId(),
        (generator, template) -> generator.generate(template, connectorSettingsToUse));

    if (customConnectorFormData.getIconInputStream() != null) {
        // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
        // can continue to be used, rather than being consumed.
        try(BufferedInputStream iconStream = new BufferedInputStream(customConnectorFormData.getIconInputStream())) {
            String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
            if (!guessedMediaType.startsWith("image/")) {
                throw new IllegalArgumentException("Invalid file contents for an image");
            }
            MediaType mediaType = MediaType.valueOf(guessedMediaType);
            Icon.Builder iconBuilder = new Icon.Builder()
                .mediaType(mediaType.toString());

            Icon icon = getDataManager().create(iconBuilder.build());
            iconDao.write(icon.getId().get(), iconStream);

            generatedConnector = new Connector.Builder().createFrom(generatedConnector).icon("db:" + icon.getId().get()).build();
        } catch (IOException e) {
            throw new IllegalArgumentException("Error while reading multipart request", e);
        }
    }

    return getDataManager().create(generatedConnector);
}
 
Example 17
@Transactional
public void insertOrUpdateExpenseLine(ActionRequest request, ActionResponse response) {
  try {
    User user = AuthUtils.getUser();
    Map<String, Object> requestData = request.getData();
    Project project =
        Beans.get(ProjectRepository.class)
            .find(Long.valueOf(requestData.get("project").toString()));
    Product product =
        Beans.get(ProductRepository.class)
            .find(Long.valueOf(requestData.get("expenseType").toString()));
    if (user != null) {
      ExpenseService expenseService = Beans.get(ExpenseService.class);
      Expense expense = expenseService.getOrCreateExpense(user);

      ExpenseLine expenseLine;
      Object idO = requestData.get("id");
      if (idO != null) {
        expenseLine = Beans.get(ExpenseLineRepository.class).find(Long.valueOf(idO.toString()));
      } else {
        expenseLine = new ExpenseLine();
      }
      expenseLine.setExpenseDate(
          LocalDate.parse(requestData.get("date").toString(), DateTimeFormatter.ISO_DATE));
      expenseLine.setComments(requestData.get("comments").toString());
      expenseLine.setExpenseProduct(product);
      expenseLine.setProject(project);
      expenseLine.setUser(user);
      expenseLine.setTotalAmount(new BigDecimal(requestData.get("unTaxTotal").toString()));
      expenseLine.setTotalTax(new BigDecimal(requestData.get("taxTotal").toString()));
      expenseLine.setUntaxedAmount(
          expenseLine.getTotalAmount().subtract(expenseLine.getTotalTax()));
      expenseLine.setToInvoice(new Boolean(requestData.get("toInvoice").toString()));
      String justification = (String) requestData.get("justification");

      if (!Strings.isNullOrEmpty(justification)) {
        String MIME_IMAGE_X_ICON = "image/x-icon";
        String MIME_IMAGE_SVG_XML = "image/svg+xml";
        String MIME_IMAGE_BMP = "image/bmp";
        String MIME_IMAGE_GIF = "image/gif";
        String MIME_IMAGE_JPEG = "image/jpeg";
        String MIME_IMAGE_TIFF = "image/tiff";
        String MIME_IMAGE_PNG = "image/png";

        Map<String, String> mimeTypeMapping = new HashMap<>(200);

        mimeTypeMapping.put(MIME_IMAGE_X_ICON, "ico");
        mimeTypeMapping.put(MIME_IMAGE_SVG_XML, "svg");
        mimeTypeMapping.put(MIME_IMAGE_BMP, "bmp");
        mimeTypeMapping.put(MIME_IMAGE_GIF, "gif");
        mimeTypeMapping.put(MIME_IMAGE_JPEG, "jpg");
        mimeTypeMapping.put(MIME_IMAGE_TIFF, "tif");
        mimeTypeMapping.put(MIME_IMAGE_PNG, "png");

        byte[] decodedFile = Base64.getDecoder().decode(justification);
        String formatName =
            URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(decodedFile));
        String extension = "";
        if (mimeTypeMapping.containsKey(formatName)) {
          extension = "." + mimeTypeMapping.get(formatName);
          File file = MetaFiles.createTempFile("justification", extension).toFile();
          Files.write(decodedFile, file);
          MetaFile metaFile = Beans.get(MetaFiles.class).upload(file);
          expenseLine.setJustificationMetaFile(metaFile);
        }
      }
      expense.addGeneralExpenseLineListItem(expenseLine);
      expense = expenseService.compute(expense);

      Beans.get(ExpenseRepository.class).save(expense);
      HashMap<String, Object> data = new HashMap<>();
      data.put("id", expenseLine.getId());
      response.setData(data);
      response.setTotal(1);
    }
  } catch (Exception e) {
    TraceBackService.trace(response, e);
  }
}
 
Example 18
private JSONObject generatePostParameters(String action, String locator, String text, long defaultWait) throws JSONException, IOException, MalformedURLException, MimeTypeException {
        JSONObject result = new JSONObject();
        String picture = "";
        String extension = "";
        /**
         * Get Picture from URL and convert to Base64
         */
        if (locator != null && !"".equals(locator)) {
            URL url = new URL(locator);
            URLConnection connection = url.openConnection();

            InputStream istream = new BufferedInputStream(connection.getInputStream());

            /**
             * Get the MimeType and the extension
             */
            String mimeType = URLConnection.guessContentTypeFromStream(istream);
            MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
            MimeType mt = allTypes.forName(mimeType);
            extension = mt.getExtension();

            /**
             * Encode in Base64
             */
            byte[] bytes = IOUtils.toByteArray(istream);
            picture = Base64.encodeBase64URLSafeString(bytes);
        }
        /**
         * Build JSONObject with parameters action : Action expected to be done
         * by Sikuli picture : Picture in Base64 format text : Text to type
         * defaultWait : Timeout for the action pictureExtension : Extension for
         * Base64 decoding
         */
        result.put("action", action);
        result.put("picture", picture);
        result.put("text", text);
        result.put("defaultWait", defaultWait);
        result.put("pictureExtension", extension);
//        result.put("minSimilarity", parameterService.getParameterStringByKey("cerberus_sikuli_minSimilarity", "", null));
        return result;
    }
 
Example 19
private File	downloadPage( URL url ){
	if ( visitedUrls.contains(url.toString()) )
		return null;
	
	activeHandler = null;
	visitedUrls.add( url.toString() );
	
	File tmpFile = null;
	
	long	startTime = System.currentTimeMillis();
	int size = 0;
	
	try{
		tmpFile = File.createTempFile("OpenBD-CollectionIndexWeb-", ".html");
		
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
		conn.setReadTimeout( 30000 );
		
	   // Connect and read the response
    InputStream in = null;
    String detectedContentType = null;
    try {
      conn.connect();
      
      if (conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
        throw new Exception("Skipping url: " + url + ". It is protected.");
      
      if (conn.getResponseCode() != -1 && conn.getResponseCode() != HttpURLConnection.HTTP_OK)
        throw new Exception("Cannot read page: " + url + " response code is: " + conn.getResponseCode());
      
      in = conn.getInputStream();
      detectedContentType = URLConnection.guessContentTypeFromStream(in);
      size = readData( tmpFile, in );
    } finally {
      if (in != null)
        in.close();
      
      conn.disconnect();
    }

    // Log the fact we made a crawl
    cfEngine.log( "CollectionIndexWeb: Time=" + (System.currentTimeMillis()-startTime) + "; Size=" + size + "; " + url );
    
    // Determine the contentType
    String specifiedContentType = conn.getContentType();
    if (specifiedContentType == null || specifiedContentType.equals(""))
      specifiedContentType = detectedContentType;
    if (specifiedContentType == null || specifiedContentType.equals(""))
      specifiedContentType = "text/plain";

    specifiedContentType = validateMimeType( specifiedContentType ); 
    
    activeHandler	= extHandlers.get( specifiedContentType );
    if ( activeHandler == null ){
    	badUrls.addElement( new cfStringData( url.toString() ) );
    	tmpFile.delete();
    	return null;
    }else
    	return tmpFile;
    
	}catch(Exception e){
		try {
			badUrls.addElement( new cfStringData( url.toString() ) );
		} catch (cfmRunTimeException e1) {}
		
		if ( tmpFile != null ) 
			tmpFile.delete();
		
		return null;
	}
}
 
Example 20
/**
 * Hosts the application's resources on an http(s):// URL. Resources
 * <code>http(s)://{domain}/{virtualResourcesPath}/{resource_type}/{resource_name}</code>.
 *
 * @param domain custom domain on which the assets should be hosted (for example "example.com").
 *               If untrusted content is to be loaded into the WebView it is advised to make
 *               this random.
 * @param virtualResourcesPath the path on the local server under which the resources
 *                             should be hosted.
 * @param enableHttp whether to enable hosting using the http scheme.
 * @param enableHttps whether to enable hosting using the https scheme.
 * @return prefixes under which the resources are hosted.
 */
public AssetHostingDetails hostResources(final String domain,
                                         final String virtualResourcesPath, boolean enableHttp,
                                         boolean enableHttps) {
    if (virtualResourcesPath.indexOf('*') != -1) {
        throw new IllegalArgumentException(
                "virtualResourcesPath cannot contain the '*' character.");
    }

    Uri.Builder uriBuilder = new Uri.Builder();
    uriBuilder.scheme(httpScheme);
    uriBuilder.authority(domain);
    uriBuilder.path(virtualResourcesPath);

    Uri httpPrefix = null;
    Uri httpsPrefix = null;

    PathHandler handler = new PathHandler() {
        @Override
        public InputStream handle(Uri url) {
            InputStream stream  = protocolHandler.openResource(url);
            String mimeType = null;
            try {
                mimeType = URLConnection.guessContentTypeFromStream(stream);
            } catch (Exception ex) {
                Log.e(TAG, "Unable to get mime type" + url);
            }

            return stream;
        }
    };

    if (enableHttp) {
        httpPrefix = uriBuilder.build();
        register(Uri.withAppendedPath(httpPrefix, "**"), handler);
    }
    if (enableHttps) {
        uriBuilder.scheme(httpsScheme);
        httpsPrefix = uriBuilder.build();
        register(Uri.withAppendedPath(httpsPrefix, "**"), handler);
    }
    return new AssetHostingDetails(httpPrefix, httpsPrefix);
}