Example usage for com.amazonaws.util IOUtils toString

List of usage examples for com.amazonaws.util IOUtils toString

Introduction

In this page you can find the example usage for com.amazonaws.util IOUtils toString.

Prototype

public static String toString(InputStream is) throws IOException 

Source Link

Document

Reads and returns the rest of the given input stream as a string.

Usage

From source file:com.netflix.spinnaker.halyard.deploy.services.v1.ArtifactService.java

License:Apache License

public void writeArtifactConfig(String bomPath, String artifactName, String profilePath) {
    if (googleWriteableProfileRegistry == null) {
        throw new HalException(FATAL, NO_WRITER_ENABLED);
    }//from  www .  j a va 2  s . c om

    BillOfMaterials bom;
    File profileFile = Paths.get(profilePath).toFile();
    String profileContents;

    try {
        bom = relaxedObjectMapper.convertValue(yamlParser.load(IOUtils.toString(new FileInputStream(bomPath))),
                BillOfMaterials.class);
    } catch (IOException e) {
        throw new HalException(
                new ConfigProblemBuilder(FATAL, "Unable to load Bill of Materials: " + e.getMessage()).build());
    }

    try {
        profileContents = IOUtils.toString(new FileInputStream(profileFile));
    } catch (IOException e) {
        throw new HalException(
                new ConfigProblemBuilder(FATAL, "Unable to load profile : " + e.getMessage()).build());
    }

    googleWriteableProfileRegistry.writeArtifactConfig(bom, artifactName, profileFile.getName(),
            profileContents);
}

From source file:com.netflix.spinnaker.halyard.deploy.services.v1.VaultService.java

License:Apache License

public void publishSecret(DeploymentConfiguration deploymentConfiguration, String name, Path path) {
    String contents;/*  w w w  .  j a va 2 s  .c  om*/
    try {
        contents = IOUtils.toString(new FileInputStream(path.toFile()));
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL,
                "Failed to read config file " + path.toString() + ": " + e.getMessage());
    }

    publishSecret(deploymentConfiguration, name, contents);
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.KubernetesV2ClouddriverProfileFactory.java

License:Apache License

private void processKubernetesAccount(KubernetesAccount account) {
    if (account.usesServiceAccount()) {
        return;//from   www  .  jav a2  s. co  m
    }

    String kubeconfigFile = account.getKubeconfigFile();
    String kubeconfigContents;
    String context = account.getContext();
    try {
        if (EncryptedSecret.isEncryptedSecret(kubeconfigFile)) {
            kubeconfigContents = secretSessionManager.decrypt(kubeconfigFile);
        } else {
            kubeconfigContents = IOUtils.toString(new FileInputStream(kubeconfigFile));
        }
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(
                "No kubeconfig file '" + kubeconfigFile + "' found, but validation passed: " + e.getMessage(),
                e);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to read kubeconfig file '" + kubeconfigFile
                + "', but validation passed: " + e.getMessage(), e);
    }

    Object obj = yamlParser.load(kubeconfigContents);
    Map<String, Object> parsedKubeconfig = objectMapper.convertValue(obj,
            new TypeReference<Map<String, Object>>() {
            });

    if (StringUtils.isEmpty(context)) {
        context = (String) parsedKubeconfig.get("current-context");
    }

    if (StringUtils.isEmpty(context)) {
        throw new HalException(Problem.Severity.FATAL, "No context specified in kubernetes account "
                + account.getName() + " and no 'current-context' in " + kubeconfigFile);
    }

    final String finalContext = context;

    String user = (String) ((List<Map<String, Object>>) parsedKubeconfig.getOrDefault("contexts",
            new ArrayList<>())).stream().filter(c -> c.getOrDefault("name", "").equals(finalContext))
                    .findFirst()
                    .map(m -> ((Map<String, Object>) m.getOrDefault("context", new HashMap<>())).get("user"))
                    .orElse("");

    if (StringUtils.isEmpty(user)) {
        return;
    }

    Map<String, Object> userProperties = (Map<String, Object>) ((List<Map<String, Object>>) parsedKubeconfig
            .getOrDefault("users", new ArrayList<>())).stream()
                    .filter(c -> c.getOrDefault("name", "").equals(user)).findFirst().map(u -> u.get("user"))
                    .orElse(null);

    if (userProperties == null) {
        throw new HalException(Problem.Severity.FATAL,
                "No user named '" + user + "' exists in your kubeconfig file.");
    }

    Map<String, Object> authProvider = (Map<String, Object>) userProperties.get("auth-provider");

    if (authProvider == null || !authProvider.getOrDefault("name", "").equals("gcp")) {
        return;
    }

    Map<String, String> authProviderConfig = (Map<String, String>) authProvider.get("config");

    if (authProviderConfig == null) {
        return;
    }

    authProviderConfig.put("cmd-path", "gcloud");

    try {
        yamlParser.dump(parsedKubeconfig, new FileWriter(kubeconfigFile));
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL,
                "Unable to write the kubeconfig file to the staging area. This may be a user permissions issue.");
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.RegistryBackedProfileFactory.java

License:Apache License

