Package eu.planets_project.services.utils

Examples of eu.planets_project.services.utils.ServicePerformanceHelper


    /**
     * @see eu.planets_project.services.identify.Identify#identify(eu.planets_project.services.datatypes.DigitalObject)
     */
    public IdentifyResult identify(DigitalObject dob, List<Parameter> parameters ) {
        // Start timing...
        ServicePerformanceHelper sph = new ServicePerformanceHelper();
       
        // Initialise the result:
        ImageReader imageReader = null;

        // Can only cope if the object is 'simple':
        if (dob.getContent() == null) {
            return returnWithErrorMessage(ServiceUtils
                    .createErrorReport("The Content of the DigitalObject should not be NULL."));
        }
        // If this is an embedded binary:
        try {
            imageReader = getFormatName(dob.getContent().getInputStream());
            // Record time take to load the input into memory:
            sph.loaded();

            if (imageReader == null || imageReader.getFormatName() == null)
                return returnWithErrorMessage(ServiceUtils.createErrorReport("Could not identify the image."));
           
            List<URI> types = new ArrayList<URI>();
            URI typeURI = FormatRegistryFactory.getFormatRegistry().createExtensionUri(sanitize(imageReader.getFormatName()));
            types.add(typeURI);
            log.fine(String.format("Identified %s as %s", dob, types));
           
            ServiceReport rep = new ServiceReport(Type.INFO, Status.SUCCESS, "OK", sph.getPerformanceProperties() );
            return new IdentifyResult(types,
                    IdentifyResult.Method.PARTIAL_PARSE, rep);
        } catch (IOException e) {
            return returnWithErrorMessage(ServiceUtils.createErrorReport("IOException reading the image: " + e));
        }
View Full Code Here


     * @see eu.planets_project.services.migrate.Migrate#migrate(eu.planets_project.services.datatypes.DigitalObject, java.net.URI, java.net.URI, eu.planets_project.services.datatypes.Parameter)
     */
    public MigrateResult migrate(DigitalObject dob, URI inputFormat,
            URI outputFormat, List<Parameter> parameters) {
        // Start timing...
        ServicePerformanceHelper sph = new ServicePerformanceHelper();
       
        BufferedImage image = null;

        // There must be content:
        if( dob.getContent() == null ) {
            return this.returnWithErrorMessage("The Content of the DigitalObject should not be NULL.", null);
        }
        // Both by-reference and by-value can be read as input streams:
        try {
            image = ImageIO.read( dob.getContent().getInputStream() );
        } catch ( Exception e) {
            return returnWithErrorMessage("Exception reading the image - unsupported or invalid input? ", e);
        }
        // Record time take to load the input into memory:
        sph.loaded();
       
        // If that failed, then report an error.
        if( image == null ) {
            return returnWithErrorMessage("Failed to read the image - unsupported or invalid input? ", null);
        }

        // Pick up the output format:
        //Format format = new Format(outputFormat);
        Set<String> extensionsForURI = format.getExtensions(outputFormat);
        if(extensionsForURI.isEmpty() ) {
            return this.returnWithErrorMessage("Unsupported output format: "+outputFormat,null);
        } else {
            log.info("Outputing image to format: "+format.getExtensions(outputFormat).iterator().next());
        }
       
        String extension = extensionsForURI.iterator().next();
        File outfile = null;
        try {
            outfile = File.createTempFile("imageio", extension);

            // FIXME If writing an RBGA image, this simple write method can accidentally convert to CMYK for JPEG, as that is the only way to represent four channels.
            /*
            ImageWriter iw = ImageIO.getImageWritersByFormatName(extension).next();
            ImageTypeSpecifier its =  iw.getDefaultWriteParam().getDestinationType();
            its.getColorModel().hasAlpha();
            its.getColorModel().getNumComponents();
            // Compare with...
            image.getColorModel().hasAlpha();
            // Write:
            iw.setOutput(new FileImageOutputStream(outfile));
            ImageWriteParam iwp = iw.getDefaultWriteParam();
            iwp.setDestinationType(its);
            iw.write(null, new IIOImage(image, null, null), iwp);
            */
           
            // Write using the simple approach:
            ImageIO.write(image, extension, outfile );
        } catch ( Exception e) {
            return this.returnWithErrorMessage("Could not create image in the new format. ",e);
        }

        //try to build digital object with content by reference
        /*
        try {                   
            WebContentHelper webHandler = new WebContentHelper();
          URL contentUrl = webHandler.copyIntoHTMLDirectory(outfile);
          log.info("got content URL: "+contentUrl);
         
            ServiceReport rep = new ServiceReport(Type.INFO, Status.SUCCESS, "OK");
          DigitalObject ndo = new DigitalObject.Builder(Content.byReference(contentUrl)).build();
            return new MigrateResult(ndo, rep);
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not return content by reference. ", e);
        }
        */
        ServiceReport rep = new ServiceReport(Type.INFO, Status.SUCCESS, "OK", sph.getPerformanceProperties() );
        DigitalObject ndo = new DigitalObject.Builder(Content.byReference(outfile)).build();
        return new MigrateResult(ndo, rep);
    }
View Full Code Here

     * @see eu.planets_project.services.compare.Compare#compare(eu.planets_project.services.datatypes.DigitalObject, eu.planets_project.services.datatypes.DigitalObject, java.util.List)
     */
    public CompareResult compare(DigitalObject first, DigitalObject second,
            List<Parameter> config) {
        // Start timing...
        ServicePerformanceHelper sph = new ServicePerformanceHelper();
       
        // Initialise what will be built:
        List<PropertyComparison> props = new ArrayList<PropertyComparison>();
        ServiceReport sr = null;
       
        // Load the images.
        BufferedImage i1;
        BufferedImage i2;
        try {
            i1 = ImageIO.read( first.getContent().getInputStream() );
            i2 = ImageIO.read( second.getContent().getInputStream() );
        } catch (IOException e) {
            return new CompareResult(null, ServiceUtils.createExceptionErrorReport("IOException reading the images. ", e));
        }
        if( i1 == null || i2 == null ) {
            log.warning("One of the images was null when loaded!");
            return new CompareResult(null, ServiceUtils.createErrorReport("Error reading the images, got a NULL."));
        }
        // Record time take to load the inputs into memory:
        sph.loaded();
       
        // Check comparison is possible: Are the dimensions the same?
        if (i1.getWidth() != i2.getWidth() || i1.getHeight() != i2.getHeight()) {
            // FIXME is this really an error, or rather a 'images are different' result?
            return new CompareResult(null, ServiceUtils.createErrorReport("The image dimensions must match!"));
        }
        // FIXME Check comparison is sensible: are there the same number of channels? This is probably a WARNING?
        if( i1.getColorModel().getNumComponents() != i2.getColorModel().getNumComponents()) {
            System.out.println("The number of colour components does not match. "+i1.getColorModel().getNumComponents()+" != "+i2.getColorModel().getNumComponents());
            log.warning("The number of colour components does not match. "+i1.getColorModel().getNumComponents()+" != "+i2.getColorModel().getNumComponents());
            sr = new ServiceReport(ServiceReport.Type.WARN, ServiceReport.Status.SUCCESS, "Number of colour components was not the same. The missing channels, e.g. the alpha channel, will be assumed to be zero.");
            // FIXME I think this should be more serious, as the results can be rather misleading.
            // The comparison assumes the bit-mask to be zero everywhere, but this did not lead to such a bad PSNR?!
        }

        // Run the comparison:
        double psnr = psnr(i1, i2);
        props.add( buildPsnrProperty(psnr) );
       
        // Create a happy service report if no problems occurred.
        if( sr == null) {
            // Also store some service properties:
            sr = new ServiceReport(ServiceReport.Type.INFO, ServiceReport.Status.SUCCESS,
                    "Comparison succeeded.", sph.getPerformanceProperties() );
        }
       
        // Halt performance measurement:
        sph.stop();

        // Return the result:
        return new CompareResult( props, sr );
    }
View Full Code Here

    @SuppressWarnings("unchecked")
    public MigrateResult migrate(DigitalObject dob, URI inputFormat,
            URI outputFormat, List<Parameter> parameters) {
       
      // Start timing...
        ServicePerformanceHelper sph = new ServicePerformanceHelper();
       
        BufferedImage image = null;
       
        // Can only cope if the object is 'simple':
        if( dob.getContent() == null ) {
            return this.returnWithErrorMessage("The Content of the DigitalObject should not be NULL.", null);
        }
        // Both by-reference and by-value can be read as input streams:
        try {
            image = Sanselan.getBufferedImage(dob.getContent().getInputStream());
        } catch (ImageReadException e) {
            return returnWithErrorMessage("Could not read the image. ", e);
        } catch (IOException e) {
            return returnWithErrorMessage("IOException reading the image. ", e);
        }
       
        // Record time take to load the input into memory:
        sph.loaded();

        // Pick up the output format:
        ImageFormat format = null;
        for( ImageFormat f : ImageFormat.getAllFormats() ) {
            if (FormatRegistryFactory.getFormatRegistry().createExtensionUri(
                    f.extension).equals(outputFormat))
                format = f;
        }
        if( format == null ) {
            return this.returnWithErrorMessage("Unsupported output format: "+outputFormat,null);
        } else {
            log.info("Outputing image to format: "+format.toString());
        }
       
        Map params = new HashMap();

        if(parameters!=null) {
            // set optional parameters if you like
            for( Parameter p : parameters ) {
                if( p.getName().equals( parmap.get(SanselanConstants.PARAM_KEY_COMPRESSION )) ) {
                    if( p.getValue().equalsIgnoreCase(TIFF_UNCOMPRESSED)) {
                        params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_UNCOMPRESSED);
                    }
                    if( p.getValue().equalsIgnoreCase(TIFF_LZW)) {
                        params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_LZW);
                    }
                    if( p.getValue().equalsIgnoreCase(TIFF_PACKBITS)) {
                        params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_PACKBITS);
                    }
                }
            }
        }

        byte[] bytes;
        try {
            bytes = Sanselan.writeImageToBytes(image, format, params);
        } catch (ImageWriteException e) {
            return this.returnWithErrorMessage("Could not write the Image. ",e);
        } catch (IOException e) {
            return this.returnWithErrorMessage("Could not write the Image. ",e);
        }
       
        ServiceReport rep = new ServiceReport(Type.INFO, Status.SUCCESS, "OK", sph.getPerformanceProperties());
        DigitalObject ndo = new DigitalObject.Builder(Content.byValue(bytes)).build();
        return new MigrateResult( ndo, rep );
    }
