org.apache.tika.mime.MediaType Java Examples

The following examples show how to use org.apache.tika.mime.MediaType. 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 check out the related API usage on the sidebar.
Example #1
Source File: TikaTest.java    From tika-server with Apache License 2.0 7 votes vote down vote up
@Override
public void handle(String filename, MediaType mediaType,
                   InputStream stream) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    if (! stream.markSupported()) {
        stream = TikaInputStream.get(stream);
    }
    stream.mark(0);
    try {
        IOUtils.copy(stream, os);
        bytes.add(os.toByteArray());
        stream.reset();
    } catch (IOException e) {
        //swallow
    }
}
 
Example #2
Source File: DetectMimeTypeBuilder.java    From kite with Apache License 2.0 7 votes vote down vote up
/**
 * Detects the content type of the given input event. Returns
 * <code>application/octet-stream</code> if the type of the event can not be
 * detected.
 * <p>
 * It is legal for the event headers or body to be empty. The detector may
 * read bytes from the start of the body stream to help in type detection.
 * 
 * @return detected media type, or <code>application/octet-stream</code>
 */
private String getMediaType(InputStream in, Metadata metadata, boolean excludeParameters) {
  MediaType mediaType;
  try {
    mediaType = getDetector().detect(in, metadata);
  } catch (IOException e) {
    throw new MorphlineRuntimeException(e);
  }
  String mediaTypeStr = mediaType.toString();
  if (excludeParameters) {
    int i = mediaTypeStr.indexOf(';');
    if (i >= 0) {
      mediaTypeStr = mediaTypeStr.substring(0, i);
    }
  }
  return mediaTypeStr;
}
 
Example #3
Source File: PdfConvertor.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public void convert(MediaType mediaType, File file, CisConversionResult result, ConversionOption conversionOption)
		throws Exception {

	if (!MEDIA_TYPE_LOAD_FORMAT_MAPPING.containsKey(mediaType)) {
		// mediaType should always be supported otherwise there a program error because
		// the supported media types should be part of the map
		throw new IllegalArgumentException("Unsupported mediaType " + mediaType + " should never happen here!");
	}
	try (InputStream inputStream = new FileInputStream(file)) {
		Document doc = new Document(inputStream, MEDIA_TYPE_LOAD_FORMAT_MAPPING.get(mediaType));
		doc.save(result.getPdfResultFile().getAbsolutePath(), SaveFormat.Pdf);
		doc.freeMemory();
		doc.dispose();
		doc.close();
	}
	result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile()));
}
 
Example #4
Source File: TikaAutoMetadataExtracter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static ArrayList<String> buildMimeTypes(TikaConfig tikaConfig)
{
   config = tikaConfig;
   parser = new AutoDetectParser(config);

   SUPPORTED_MIMETYPES = new ArrayList<String>();
   for(MediaType mt : parser.getParsers().keySet()) 
   {
      // Add the canonical mime type
      SUPPORTED_MIMETYPES.add( mt.toString() );
      
      // And add any aliases of the mime type too - Alfresco uses some
      //  non canonical forms of various mimetypes, so we need all of them
      for(MediaType alias : config.getMediaTypeRegistry().getAliases(mt)) 
      {
          SUPPORTED_MIMETYPES.add( alias.toString() );
      }
   }
   return SUPPORTED_MIMETYPES;
}
 
Example #5
Source File: ContentExtractor.java    From jate with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String extractContent(File file) throws JATEException {
	String content = "";
	if (file == null || !file.exists()) {
		throw new JATEException("File is not found!");
	}

	try {
		String contentType = Files.probeContentType(file.toPath());

		if (MediaType.TEXT_PLAIN.getBaseType().toString().equals(contentType)) {
			content = parseTXTToString(file);
		} else {
			content = tika.parseToString(file);
		}
	} catch (IOException e1) {
		throw new JATEException("I/O exception when detecting file type.");
	} catch (TikaException tikaEx) {
		throw new JATEException("Tika Content extraction exception: " + tikaEx.toString());
	}

	return content;
}
 
