Example usage for java.security GeneralSecurityException printStackTrace

List of usage examples for java.security GeneralSecurityException printStackTrace

Introduction

In this page you can find the example usage for java.security GeneralSecurityException printStackTrace.

Prototype

public void printStackTrace(PrintStream s) 

Source Link

Document

Prints this throwable and its backtrace to the specified print stream.

Usage

From source file:org.jenkinsci.plugins.androidsigning.SignApksBuilder.java

@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
        @Nonnull TaskListener listener) throws InterruptedException, IOException {
    if (isIntermediateFailure(run)) {
        listener.getLogger()/* w w w .  j  ava 2 s.  co m*/
                .println("[SignApksBuilder] skipping Sign APKs step because a previous step failed");
        return;
    }

    if (getEntries() != null && !getEntries().isEmpty()) {
        List<SignApksBuilder> newModelBuilders = singleEntryBuildersFromEntriesOfBuilder(this);
        for (SignApksBuilder builder : newModelBuilders) {
            builder.perform(run, workspace, launcher, listener);
        }
        return;
    }

    EnvVars env;
    if (run instanceof AbstractBuild) {
        env = run.getEnvironment(listener);
        env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables());
    } else {
        env = new EnvVars();
    }

    FilePath builderDir = workspace.child(BUILDER_DIR);
    String excludeBuilderDir = builderDir.getName() + "/**";
    ZipalignTool zipalign = new ZipalignTool(env, workspace, listener.getLogger(), androidHome, zipalignPath);
    Map<String, String> apksToArchive = new LinkedHashMap<>();

    StandardCertificateCredentials keyStoreCredential = getKeystore(getKeyStoreId(), run.getParent());
    char[] storePassword = keyStoreCredential.getPassword().getPlainText().toCharArray();
    // TODO: add key password support
    char[] keyPassword = storePassword;
    KeyStore keyStore = keyStoreCredential.getKeyStore();
    String alias = getKeyAlias();
    PrivateKey key;
    Certificate[] certChain;
    try {
        if (getKeyAlias() == null) {
            // TODO: search all entries to find key, throw error if multiple keys
        }
        key = (PrivateKey) keyStore.getKey(alias, keyPassword);
        certChain = keyStore.getCertificateChain(alias);
    } catch (GeneralSecurityException e) {
        PrintWriter details = listener.fatalError("Error reading keystore " + getKeyStoreId());
        e.printStackTrace(details);
        throw new AbortException("Error reading keystore " + getKeyStoreId());
    }

    if (key == null || certChain == null) {
        throw new AbortException("Alias " + alias
                + " does not exist or does not point to a key and certificate in certificate credentials "
                + getKeyStoreId());
    }

    String v1SigName = alias;
    if (v1SigName == null) {
        v1SigName = keyStoreCredential.getId();
    }

    Set<FilePath> matchedApks = new TreeSet<>(Comparator.comparing(FilePath::getRemote));
    String[] globs = getSelectionGlobs();
    for (String glob : globs) {
        FilePath[] globMatch = workspace.list(glob, excludeBuilderDir);
        if (globMatch.length == 0) {
            throw new AbortException("No APKs in workspace matching " + glob);
        }
        matchedApks.addAll(Arrays.asList(globMatch));
    }

    for (FilePath unsignedApk : matchedApks) {
        unsignedApk = unsignedApk.absolutize();
        FilePath archiveDir = builderDir.child(unsignedApk.getName());
        if (archiveDir.isDirectory()) {
            archiveDir.deleteContents();
        } else {
            archiveDir.mkdirs();
        }
        String archiveDirRelName = relativeToWorkspace(workspace, archiveDir);
        String unsignedPathName = unsignedApk.getRemote();
        Pattern stripUnsignedPattern = Pattern.compile("(-?unsigned)?.apk$", Pattern.CASE_INSENSITIVE);
        Matcher stripUnsigned = stripUnsignedPattern.matcher(unsignedApk.getName());
        String strippedApkName = stripUnsigned.replaceFirst("");
        String alignedRelName = archiveDirRelName + "/" + strippedApkName + "-aligned.apk";
        String signedRelName = archiveDirRelName + "/" + strippedApkName + "-signed.apk";

        ArgumentListBuilder zipalignCommand = zipalign.commandFor(unsignedPathName, alignedRelName);
        listener.getLogger().printf("[SignApksBuilder] %s%n", zipalignCommand);
        int zipalignResult = launcher.launch().cmds(zipalignCommand).pwd(workspace).stdout(listener)
                .stderr(listener.getLogger()).join();

        if (zipalignResult != 0) {
            listener.fatalError("[SignApksBuilder] zipalign failed: exit code %d", zipalignResult);
            throw new AbortException(
                    String.format("zipalign failed on APK %s: exit code %d", unsignedPathName, zipalignResult));
        }

        FilePath alignedPath = workspace.child(alignedRelName);
        if (!alignedPath.exists()) {
            throw new AbortException(String.format("aligned APK does not exist: %s", alignedRelName));
        }

        listener.getLogger().printf("[SignApksBuilder] signing APK %s%n", alignedRelName);

        FilePath signedPath = workspace.child(signedRelName);
        final SignApkCallable signApk = new SignApkCallable(key, certChain, v1SigName, signedPath.getRemote(),
                listener);
        alignedPath.act(signApk);

        listener.getLogger().printf("[SignApksBuilder] signed APK %s%n", signedRelName);

        if (getArchiveUnsignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving unsigned APK %s%n", unsignedPathName);
            apksToArchive.put(archiveDirRelName + "/" + unsignedApk.getName(),
                    relativeToWorkspace(workspace, unsignedApk));
        }
        if (getArchiveSignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving signed APK %s%n", signedRelName);
            apksToArchive.put(signedRelName, signedRelName);
        }
    }

    listener.getLogger().println("[SignApksBuilder] finished signing APKs");

    if (apksToArchive.size() > 0) {
        run.pickArtifactManager().archive(workspace, launcher, BuildListenerAdapter.wrap(listener),
                apksToArchive);
    }
}