View Full Code Here

    @SuppressWarnings("boxing")
  public MigrateResult migrate(DigitalObject digitalObject, URI inputFormat,
      URI outputFormat, List<Parameter> toolParameters)
      throws MigrationException, ConfigurationException {

  final ServicePerformanceHelper servicePerformanceHelper = new ServicePerformanceHelper();
  final Date migrationStartTime = new Date();

  /*
   * Validate that the proper parameters are set for the migration path
   * identified by inputFormat and outputFormat
   */
  final MigrationPath migrationPath = this.migrationPaths.getMigrationPath(
    inputFormat, outputFormat);

  // If called with null parameters, use an empty list instead
  if (toolParameters == null) {
      this.log.warning("Called with null parameters. Assuming the caller ment"
        + " to call with an empty list.");
      toolParameters = new ArrayList<Parameter>();
  }

  // Prepare any necessary temporary files.
  final Map<String, File> temporaryFileMappings = createTemporaryFiles(migrationPath);

  // Prepare the data to migrate
  InputStream standardInputStream = null;
  final ToolIOProfile inputIOProfile = migrationPath
    .getToolInputProfile();
  if (inputIOProfile.usePipedIO()) {

      // Serve the digital object through standard input
      standardInputStream = digitalObject.getContent().getInputStream();
  } else {

      // Serve the digital object through a temporary input file.
      File inputTempFile = temporaryFileMappings.get(inputIOProfile
        .getCommandLineFileLabel());
      DigitalObjectUtils.toFile(digitalObject, inputTempFile);
  }

  // Create an executable command line for the process runner.
  final PRCommandBuilder commandBuilder = new PRCommandBuilder(
    this.environmentParameters);
  final List<String> prCommand = commandBuilder.buildCommand(
    migrationPath, toolParameters, temporaryFileMappings);

  if (this.log.isLoggable(Level.INFO)) {
      String fullCommandLine = "";
      for (String cmdfrag : prCommand) {
    fullCommandLine += cmdfrag + " ";
      }
      this.log.info("Executing command line: " + fullCommandLine);
  }

  // Execute the tool
  final ProcessRunner toolProcessRunner = new ProcessRunner();
  final boolean executionSuccessful = executeToolProcess(
    toolProcessRunner, prCommand, standardInputStream);

  // Delete temporary files. However, do NOT delete the output unless the
  // execution failed.

  final ToolIOProfile outputIOProfile = migrationPath
    .getToolOutputProfile();

  if ((outputIOProfile.usePipedIO() == false) && executionSuccessful) {
      // OK, there should exist an output file. Avoid deleting it.
      final String outputFileLabel = outputIOProfile
        .getCommandLineFileLabel();
      for (String tempFileLabel : temporaryFileMappings.keySet()) {
    if (outputFileLabel.equals(tempFileLabel) == false) {
        temporaryFileMappings.get(tempFileLabel).delete();
    }
      }
  } else {
      // The output has been returned through a pipe, so it is safe to
      // delete all files.
      for (File tempFile : temporaryFileMappings.values()) {
    tempFile.delete();
      }
  }

  if (executionSuccessful == false) {
      return buildMigrationResult(migrationPath, digitalObject, null,
        toolProcessRunner);
  }

  // Now create a digital object from the tools output.
  DigitalObject.Builder builder;

  final ParameterReader parameterReader = new ParameterReader(
    toolParameters);
  final boolean returnDataByReference = parameterReader
    .getBooleanParameter("returnByReference", true);

  final ToolIOProfile toolOutputProfile = migrationPath
    .getToolOutputProfile();
  if (toolOutputProfile.usePipedIO() == false) {

      // The tool has written the output to a temporary file. Create a
      // digital object based on that.
      final File outputFile = temporaryFileMappings.get(toolOutputProfile
        .getCommandLineFileLabel());
      if (returnDataByReference) {
    builder = new DigitalObject.Builder(Content
      .byReference(outputFile));
    // We cannot tell when the temporary file can be deleted, so let
    // it live.
      } else {
    builder = new DigitalObject.Builder(Content.byValue(outputFile));

    // It is now safe to delete the temporary file.
    outputFile.delete();
      }
  } else {

      // The tool has written the output to standard output. Create a
      // digital object based on that output.
      if (returnDataByReference) {
    // Direct the standard output contents to a temporary file.
    builder = new DigitalObject.Builder(Content
      .byReference(toolProcessRunner.getProcessOutput()));
      } else {
    // Return the standard output contents by value.
    builder = new DigitalObject.Builder(Content
      .byValue(toolProcessRunner.getProcessOutput()));
      }
  }

  final double migrationDuration = new Date().getTime()
    - migrationStartTime.getTime();

  builder.format(outputFormat);
  final Agent agent = new Agent(this.toolIdentifier, this.serviceDescription
    .getName(), this.serviceDescription.getType());

  String eventSummary = "Migration carried out by executing the command line:";
  for (String commandLineFragment : prCommand) {
      eventSummary += " " + commandLineFragment;
  }
  eventSummary += "\n\nThe migration service was called with these parameters:\n\n";
  for (Parameter serviceParameter : toolParameters) {
      eventSummary += serviceParameter.getName() + " = "
        + serviceParameter.getValue() + "\n";
  }

  servicePerformanceHelper.stop();

  // Add information about the migration event to the digital object.
  final DateFormat defaultDateFormat = DateFormat.getDateInstance();
  final Event event = new Event(eventSummary, defaultDateFormat
    .format(migrationStartTime), migrationDuration, agent,
    servicePerformanceHelper.getPerformanceProperties());
  builder.events(event);

  final DigitalObject resultObject = builder.build();

  return buildMigrationResult(migrationPath, digitalObject, resultObject,
View Full Code Here

TOP

Related Classes of eu.planets_project.services.utils.ServicePerformanceHelper

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.