Example #6
Source File: CisConversionResult.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * CreateCisConversionResult
 * 
 * @param conversionOption
 * @param mediaType
 * @param documentName
 * @param pdfResultFile
 * @param failureReason
 * @param argAttachments
 * @return
 */
public static CisConversionResult createCisConversionResult(ConversionOption conversionOption, MediaType mediaType,
		String documentName, File pdfResultFile, String failureReason, List<CisConversionResult> argAttachments) {

	CisConversionResult cisConversionResult = new CisConversionResult();
	cisConversionResult.setConversionOption(conversionOption);
	cisConversionResult.setMediaType(mediaType);
	cisConversionResult.setDocumentName(documentName);
	cisConversionResult.setPdfResultFile(pdfResultFile);
	cisConversionResult.setFailureReason(failureReason);
	if (argAttachments != null) {
		for (CisConversionResult attachment : argAttachments) {
			cisConversionResult.addAttachment(attachment);
		}
	}

	return cisConversionResult;
}
 
Example #7
Source File: DefaultMimeSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Nonnull
@Override
public List<String> detectMimeTypes(final InputStream input, @Nullable final String fileName) throws IOException {
  checkNotNull(input);

  List<String> detected = Lists.newArrayList();
  Metadata metadata = new Metadata();
  if (fileName != null) {
    metadata.set(Metadata.RESOURCE_NAME_KEY, fileName);
  }

  MediaType mediaType;
  try (final TikaInputStream tis = TikaInputStream.get(input)) {
    mediaType = detector.detect(tis, metadata);
  }

  // unravel to least specific
  unravel(detected, mediaType);

  if (detected.isEmpty()) {
    detected.add(MimeTypes.OCTET_STREAM);
  }

  return detected;
}
 
Example #8
Source File: SlidesConvertor.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public void convert(MediaType mediaType, File file, CisConversionResult result, ConversionOption conversionOption)
		throws Exception {

	if (!MEDIA_TYPE_LOAD_FORMAT_MAPPING.containsKey(mediaType)) {
		// mediaType should always be supported otherwise there a program error because
		// the supported media types should be part of the map
		throw new IllegalArgumentException("Unsupported mediaType " + mediaType + " should never happen here!");
	}
	try (FileInputStream inputStream = new FileInputStream(file)) {
		Presentation presentation = new Presentation(inputStream, MEDIA_TYPE_LOAD_FORMAT_MAPPING.get(mediaType));
		long startTime = new Date().getTime();
		presentation.save(result.getPdfResultFile().getAbsolutePath(), SaveFormat.Pdf);
		long endTime = new Date().getTime();
		
		LOGGER.info("Conversion(save operation in convert method) takes  :::  " + (endTime - startTime) + " ms");
		
		presentation.dispose();
		result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile()));
	}
}
 
Example #9
Source File: TikaUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public static String getMediaTypeDescriptionOrNullSafe(MediaType mediaType, MimeTypes mimeTypes) {
    MimeType mimeType = getMimeTypeForMediaTypeSafe(mediaType, mimeTypes, true);
    String description = null;

    if (mimeType != null) {
        description = mimeType.getDescription();
    } else {
        // when this prints, it's because of imperfections in tika-mimetypes.xml...
        Debug.logWarning("No Tika mime-type for MediaType: " + mediaType.toString(), module);
    }
    if (UtilValidate.isNotEmpty(description)) {
        return description;
    } else {
        MediaTypeRegistry registry = mimeTypes.getMediaTypeRegistry();

        // check if can find one in supertype
        MediaType superType = registry.getSupertype(mediaType);
        if (superType != null) {
            description = getMediaTypeDescriptionOrNullSafe(superType, mimeTypes);
            if (UtilValidate.isNotEmpty(description)) {
                return description + " (sub-type)";
            }
        }
    }
    return null;
}
 
Example #10
Source File: TikaUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * WARN: the registry.getAliases method does not work reliably. This method instead tries to work around
 * it so any alias can be passed, not just the canonical form...
 * TODO: REVIEW: this may not work right for media types with parameters...
 */
