Example usage for java.io UncheckedIOException UncheckedIOException

List of usage examples for java.io UncheckedIOException UncheckedIOException

Introduction

In this page you can find the example usage for java.io UncheckedIOException UncheckedIOException.

Prototype

public UncheckedIOException(String message, IOException cause) 

Source Link

Document

Constructs an instance of this class.

Usage

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestResponse.java

/**
 * Returns the body as a string/*from   ww  w  .  j av  a2s .c  o  m*/
 */
public String getBodyAsString() {
    if (bodyAsString == null && body != null) {
        //content-type null means that text was returned
        if (bodyContentType == null || bodyContentType == XContentType.JSON
                || bodyContentType == XContentType.YAML) {
            bodyAsString = new String(body, StandardCharsets.UTF_8);
        } else {
            //if the body is in a binary format and gets requested as a string (e.g. to log a test failure), we convert it to json
            try (XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()) {
                try (XContentParser parser = bodyContentType.xContent()
                        .createParser(NamedXContentRegistry.EMPTY, body)) {
                    jsonBuilder.copyCurrentStructure(parser);
                }
                bodyAsString = jsonBuilder.string();
            } catch (IOException e) {
                throw new UncheckedIOException("unable to convert response body to a string format", e);
            }
        }
    }
    return bodyAsString;
}

From source file:org.trellisldp.file.FileUtils.java

/**
 * Write a Memento to a particular resource directory.
 * @param resourceDir the resource directory
 * @param resource the resource//w w  w.j a v a  2 s  .c om
 * @param time the time for the memento
 */
public static void writeMemento(final File resourceDir, final Resource resource, final Instant time) {
    try (final BufferedWriter writer = newBufferedWriter(getNquadsFile(resourceDir, time).toPath(), UTF_8,
            CREATE, WRITE, TRUNCATE_EXISTING)) {

        try (final Stream<String> quads = generateServerManaged(resource).map(FileUtils::serializeQuad)) {
            final Iterator<String> lineIter = quads.iterator();
            while (lineIter.hasNext()) {
                writer.write(lineIter.next() + lineSeparator());
            }
        }

        try (final Stream<String> quads = resource.stream().filter(FileUtils::notServerManaged)
                .map(FileUtils::serializeQuad)) {
            final Iterator<String> lineiter = quads.iterator();
            while (lineiter.hasNext()) {
                writer.write(lineiter.next() + lineSeparator());
            }
        }
    } catch (final IOException ex) {
        throw new UncheckedIOException(
                "Error writing resource version for " + resource.getIdentifier().getIRIString(), ex);
    }
}

From source file:org.datacleaner.components.machinelearning.MLRegressionTrainingAnalyzer.java

@Override
public MLRegressionAnalyzerResult getResult() {
    final List<MLFeatureModifier> featureModifiers = featureModifierBuilders.stream()
            .map(MLFeatureModifierBuilder::build).collect(Collectors.toList());
    final List<String> columnNames = CollectionUtils.map(featureColumns, new HasNameMapper());
    final MLTrainingOptions options = new MLTrainingOptions(Double.class, columnNames, featureModifiers);

    final MLRegressorTrainer trainer = createTrainer(options);
    log("Training model starting. Records=" + trainingRecords.size() + ", Columns=" + columnNames.size()
            + ", Features=" + MLFeatureUtils.getFeatureCount(featureModifiers) + ".");
    final MLRegressor regressor = trainer.train(trainingRecords, featureModifiers, new MLTrainerCallback() {
        @Override//from  w w w.j a  v a 2 s . c om
        public void epochDone(int epochNo, int expectedEpochs) {
            if (expectedEpochs > 1) {
                log("Training progress: Epoch " + epochNo + " of " + expectedEpochs + " done.");
            }
        }
    });

    if (saveModelToFile != null) {
        logger.info("Saving model to file: {}", saveModelToFile);
        try {
            final byte[] bytes = SerializationUtils.serialize(regressor);
            Files.write(bytes, saveModelToFile);
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to save model to file: " + saveModelToFile, e);
        }
    }

    log("Trained model. Creating evaluation matrices.");

    return new MLRegressionAnalyzerResult(regressor);
}

