Search in sources :

Example 1 with ICredentials

use of org.knime.core.node.workflow.ICredentials in project knime-core by knime.

the class DatabaseConnectionSettings method loadConnection.

private boolean loadConnection(final ConfigRO settings, final boolean write, final CredentialsProvider cp) throws InvalidSettingsException {
    if (settings == null) {
        throw new InvalidSettingsException("Connection settings not available!");
    }
    final Version knimeVersion = new Version(settings.getString("knimeVersion", LEGACY_VERSION.toString()));
    String driver = settings.getString("driver");
    String jdbcUrl = settings.getString("database");
    String user = "";
    String password = null;
    String credName = null;
    String timezone = settings.getString("timezone", "none");
    boolean validateConnection = settings.getBoolean("validateConnection", false);
    boolean retrieveMetadataInConfigure = settings.getBoolean("retrieveMetadataInConfigure", true);
    boolean allowSpacesInColumnNames = settings.getBoolean("allowSpacesInColumnNames", false);
    boolean rowIdsStartWithZero = settings.getBoolean("rowIdsStartWithZero", false);
    boolean kerberos = settings.getBoolean("kerberos", false);
    boolean useCredential = settings.containsKey("credential_name");
    if (useCredential) {
        credName = settings.getString("credential_name");
        if (cp != null) {
            try {
                ICredentials cred = cp.get(credName);
                user = cred.getLogin();
                password = cred.getPassword();
                if (password == null) {
                    LOGGER.warn("Credentials/Password has not been set, using empty password.");
                }
            } catch (IllegalArgumentException e) {
                if (!write) {
                    throw new InvalidSettingsException(e.getMessage());
                }
            }
        }
    } else {
        user = settings.getString("user");
        if (USER_INDICATOR.equals(user) && settings.containsKey(CFG_USER_NAME)) {
            // this is the new user name setting starting with KNIME 3.4.1 and no flow variables where used to set
            // the old 'user' setting
            user = settings.getString(CFG_USER_NAME);
        }
        final String pw = settings.getString("password", null);
        if (pw != null) {
            // these settings where either created prior KNIME 3.4 or flow variables are used to set the password
            try {
                password = KnimeEncryption.decrypt(pw);
            } catch (Exception e) {
                LOGGER.error("Password could not be decrypted, reason: " + e.getMessage());
            }
        } else {
            password = settings.getPassword("passwordEncrypted", ";Op5~pK{31AIN^eH~Ab`:YaiKM8CM`8_Dw:1Kl4_WHrvuAXO", "");
        }
    }
    final String dbIdentifier = settings.getString("databaseIdentifier", null);
    // write settings or skip it
    if (write) {
        m_driver = driver;
        DRIVER_ORDER.add(m_driver);
        boolean changed = false;
        if (useCredential) {
            changed = (m_credName != null) && (credName != null) && credName.equals(m_credName);
            m_credName = credName;
        } else {
            if ((m_user != null) && (m_jdbcUrl != null) && (m_pass != null)) {
                if (!m_user.equals(user) || !m_jdbcUrl.equals(jdbcUrl) || !m_pass.equals(password)) {
                    changed = true;
                }
            }
            m_credName = null;
        }
        m_user = user;
        m_pass = (password == null ? "" : password);
        m_jdbcUrl = jdbcUrl;
        m_timezone = timezone;
        m_validateConnection = validateConnection;
        m_retrieveMetadataInConfigure = retrieveMetadataInConfigure;
        m_allowSpacesInColumnNames = allowSpacesInColumnNames;
        m_rowIdsStartWithZero = rowIdsStartWithZero;
        m_dbIdentifier = dbIdentifier;
        m_kerberos = kerberos;
        m_knimeVersion = knimeVersion;
        DATABASE_URLS.add(m_jdbcUrl);
        return changed;
    }
    return false;
}
Also used : InvalidSettingsException(org.knime.core.node.InvalidSettingsException) Version(org.knime.core.util.Version) ICredentials(org.knime.core.node.workflow.ICredentials) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) SQLException(java.sql.SQLException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException)

Example 2 with ICredentials

use of org.knime.core.node.workflow.ICredentials in project knime-core by knime.

the class SendMailConfiguration method send.

/**
 * Send the mail.
 * @throws MessagingException ... when sending fails, also authorization exceptions etc.
 * @throws IOException SSL problems or when copying remote URLs to temp local file.
 * @throws InvalidSettingsException on invalid referenced flow vars
 */