public static Set<MediaType> getMediaTypeAliases(MediaType mediaType, MediaTypeRegistry registry) {
    if (mediaType == null) {
        return Collections.<MediaType> emptySet();
    }
    MediaType normType = registry.normalize(mediaType);
    Set<MediaType> aliases = registry.getAliases(normType);
    if (aliases == null) {
        return Collections.<MediaType> emptySet();
    }
    if (normType.equals(mediaType)) {
        return aliases;
    } else {
        Set<MediaType> al = new TreeSet<>(aliases);
        al.remove(mediaType);
        al.add(normType);
        return al;
    }
}
 
Example #11
Source File: WordConvertor.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public void convert(MediaType mediaType, File file, CisConversionResult result, ConversionOption conversionOption)
		throws Exception {

	if (!MEDIA_TYPE_LOAD_FORMAT_MAPPING.containsKey(mediaType)) {
		// mediaType should always be supported otherwise there a program error because
		// the supported media types should be part of the map
		throw new IllegalArgumentException("Unsupported mediaType " + mediaType + " should never happen here!");
	}

	try (FileInputStream inputStream = new FileInputStream(file)) {
		Document doc = new Document(inputStream, MEDIA_TYPE_LOAD_FORMAT_MAPPING.get(mediaType));
		new Fontsetter(cisConversionService.getFontsDirectory()).setFontSettings(doc);
		SaveOptions saveOptions = SaveOptions.createSaveOptions(SaveFormat.PDF);
		saveOptions.setMemoryOptimization(true);
		
		long startTime = new Date().getTime();
		doc.save(result.getPdfResultFile().getAbsolutePath(), saveOptions);
		long endTime = new Date().getTime();
		LOGGER.debug(
				"Conversion(save operation in convert method) takes  :::  " + (endTime - startTime) + " ms");
		result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile()));
	}
}
 
Example #12
Source File: FileTypeResolver.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Finds MimeType (through Apache Tika library), as string representation, based on filename and magic numbers.
 */
protected GenericValue findMimeTypeLib(ByteBuffer byteBuffer, String fileName) throws GeneralException {
    MediaType mediaType = TikaUtil.findMediaTypeSafe(byteBuffer, fileName);

    if (mediaType != null) {
        String mimeTypeId = TikaUtil.getMimeTypeId(mediaType);
        // SPECIAL: here we assume Tika identified the file correctly.
        // so if it maps to a non-allowed type, we must throw error, NOT return null.
        if (!isAllowedMediaType(mimeTypeId)) {
            throw new FileTypeException(PropertyMessage.make("CommonErrorUiLabels", "CommonInvalidFileTypeForMediaCat",
                    UtilMisc.toMap("mediaType", mimeTypeId, "providedType", getProvidedType())));
        }
    }

    // check if we have an exact match in system
    // NOTE: is possible there is no exact match in the system (though should try to minimize this)
    return TikaUtil.findEntityMimeTypeForMediaType(delegator, mediaType, true);
}
 
Example #13
Source File: WebServerServiceRestImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateAndDeployConfigBinaryFile() throws CommandFailureException, IOException {
    when(Config.mockWebServerService.getResourceTemplateMetaData(anyString(), anyString())).thenReturn("{\"contentType\":\"application/binary\",\"deployPath\":\"./anyPath\"}");
    when(Config.mockResourceService.generateResourceGroup()).thenReturn(new ResourceGroup());
    CommandOutput commandOutput = mock(CommandOutput.class);
    ExecReturnCode execReturnCode = mock(ExecReturnCode.class);
    when(commandOutput.getReturnCode()).thenReturn(execReturnCode);
    when(commandOutput.getReturnCode().wasSuccessful()).thenReturn(true);
    when(Config.mockResourceService.generateResourceFile(anyString(), anyString(), any(ResourceGroup.class), any(), any(ResourceGeneratorType.class))).thenReturn("{\"contentType\":\"application/binary\",\"deployPath\":\"./anyPath\"}");
    ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class);
    when(mockMetaData.getDeployFileName()).thenReturn("httpd.conf");
    when(mockMetaData.getDeployPath()).thenReturn("./anyPath");
    when(mockMetaData.getContentType()).thenReturn(MediaType.TEXT_PLAIN);
    when(Config.mockResourceService.getTokenizedMetaData(anyString(), Matchers.anyObject(), anyString())).thenReturn(mockMetaData);
    Response response = webServerServiceRest.generateAndDeployConfig(webServer.getName(), "httpd.exe", Config.mockAuthenticatedUser);
    assertTrue(response.hasEntity());
}
 