From source file:org.datacleaner.components.machinelearning.MLClassificationTrainingAnalyzer.java

@Override
public MLClassificationAnalyzerResult getResult() {
    final List<MLFeatureModifier> featureModifiers = featureModifierBuilders.stream()
            .map(MLFeatureModifierBuilder::build).collect(Collectors.toList());
    final List<String> columnNames = CollectionUtils.map(featureColumns, new HasNameMapper());
    final MLTrainingOptions options = new MLTrainingOptions(classification.getDataType(), columnNames,
            featureModifiers);//from   ww  w  .ja  va 2  s  .com

    final MLClassificationTrainer trainer = createTrainer(options);
    log("Training model starting. Records=" + trainingRecords.size() + ", Columns=" + columnNames.size()
            + ", Features=" + MLFeatureUtils.getFeatureCount(featureModifiers) + ".");
    final MLClassifier classifier = trainer.train(trainingRecords, featureModifiers, new MLTrainerCallback() {
        @Override
        public void epochDone(int epochNo, int expectedEpochs) {
            if (expectedEpochs > 1) {
                log("Training progress: Epoch " + epochNo + " of " + expectedEpochs + " done.");
            }
        }
    });

    if (saveModelToFile != null) {
        logger.info("Saving model to file: {}", saveModelToFile);
        try {
            final byte[] bytes = SerializationUtils.serialize(classifier);
            Files.write(bytes, saveModelToFile);
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to save model to file: " + saveModelToFile, e);
        }
    }

    log("Trained model. Creating evaluation matrices.");

    final Crosstab<Integer> trainedRecordsConfusionMatrix = createConfusionMatrixCrosstab(classifier,
            trainingRecords);
    final Crosstab<Integer> crossValidationConfusionMatrix = createConfusionMatrixCrosstab(classifier,
            crossValidationRecords);

    return new MLClassificationAnalyzerResult(classifier, trainedRecordsConfusionMatrix,
            crossValidationConfusionMatrix);
}

From source file:org.trellisldp.file.FileBinaryService.java

@Override
public CompletionStage<Void> setContent(final BinaryMetadata metadata, final InputStream stream) {
    requireNonNull(stream, "InputStream may not be null!");
    return supplyAsync(() -> {
        final File file = getFileFromIdentifier(metadata.getIdentifier());
        LOGGER.debug("Setting binary content for {} at {}", metadata.getIdentifier(), file.getAbsolutePath());
        try (final InputStream input = stream) {
            final File parent = file.getParentFile();
            parent.mkdirs();//ww w .j av a 2s  .  c om
            copy(stream, file.toPath(), REPLACE_EXISTING);
        } catch (final IOException ex) {
            throw new UncheckedIOException("Error while setting content for " + metadata.getIdentifier(), ex);
        }
        return null;
    });
}

From source file:org.mitre.mpf.wfm.pipeline.PipelineManager.java