void send(final FlowVariableProvider flowVarResolver, final CredentialsProvider credProvider) throws MessagingException, IOException, InvalidSettingsException {
    String flowVarCorrectedText;
    try {
        flowVarCorrectedText = FlowVariableResolver.parse(m_text, flowVarResolver);
    } catch (NoSuchElementException nse) {
        throw new InvalidSettingsException(nse.getMessage(), nse);
    }
    Properties properties = new Properties(System.getProperties());
    String protocol = "smtp";
    switch(getConnectionSecurity()) {
        case NONE:
            break;
        case STARTTLS:
            properties.setProperty("mail.smtp.starttls.enable", "true");
            break;
        case SSL:
            // this is the way to do it in javax.mail 1.4.5+ (default is currently (Aug '13) 1.4.0):
            // www.oracle.com/technetwork/java/javamail145sslnotes-1562622.html
            // 'First, and perhaps the simplest, is to set a property to enable use
            // of SSL.  For example, to enable use of SSL for SMTP connections, set
            // the property "mail.smtp.ssl.enable" to "true".'
            properties.setProperty("mail.smtp.ssl.enable", "true");
            // this is an alternative/backup, which works also:
            // http://javakiss.blogspot.ch/2010/10/smtp-in-java-with-javaxmail.html
            // I verify it's actually using SSL:
            // - it hid a breakpoint in sun.security.ssl.SSLSocketFactoryImpl
            // - Hostpoint (knime.com mail server) is rejecting any smtp request on their ssl port (465)
            // without this property
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            // a third (and most transparent) option would be to use a different protocol:
            protocol = "smtps";
            /* note, protocol smptps doesn't work with default javax.mail bundle (1.4.0):
                 * Unable to load class for provider: protocol=smtps; type=javax.mail.Provider$Type@2d0fc05b;
                 * class=org.apache.geronimo.javamail.transport.smtp.SMTPTSransport;
                 * vendor=Apache Software Foundation;version=1.0
                 * https://issues.apache.org/jira/browse/GERONIMO-4476
                 * It's a typo in geronimo class name (SMTPSTransport vs. SMTPTSransport) - plenty of google hits.
                 * (This impl. uses javax.mail.glassfish bundle.) */
            break;
        default:
    }
    properties.setProperty("mail." + protocol + ".host", getSmtpHost());
    properties.setProperty("mail." + protocol + ".port", Integer.toString(getSmtpPort()));
    properties.setProperty("mail." + protocol + ".auth", Boolean.toString(isUseAuthentication()));
    Session session = Session.getInstance(properties, null);
    MimeMessage message = new MimeMessage(session);
    if (!StringUtils.isBlank(getFrom())) {
        message.setFrom(new InternetAddress(getFrom()));
    } else {
        message.setFrom();
    }
    if (!StringUtils.isBlank(getTo())) {
        message.addRecipients(Message.RecipientType.TO, parseAndValidateRecipients(getTo()));
    }
    if (!StringUtils.isBlank(getCc())) {
        message.addRecipients(Message.RecipientType.CC, parseAndValidateRecipients(getCc()));
    }
    if (!StringUtils.isBlank(getBcc())) {
        message.addRecipients(Message.RecipientType.BCC, parseAndValidateRecipients(getBcc()));
    }
    if (message.getAllRecipients() == null) {
        throw new InvalidSettingsException("No recipients specified");
    }
    message.setHeader("X-Mailer", "KNIME/" + KNIMEConstants.VERSION);
    message.setHeader("X-Priority", m_priority.toXPriority());
    message.setSentDate(new Date());
    message.setSubject(getSubject());
    // text or html message part
    MimeBodyPart contentBody = new MimeBodyPart();
    String textType;
    switch(getFormat()) {
        case Html:
            textType = "text/html; charset=\"utf-8\"";
            break;
        case Text:
            textType = "text/plain; charset=\"utf-8\"";
            break;
        default:
            throw new RuntimeException("Unsupported format: " + getFormat());
    }
    contentBody.setContent(flowVarCorrectedText, textType);
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(contentBody);
    List<File> tempDirs = new ArrayList<File>();
    Transport t = null;
    ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
    // make sure to set class loader to javax.mail - this has caused problems in the past, see bug 5316
    Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
    try {
        for (URL url : getAttachedURLs()) {
            MimeBodyPart filePart = new MimeBodyPart();
            File file;
            if ("file".equals(url.getProtocol())) {
                try {
                    file = new File(url.toURI());
                } catch (URISyntaxException e) {
                    throw new IOException("Invalid attachment: " + url, e);
                }
            } else {
                File tempDir = FileUtil.createTempDir("send-mail-attachment");
                tempDirs.add(tempDir);
                try {
                    file = new File(tempDir, FilenameUtils.getName(url.toURI().getSchemeSpecificPart()));
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
                FileUtils.copyURLToFile(url, file);
            }
            if (!file.canRead()) {
                throw new IOException("Unable to file attachment \"" + url + "\"");
            }
            filePart.attachFile(file);
            // java 7u7 is missing mimemtypes.default file:
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7096063
            // find mime type in this bundle (META-INF folder contains mime.types) and set it
            filePart.setHeader("Content-Type", FileTypeMap.getDefaultFileTypeMap().getContentType(file));
            mp.addBodyPart(filePart);
        }
        t = session.getTransport(protocol);
        if (isUseAuthentication()) {
            String user;
            String pass;
            if (isUseCredentials()) {
                ICredentials iCredentials = credProvider.get(getCredentialsId());
                user = iCredentials.getLogin();
                pass = iCredentials.getPassword();
            } else {
                user = getSmtpUser();
                pass = getSmtpPassword();
            }
            t.connect(user, pass);
        } else {
            t.connect();
        }
        message.setContent(mp);
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        Thread.currentThread().setContextClassLoader(oldContextClassLoader);
        for (File d : tempDirs) {
            FileUtils.deleteQuietly(d);
        }
        if (t != null) {
            t.close();
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Properties(java.util.Properties) Date(java.util.Date) URL(java.net.URL) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ICredentials(org.knime.core.node.workflow.ICredentials) MimeBodyPart(javax.mail.internet.MimeBodyPart) Transport(javax.mail.Transport) File(java.io.File) NoSuchElementException(java.util.NoSuchElementException) Session(javax.mail.Session)

Example 3 with ICredentials

use of org.knime.core.node.workflow.ICredentials in project knime-core by knime.

the class PortObjectIDSettings method loadSettings.

/**
 * Loads the settings from a NodeSettings object.
 * @param settings to load from.
 * @throws InvalidSettingsException If no settings present or invalid.
 */
public void loadSettings(final NodeSettingsRO settings) throws InvalidSettingsException {
    m_id = settings.getInt("portobject_ID");
    m_copyData = settings.getBoolean("copyData");
    m_flowVariables = new ArrayList<FlowVariable>();
    // added for cluster version 1.0.2
    if (settings.containsKey("flowVariables")) {
        NodeSettingsRO sub = settings.getNodeSettings("flowVariables");
        for (String key : sub.keySet()) {
            NodeSettingsRO child = sub.getNodeSettings(key);
            // code copied from (package scope) load method in FlowVariable
            String name = child.getString("name");
            String typeS = child.getString("class");
            if (typeS == null || name == null) {
                throw new InvalidSettingsException("name or type is null");
            }
            FlowVariable.Type varType;
            try {
                varType = FlowVariable.Type.valueOf(typeS);
            } catch (final IllegalArgumentException e) {
                throw new InvalidSettingsException("invalid type " + typeS);
            }
            FlowVariable v;
            switch(varType) {
                case DOUBLE:
                    v = new FlowVariable(name, child.getDouble("value"));
                    break;
                case INTEGER:
                    v = new FlowVariable(name, child.getInt("value"));
                    break;
                case STRING:
                    v = new FlowVariable(name, child.getString("value"));
                    break;
                case CREDENTIALS:
                    CheckUtils.checkState(m_credentialsProvider != null, "No credentials provider set");
                    ICredentials credentials = m_credentialsProvider.get(child.getString("value"));
                    v = CredentialsStore.newCredentialsFlowVariable(credentials.getName(), credentials.getLogin(), credentials.getPassword(), false, false);
                    break;
                default:
                    throw new InvalidSettingsException("Unknown type " + varType);
            }
            m_flowVariables.add(v);
        }
    }
}
Also used : InvalidSettingsException(org.knime.core.node.InvalidSettingsException) ICredentials(org.knime.core.node.workflow.ICredentials) NodeSettingsRO(org.knime.core.node.NodeSettingsRO) FlowVariable(org.knime.core.node.workflow.FlowVariable)

Aggregations

InvalidSettingsException (org.knime.core.node.InvalidSettingsException)3 ICredentials (org.knime.core.node.workflow.ICredentials)3 IOException (java.io.IOException)2 File (java.io.File)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 InvalidKeyException (java.security.InvalidKeyException)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 NoSuchElementException (java.util.NoSuchElementException)1 Properties (java.util.Properties)1 BadPaddingException (javax.crypto.BadPaddingException)1 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)1 Multipart (javax.mail.Multipart)1 Session (javax.mail.Session)1 Transport (javax.mail.Transport)1 InternetAddress (javax.mail.internet.InternetAddress)1 MimeBodyPart (javax.mail.internet.MimeBodyPart)1 MimeMessage (javax.mail.internet.MimeMessage)1