Example #14
Source File: TesseractOCRParser.java    From CogStack-Pipeline with Apache License 2.0 5 votes vote down vote up
@Override
public Set<MediaType> getSupportedTypes(ParseContext context) {
    // If Tesseract is installed, offer our supported image types
    TesseractOCRConfig config = context.get(TesseractOCRConfig.class, DEFAULT_CONFIG);
    if (hasTesseract(config))
        return SUPPORTED_TYPES;

    // Otherwise don't advertise anything, so the other image parsers
    //  can be selected instead
    return Collections.emptySet();
}
 
Example #15
Source File: DirectoryScanner.java    From importer-exporter with Apache License 2.0 5 votes vote down vote up
private MediaType getMediaType(Path file) {
    try (InputStream stream = TikaInputStream.get(file)) {
        Metadata metadata = new Metadata();
        metadata.set(Metadata.RESOURCE_NAME_KEY, file.toString());
        return tikaConfig.getDetector().detect(stream, metadata);
    } catch (IOException e) {
        return MediaType.EMPTY;
    }
}
 
Example #16
Source File: PDFPreprocessorParser.java    From CogStack-Pipeline with Apache License 2.0 5 votes vote down vote up
@Override
public Set<MediaType> getSupportedTypes(ParseContext context) {
    // If ImageMagick is installed, offer our supported image types
    ImageMagickConfig imconfig = context.get(ImageMagickConfig.class, DEFAULT_IMAGEMAGICK_CONFIG);
    if (hasImageMagick(imconfig)) {
        return SUPPORTED_TYPES;
    }

    // Otherwise don't advertise anything, so the other parsers
    //  can be selected instead
    return Collections.emptySet();
}
 
Example #17
Source File: MimeTypeUtils.java    From oodt with Apache License 2.0 5 votes vote down vote up
public String getSuperTypeForMimeType(String mimeType) {
	try {
		MediaType mediaType = this.mimeTypes.getMediaTypeRegistry().getSupertype(this.mimeTypes.forName(mimeType).getType());
		if (mediaType != null) {
            return mediaType.getType() + "/" + mediaType.getSubtype();
        } else {
            return null;
        }
	}catch (Exception e) {
		LOG.log(Level.WARNING, "Failed to get super-type for mimetype " 
				+ mimeType + " : " + e.getMessage());
		return null;
	}
}
 
Example #18
Source File: ResourceServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
/**
 * Create the application template in the db and in the templates path for all the application.
 *
 * @param metaData        the data that describes the template, please see {@link ResourceTemplateMetaData}
 * @param templateContent the template content/data
 * @param targetAppName   the application name
 */