@PostConstruct
public void init() {
    log.debug("Initializing PipelineManager");
    xStream = new XStream();

    xStream.processAnnotations(PipelineDefinitionCollection.class);
    xStream.processAnnotations(TaskDefinitionCollection.class);
    xStream.processAnnotations(ActionDefinitionCollection.class);
    xStream.processAnnotations(AlgorithmDefinitionCollection.class);

    try {//from w  w  w .  j a va  2  s . c o m
        AlgorithmDefinitionCollection algorithms = fromXStream(propertiesUtil.getAlgorithmDefinitions(),
                AlgorithmDefinitionCollection.class);

        algorithms.getAlgorithms().stream()
                .flatMap(ad -> ad.getProvidesCollection().getAlgorithmProperties().stream())
                .forEach(pd -> pd.setDefaultValue(properties));

        for (AlgorithmDefinition algorithm : algorithms.getAlgorithms()) {
            if (addAlgorithm(algorithm)) {
                log.debug("added algorithm {}", algorithm);
            } else {
                log.warn("failed to add algorithm {}", algorithm);
            }
        }

        ActionDefinitionCollection actions = fromXStream(propertiesUtil.getActionDefinitions(),
                ActionDefinitionCollection.class);

        for (ActionDefinition action : actions.getActionDefinitions()) {
            if (addAction(action)) {
                log.debug("added action {}", action);
            } else {
                log.warn("failed to add action {}", action);
            }
        }

        TaskDefinitionCollection tasks = fromXStream(propertiesUtil.getTaskDefinitions(),
                TaskDefinitionCollection.class);

        for (TaskDefinition task : tasks.getTasks()) {
            if (addTask(task)) {
                log.debug("added task {}", task);
            } else {
                log.warn("failed to add task {}", task);
            }
        }

        PipelineDefinitionCollection pipelines = fromXStream(propertiesUtil.getPipelineDefinitions(),
                PipelineDefinitionCollection.class);

        for (PipelineDefinition pipeline : pipelines.getPipelines()) {
            if (addPipeline(pipeline)) {
                log.debug("added pipeline {}", pipeline);
            } else {
                log.warn("failed to add pipeline {}", pipeline);
            }
        }
    } catch (IOException e) {
        // Throwing an uncaught exception in a @PostConstruct function prevents the Spring ApplicationContext from starting up.
        throw new UncheckedIOException(
                "An exception occurred while trying to load an XML definitions file. Cannot start Workflow Manager without reading these files",
                e);
    }
}

From source file:org.mitre.mpf.wfm.service.PipelineServiceImpl.java