@Override
protected Profile getBaseProfile(String name, String version, String outputFile) {
    try {/*  ww  w.  java  2 s. co m*/
        return new Profile(name, version, outputFile,
                IOUtils.toString(profileRegistry.readProfile(getArtifact().getName(), version, name)));
    } catch (RetrofitError | IOException e) {
        throw new HalException(new ConfigProblemBuilder(FATAL,
                "Unable to retrieve profile \"" + name + "\": " + e.getMessage()).build(), e);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.SpinnakerProfile.java

License:Apache License

/**
 * @return the base config (typically found in a profile's ./halconfig/ directory) for
 * the version of the profile specified by the Spinnaker version in the loaded halconfig.
 *//*  ww  w.  j  av  a 2 s  . co m*/
private ProfileConfig getBaseConfig(DeploymentConfiguration deploymentConfiguration) {
    try {
        String componentVersion = artifactService.getArtifactVersion(deploymentConfiguration.getName(),
                getArtifact());
        String componentObjectName = ProfileRegistry.profilePath(getArtifact().getName(), componentVersion,
                getProfileFileName());

        return new ProfileConfig().setPrimaryConfigFile(getProfileFileName())
                .extendConfig(getProfileFileName(),
                        IOUtils.toString(profileRegistry.getObjectContents(componentObjectName)))
                .setVersion(componentVersion);
    } catch (RetrofitError | IOException e) {
        throw new HalException(new ConfigProblemBuilder(FATAL,
                "Unable to retrieve a profile for \"" + getArtifact().getName() + "\": " + e.getMessage())
                        .build());
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.KubernetesProviderUtils.java

License:Apache License

static void upsertSecret(AccountDeploymentDetails<KubernetesAccount> details, Set<String> files,
        String secretName, String namespace) {
    KubernetesClient client = getClient(details);

    if (client.secrets().inNamespace(namespace).withName(secretName).get() != null) {
        client.secrets().inNamespace(namespace).withName(secretName).delete();
    }// www.j  a  v a2 s  .c om

    Map<String, String> secretContents = new HashMap<>();

    files.forEach(s -> {
        try {
            File f = new File(s);
            String name = f.getName();
            String data = new String(
                    Base64.getEncoder().encode(IOUtils.toString(new FileInputStream(f)).getBytes()));
            secretContents.putIfAbsent(name, data);
        } catch (IOException e) {
            throw new HalException(Severity.ERROR, "Unable to read contents of \"" + s + "\": " + e);
        }
    });

    SecretBuilder secretBuilder = new SecretBuilder();
    secretBuilder = secretBuilder.withNewMetadata().withName(secretName).withNamespace(namespace).endMetadata()
            .withData(secretContents);

    client.secrets().inNamespace(namespace).create(secretBuilder.build());
}

From source file:edu.brandeis.wisedb.WiSeDBUtils.java

License:Open Source License

/**
 * Generate a cached decision tree model that can be applied quickly over and over again
 * (instead of rebuilding the decision tree model from training data each time).
 * @param training the training data/*from w  w w .j a v a  2  s . co m*/
 * @param wf the workload specification
 * @return a black-box object representing the cached DT model
 */
public static WiSeDBCachedModel getCachedModel(InputStream training, WorkloadSpecification wf) {
    String s;
    try {
        s = IOUtils.toString(training);
    } catch (IOException e) {
        return null;
    }
    return new WiSeDBCachedModel(SchedulerUtils.getDTModel(new ByteArrayInputStream(s.getBytes()), wf), s, wf);
}

From source file:org.icgc.dcc.storage.client.exception.AmazonS3RetryableResponseErrorHandler.java

License:Open Source License

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus status = response.getStatusCode();
    AmazonS3Exception e = new AmazonS3Exception(IOUtils.toString(response.getBody()));
    switch (status) {
    case BAD_REQUEST:
        if (e.getErrorCode() == null || e.getErrorCode().equals("RequestTimeout")) {
            throw retryableException(response);
        }/*from   w  w w.ja  va 2s  .  c o  m*/
    case NOT_FOUND:
        throw notRetryableException(response);

    case INTERNAL_SERVER_ERROR:
        log.warn("Server error. Stop processing: {}", response.getStatusText());
        throw notResumableException(response);

    case FORBIDDEN:
        log.warn("FORBIDDEN response code received");
        throw notRetryableException(
                "Access refused by object store. Confirm client is part of repository cloud and that the download was initiated less than 1 day earlier (7 days for uploads)",
                response);

    default:
        log.warn("Retryable exception: {}", response.getStatusText());
        throw retryableException(response);

    }
}

From source file:org.icgc.dcc.storage.client.exception.ControlExceptionFactory.java

License:Open Source License

public static RetryableException retryableException(String prefix, ClientHttpResponse response)
        throws IOException {
    return new RetryableException(
            new IOException((prefix == null ? "" : prefix) + IOUtils.toString(response.getBody())));
}

From source file:org.icgc.dcc.storage.client.exception.ControlExceptionFactory.java

License:Open Source License

public static NotRetryableException notRetryableException(String prefix, ClientHttpResponse response)
        throws IOException {
    return new NotRetryableException(
            new IOException((prefix == null ? "" : prefix) + IOUtils.toString(response.getBody())));
}