@Deprecated
private CreateResourceResponseWrapper createGroupedApplicationsTemplate(final ResourceTemplateMetaData metaData,
                                                                        final String templateContent,
                                                                        final String targetAppName) throws IOException {
    final String groupName = metaData.getEntity().getGroup();
    Group group = groupPersistenceService.getGroup(groupName);
    final List<Application> applications = applicationPersistenceService.findApplicationsBelongingTo(groupName);
    ConfigTemplate createdConfigTemplate = null;

    if (MediaType.APPLICATION_ZIP.equals(metaData.getContentType()) &&
            metaData.getDeployFileName().toLowerCase(Locale.US).endsWith(WAR_FILE_EXTENSION)) {
        String tokenizedWarDeployPath = resourceContentGeneratorService.generateContent(
                metaData.getDeployFileName(),
                metaData.getDeployPath(),
                null,
                applicationPersistenceService.getApplication(targetAppName),
                ResourceGeneratorType.METADATA);
        applicationPersistenceService.updateWarInfo(targetAppName, metaData.getDeployFileName(), templateContent, tokenizedWarDeployPath);
    }
    final String deployFileName = metaData.getDeployFileName();

    for (final Application application : applications) {
        if (metaData.getEntity().getDeployToJvms() && application.getName().equals(targetAppName)) {
            for (final Jvm jvm : group.getJvms()) {
                UploadAppTemplateRequest uploadAppTemplateRequest = new UploadAppTemplateRequest(application, metaData.getTemplateName(),
                        deployFileName, jvm.getJvmName(), metaData.getJsonData(), templateContent
                );
                JpaJvm jpaJvm = jvmPersistenceService.getJpaJvm(jvm.getId(), false);
                applicationPersistenceService.uploadAppTemplate(uploadAppTemplateRequest, jpaJvm);
            }
        }
    }

    createdConfigTemplate = groupPersistenceService.populateGroupAppTemplate(groupName, targetAppName, deployFileName,
            metaData.getJsonData(), templateContent);

    return new CreateResourceResponseWrapper(createdConfigTemplate);
}
 
Example #19
Source File: TikaUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static Set<String> getMediaTypeAliasMimeTypeIds(MediaType mediaType) {
    Set<String> ids = new LinkedHashSet<>();
    for(MediaType alias : getMediaTypeAliases(mediaType)) {
        ids.add(getMimeTypeId(alias));
    }
    return ids;
}
 
Example #20
Source File: TikaUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Makes a normalized tika MediaType instance (normalized means alias translated to the main recognized name).
 * Result NOT necessarily exists in the registry.
 */
public static MediaType asNormMediaType(String mediaType) {
    return getMediaTypeRegistry().normalize(MediaType.parse(mediaType));
    // this code returned null for aliases.
    //MimeType mimeType = getMimeTypeForMediaTypeSafe(mediaType, getMimeTypeRegistry(), exact);
    //return mimeType != null ? mimeType.getType() : null;
}
 
Example #21
Source File: ResourceServiceImplTest.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateResource() {
    final ResourceIdentifier resourceIdentifier = mock(ResourceIdentifier.class);
    final ResourceTemplateMetaData resourceTemplateMetaData = mock(ResourceTemplateMetaData.class);
    when(resourceTemplateMetaData.getContentType()).thenReturn(MediaType.TEXT_PLAIN);
    final InputStream inputStream = mock(InputStream.class);
    CreateResourceResponseWrapper createResourceResponseWrapper = mock(CreateResourceResponseWrapper.class);
    when(Config.mockResourceHandler.createResource(eq(resourceIdentifier), eq(resourceTemplateMetaData), anyString())).thenReturn(createResourceResponseWrapper);
    assertEquals(createResourceResponseWrapper, resourceService.createResource(resourceIdentifier, resourceTemplateMetaData, inputStream));
}
 
Example #22
Source File: PreviewHelper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private static Map<MediaType, String> makeVideoMediaTypeGeneralizationsMap() {
    Map<MediaType, String> map = new HashMap<>();

    map.put(TikaUtil.asNormMediaType("video/webm"), "video/webm");
    map.put(TikaUtil.asNormMediaType("video/ogg"), "video/ogg");
    map.put(TikaUtil.asNormMediaType("video/mpeg"), "video/mpeg");

    return map;
}
 
Example #23
Source File: FileParser.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isSupported(MediaType mediaType)
{
	if(mediaType==null)
		return false;
	if(supportedFiles.containsKey(mediaTypeString(mediaType)))
		return true;
	return false;
}
 
Example #24
Source File: MediatTypeToStrSerializer.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(MediaType value, org.codehaus.jackson.JsonGenerator jgen, org.codehaus.jackson.map.SerializerProvider provider) throws IOException, JsonProcessingException {
    if (null == value) {
        jgen.writeString("");
    } else {
        jgen.writeString(value.toString());
    }
}
 