@PostConstruct
public void init() {
    // Method is reading from the algorithms.xml file, to build up a collection of algorithm definitions.
    log.debug("Initializing PipelineManager");
    xStream = new XStream();

    xStream.processAnnotations(PipelineDefinitionCollection.class);
    xStream.processAnnotations(TaskDefinitionCollection.class);
    xStream.processAnnotations(ActionDefinitionCollection.class);
    xStream.processAnnotations(AlgorithmDefinitionCollection.class);

    try {//from   w  w  w. j  a  v  a2 s.  c  o  m
        AlgorithmDefinitionCollection algorithms = fromXStream(propertiesUtil.getAlgorithmDefinitions(),
                AlgorithmDefinitionCollection.class);

        for (AlgorithmDefinition algorithm : algorithms.getAlgorithms()) {
            try {
                addAlgorithm(algorithm);
                log.debug("added algorithm {}", algorithm);
            } catch (WfmProcessingException ex) {
                log.warn("failed to add algorithm {}", algorithm);
            }
        }

        ActionDefinitionCollection actions = fromXStream(propertiesUtil.getActionDefinitions(),
                ActionDefinitionCollection.class);

        for (ActionDefinition action : actions.getActionDefinitions()) {
            try {
                addAction(action);
                log.debug("added action {}", action);
            } catch (WfmProcessingException ex) {
                log.warn("failed to add action {}", action);
            }
        }

        TaskDefinitionCollection tasks = fromXStream(propertiesUtil.getTaskDefinitions(),
                TaskDefinitionCollection.class);

        for (TaskDefinition task : tasks.getTasks()) {
            try {
                addTask(task);
                log.debug("added task {}", task);
            } catch (WfmProcessingException ex) {
                log.warn("failed to add task {}", task);
            }
        }

        PipelineDefinitionCollection pipelines = fromXStream(propertiesUtil.getPipelineDefinitions(),
                PipelineDefinitionCollection.class);

        for (PipelineDefinition pipeline : pipelines.getPipelines()) {
            try {
                addPipeline(pipeline);
                log.debug("added pipeline {}", pipeline);
            } catch (WfmProcessingException ex) {
                log.warn("failed to add pipeline {}", pipeline);
            }
        }
    } catch (IOException e) {
        // Throwing an uncaught exception in a @PostConstruct function prevents the Spring ApplicationContext from starting up.
        throw new UncheckedIOException(
                "An exception occurred while trying to load an XML definitions file. Cannot start Workflow Manager without reading these files",
                e);
    }
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

/**
 * Creates a new instance of the helper class.
 *
 * @param connectionContext connection object
 * @param requestFactory instance used for building requests to Manta
 * @param config configuration context object
 *//*  ww w  .  j  a v a 2 s. c om*/
public EncryptionHttpHelper(final MantaConnectionContext connectionContext,
        final MantaHttpRequestFactory requestFactory, final ConfigContext config) {
    super(connectionContext, requestFactory,
            ObjectUtils.firstNonNull(config.verifyUploads(), DefaultsConfigContext.DEFAULT_VERIFY_UPLOADS),
            ObjectUtils.firstNonNull(config.downloadContinuations(),
                    DefaultsConfigContext.DEFAULT_DOWNLOAD_CONTINUATIONS));

    this.encryptionKeyId = ObjectUtils.firstNonNull(config.getEncryptionKeyId(), "unknown-key");
    this.permitUnencryptedDownloads = ObjectUtils.firstNonNull(config.permitUnencryptedDownloads(),
            DefaultsConfigContext.DEFAULT_PERMIT_UNENCRYPTED_DOWNLOADS);

    this.encryptionAuthenticationMode = ObjectUtils.firstNonNull(config.getEncryptionAuthenticationMode(),
            EncryptionAuthenticationMode.DEFAULT_MODE);

    this.cipherDetails = ObjectUtils.firstNonNull(
            SupportedCiphersLookupMap.INSTANCE.getWithCaseInsensitiveKey(config.getEncryptionAlgorithm()),
            DefaultsConfigContext.DEFAULT_CIPHER);

    if (config.getEncryptionPrivateKeyPath() != null) {
        Path keyPath = Paths.get(config.getEncryptionPrivateKeyPath());

        try {
            secretKey = SecretKeyUtils.loadKeyFromPath(keyPath, this.cipherDetails);
        } catch (IOException e) {
            String msg = String.format("Unable to load secret key from file: %s", keyPath);
            throw new UncheckedIOException(msg, e);
        }
    } else if (config.getEncryptionPrivateKeyBytes() != null) {
        secretKey = SecretKeyUtils.loadKey(config.getEncryptionPrivateKeyBytes(), cipherDetails);
    } else {
        throw new MantaClientEncryptionException(
                "Either private encryption key path or bytes must be specified");
    }
}

From source file:org.trellisldp.file.FileBinaryService.java

private MessageDigest computeDigest(final IRI identifier, final MessageDigest algorithm) {
    try (final InputStream input = new FileInputStream(getFileFromIdentifier(identifier))) {
        return updateDigest(algorithm, input);
    } catch (final IOException ex) {
        throw new UncheckedIOException("Error computing digest", ex);
    }//from www.  java 2s. com
}

From source file:net.morimekta.idltool.IdlUtils.java

public static Map<String, String> buildSha1Sums(Path dir) throws IOException {
    ImmutableSortedMap.Builder<String, String> sha1sums = ImmutableSortedMap.naturalOrder();

    // TODO: Support nested directories.
    Files.list(dir).forEach(file -> {
        try {//from w  w w . j a  v  a 2s . c o  m
            if (Files.isRegularFile(file)) {
                String sha = DigestUtils.sha1Hex(Files.readAllBytes(file));
                sha1sums.put(file.getFileName().toString(), sha);
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e.getMessage(), e);
        }
    });

    return sha1sums.build();
}