Example #25
Source File: GroupLevelAppResourceHandler.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
public CreateResourceResponseWrapper
createResource(final ResourceIdentifier resourceIdentifier,
               final ResourceTemplateMetaData metaData,
               final String templateContent) {
    ResourceTemplateMetaData metaDataCopy = metaData;
    CreateResourceResponseWrapper createResourceResponseWrapper = null;
    if (canHandle(resourceIdentifier)) {
        final String groupName = resourceIdentifier.groupName;
        final Group group = groupPersistenceService.getGroup(groupName);
        final ConfigTemplate createdConfigTemplate;

        if (metaDataCopy.getContentType().equals(MediaType.APPLICATION_ZIP) &&
                templateContent.toLowerCase(Locale.US).endsWith(WAR_FILE_EXTENSION)) {
            final Application app = applicationPersistenceService.getApplication(resourceIdentifier.webAppName);
            if (StringUtils.isEmpty(app.getWarName())) {
                applicationPersistenceService.updateWarInfo(resourceIdentifier.webAppName, metaDataCopy.getDeployFileName(), templateContent, getTokenizedDeployPath(metaDataCopy, app));
                metaDataCopy = updateApplicationWarMetaData(resourceIdentifier, metaDataCopy, app);
            } else {
                throw new ResourceServiceException(MSG_CAN_ONLY_HAVE_ONE_WAR);
            }
        }

        createdConfigTemplate = groupPersistenceService.populateGroupAppTemplate(groupName, resourceIdentifier.webAppName,
                metaDataCopy.getDeployFileName(), metaDataCopy.getJsonData(), templateContent);

        createJvmTemplateFromAppResource(resourceIdentifier, templateContent, metaDataCopy, group);

        createResourceResponseWrapper = new CreateResourceResponseWrapper(createdConfigTemplate);
    } else if (successor != null) {
        createResourceResponseWrapper = successor.createResource(resourceIdentifier, metaDataCopy, templateContent);
    }
    return createResourceResponseWrapper;
}
 
Example #26
Source File: JvmServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
private Map<String, ScpDestination> generateResourceFiles(final String jvmName) throws IOException {
	Map<String, ScpDestination> generatedFiles = new HashMap<>();
	final List<JpaJvmConfigTemplate> jpaJvmConfigTemplateList = jvmPersistenceService.getConfigTemplates(jvmName);
	for (final JpaJvmConfigTemplate jpaJvmConfigTemplate : jpaJvmConfigTemplateList) {
		final ResourceGroup resourceGroup = resourceService.generateResourceGroup();
		final Jvm jvm = jvmPersistenceService.findJvmByExactName(jvmName);
		String resourceTemplateMetaDataString = "";
		resourceTemplateMetaDataString = resourceService.generateResourceFile(
				jpaJvmConfigTemplate.getTemplateName(), jpaJvmConfigTemplate.getMetaData(), resourceGroup, jvm,
				ResourceGeneratorType.METADATA);
		final ResourceTemplateMetaData resourceTemplateMetaData = resourceService
				.getMetaData(resourceTemplateMetaDataString);
		final String deployFileName = resourceTemplateMetaData.getDeployFileName();
		if (resourceTemplateMetaData.getContentType().getType().equalsIgnoreCase(MEDIA_TYPE_TEXT)
				|| MediaType.APPLICATION_XML.equals(resourceTemplateMetaData.getContentType())) {
			final String generatedResourceStr = resourceService.generateResourceFile(
					jpaJvmConfigTemplate.getTemplateName(), jpaJvmConfigTemplate.getTemplateContent(),
					resourceGroup, jvm, ResourceGeneratorType.TEMPLATE);
			generatedFiles.put(
					createConfigFile(
							ApplicationProperties.get(PropertyKeys.PATHS_GENERATED_RESOURCE_DIR) + '/' + jvmName,
							deployFileName, generatedResourceStr),
					new ScpDestination(resourceTemplateMetaData.getDeployPath() + '/' + deployFileName,
							resourceTemplateMetaData.isOverwrite()));
		} else {
			generatedFiles.put(jpaJvmConfigTemplate.getTemplateContent(),
					new ScpDestination(resourceTemplateMetaData.getDeployPath() + '/' + deployFileName,
							resourceTemplateMetaData.isOverwrite()));
		}
	}
	return generatedFiles;
}
 
Example #27
Source File: WebServerServiceRestImplTest.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateAndDeployWebServerDeleteServiceForNonexistentService() throws CommandFailureException, IOException {
    List<String> webServerResourceNames = new ArrayList<>();
    webServerResourceNames.add("httpd.conf");

    CommandOutput retSuccessExecData = new CommandOutput(new ExecReturnCode(0), "", "");
    when(Config.mockWebServerControlService.controlWebServer(any(ControlWebServerRequest.class), any(User.class))).thenReturn(retSuccessExecData);

    when(Config.mockWebServerService.getWebServer(anyString())).thenReturn(webServer);
    when(Config.mockWebServerService.generateInstallServiceScript(any(WebServer.class))).thenReturn("invoke me");
    when(Config.mockWebServerService.getResourceTemplateMetaData(anyString(), anyString())).thenReturn("{\"contentType\":\"text/plain\",\"deployPath\":\"./anyPath\",\"deployFileName\":\"httpd.conf\"}");
    when(Config.mockWebServerService.getResourceTemplateNames(anyString())).thenReturn(webServerResourceNames);
    when(Config.mockWebServerService.isStarted(eq(webServer))).thenReturn(false);

    ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class);
    when(mockMetaData.getDeployFileName()).thenReturn("httpd.conf");
    when(mockMetaData.getDeployPath()).thenReturn("./anyPath");
    when(mockMetaData.getContentType()).thenReturn(MediaType.TEXT_PLAIN);

    when(Config.mockResourceService.generateResourceGroup()).thenReturn(new ResourceGroup());
    when(Config.mockResourceService.generateResourceFile(anyString(), anyString(), any(ResourceGroup.class), any(), any(ResourceGeneratorType.class))).thenReturn("{\"contentType\":\"text/plain\",\"deployPath\":\"./anyPath\",\"deployFileName\":\"httpd.conf\"}");
    when(Config.mockResourceService.getTokenizedMetaData(anyString(), Matchers.anyObject(), anyString())).thenReturn(mockMetaData);

    Response response = webServerServiceRest.generateAndDeployWebServer(webServer.getName(), Config.mockAuthenticatedUser);
    assertNotNull(response);

    verify(Config.mockSimpleMessageService).send(any(WebServerState.class));

}
 
Example #28
Source File: CisConversionResult.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static CisConversionResult createPasswordFailureResult(String filename, ConversionOption conversionOption,
		MediaType mediaTypeReceived) {
	StringBuilder msg = new StringBuilder();
	if (filename != null) {
		msg.append(filename);
	}
	msg.append(" " + PASSWORD_MESSAGE);
	return createFailureResult(conversionOption, mediaTypeReceived, filename, msg.toString(), null);
}
 
Example #29
Source File: TikaUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static MediaType findMediaTypeSafe(InputStream is, String fileName) {
    try {
        return findMediaType(is, fileName);
    } catch (IOException e) {
        return null;
    }
}
 
Example #30
Source File: TikaExtractorTest.java    From ache with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetectMimeType() {
    // given
    String filename = "http%3A%2F%2Fwww.darpa.mil%2Fprogram%2Fmemex";
    InputStream fileStream = CDRDocumentBuilderTest.class.getResourceAsStream(filename);
    
    TikaExtractor parser = new TikaExtractor();

    // when
    MediaType type = parser.detect(fileStream, filename, null);
    
    // then
    assertThat(type.getBaseType(), is(MediaType.TEXT_HTML));
    assertThat(type.getBaseType().toString(), is("text/html"));
}