Example usage for java.util Properties remove

List of usage examples for java.util Properties remove

Introduction

In this page you can find the example usage for java.util Properties remove.

Prototype

@Override
    public synchronized Object remove(Object key) 

Source Link

Usage

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*  www .java2s.c  o m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:org.jboss.bqt.framework.TestConfigPropertyLoader.java

/**
 * Tests {@link org.jboss.bqt.core.util.PropertiesUtils}
 * @throws Exception /*from   w  ww.j a v  a 2  s. c om*/
 */
@Test
public void test1() throws Exception {
    // add this step of removing the property because the order of
    // running is not guaranteed, and if this doesn't run first,
    // this property is set by other tests
    Properties props = System.getProperties();
    props.remove(ConfigPropertyNames.CONFIG_FILE);

    System.setProperties(props);

    System.setProperty("test", "value");

    ConfigPropertyLoader _instance = ConfigPropertyLoader.getInstance();
    Properties p = _instance.getProperties();
    assertNotNull(p);
    assertTrue(!p.isEmpty());

    assertEquals("value", p.getProperty("test")); //$NON-NLS-1$ //$NON-NLS-2$

    _instance.setProperty("override", "ovalue");

    assertEquals("ovalue", _instance.getProperty("override")); //$NON-NLS-1$ //$NON-NLS-2$

    // confirm the loader actually loaded the default-config.properties file
    assertEquals("driver", p.getProperty(ConfigPropertyNames.CONNECTION_TYPE)); //$NON-NLS-1$ //$NON-NLS-2$

    System.setProperty("username", "");

    ConfigPropertyLoader.reset();

    _instance = ConfigPropertyLoader.getInstance();
    p = _instance.getProperties();

    assertNull("should be null after reset", _instance.getProperties().getProperty("override"));

    assertEquals("failed to pickup system property", "value", p.getProperty("test")); //$NON-NLS-1$ //$NON-NLS-2$

    // confirm the loader actually loaded the default-config.properties file
    assertEquals("failed to correctly pickup the User ", "", _instance.getProperty("conn.user")); //$NON-NLS-1$ //$NON-NLS-2$

}

From source file:net.sf.jabb.util.db.impl.DbcpDataSourceProvider.java

public DataSource createDataSource(String source, String config) {
    String[] cfgs = config.split(PropertiesLoader.DELIMITERS, 2);
    if (cfgs.length != 2) {
        log.warn("Wrong configuration format for '" + source + "' : " + config);
        return null;
    }/*from  w ww . java  2  s.  c  o m*/

    DataSource ds = null;

    try {
        DirectDataSourceConfiguration lowerConfig = new DirectDataSourceConfiguration(cfgs[0]);
        Class.forName(lowerConfig.getDriverClassName());

        Properties props = propLoader.load(cfgs[1]);
        Properties connProps = lowerConfig.getConnectionProperties();
        props.put("username", connProps.get("user"));
        connProps.remove("user");
        props.put("password", connProps.get("password"));
        connProps.remove("password");
        props.put("url", lowerConfig.getUrl());
        props.put("driverClassName", lowerConfig.getDriverClassName());

        StringBuilder sb = new StringBuilder();
        String oldConnProp = props.getProperty("connectionProperties");
        if (oldConnProp != null) {
            sb.append(oldConnProp.trim());
        }
        for (Map.Entry<Object, Object> p : connProps.entrySet()) {
            if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ';') {
                sb.append(';');
            }
            sb.append(p.getKey().toString());
            sb.append('=');
            sb.append(p.getValue().toString());
        }
        props.put("connectionProperties", sb.toString());

        ds = BasicDataSourceFactory.createDataSource(props);

    } catch (InvalidPropertiesFormatException e) {
        log.warn(
                "Wrong configuration properties file format for '" + source + "' with configuration: " + config,
                e);
    } catch (IOException e) {
        log.warn("Error loading configuration file for '" + source + "' with configuration: " + config, e);
    } catch (ClassNotFoundException e) {
        log.warn("Driver class not found for '" + source + "' with configuration: " + config, e);
    } catch (Exception e) {
        log.warn("Error creating data source for '" + source + "' with configuration: " + config, e);
    }

    return ds;
}

From source file:org.wso2.carbon.identity.event.internal.EventUtils.java

/**
 * @param prefix                 Prefix of the property key
 * @param propertiesWithFullKeys Set of properties which needs to be converted to single word key properties
 * @return Set of properties which has keys containing single word.
 *///from w w  w  . j a v a2 s  .co  m
public static Properties buildSingleWordKeyProperties(String prefix, Properties propertiesWithFullKeys) {

    // Stop proceeding if required arguments are not present
    if (StringUtils.isEmpty(prefix) || propertiesWithFullKeys == null) {
        throw new IllegalArgumentException(
                "Prefix and properties should not be null to get  properties with " + "single word keys.");
    }

    propertiesWithFullKeys = EventUtils.getPropertiesWithPrefix(prefix, propertiesWithFullKeys);
    Properties properties = new Properties();
    Enumeration propertyNames = propertiesWithFullKeys.propertyNames();

    while (propertyNames.hasMoreElements()) {
        String key = (String) propertyNames.nextElement();
        String newKey = key.substring(key.lastIndexOf(".") + 1, key.length());
        if (!newKey.trim().isEmpty()) {
            // Remove from original properties to hold property schema. ie need to get the set of properties which
            // remains after consuming all required specific properties
            properties.put(newKey, propertiesWithFullKeys.remove(key));
        }
    }
    return properties;
}

From source file:org.wso2.carbon.identity.event.IdentityEventUtils.java

/**
 * @param prefix                 Prefix of the property key
 * @param propertiesWithFullKeys Set of properties which needs to be converted to single word key properties
 * @return Set of properties which has keys containing single word.
 *///ww  w. ja  v  a 2 s  .  com
public static Properties buildSingleWordKeyProperties(String prefix, Properties propertiesWithFullKeys) {

    // Stop proceeding if required arguments are not present
    if (StringUtils.isEmpty(prefix) || propertiesWithFullKeys == null) {
        throw new IllegalArgumentException(
                "Prefix and properties should not be null to get  properties with " + "single word keys.");
    }

    propertiesWithFullKeys = IdentityEventUtils.getPropertiesWithPrefix(prefix, propertiesWithFullKeys);
    Properties properties = new Properties();
    Enumeration propertyNames = propertiesWithFullKeys.propertyNames();

    while (propertyNames.hasMoreElements()) {
        String key = (String) propertyNames.nextElement();
        String newKey = key.substring(key.lastIndexOf(".") + 1, key.length());
        if (!newKey.trim().isEmpty()) {
            // Remove from original properties to hold property schema. ie need to get the set of properties which
            // remains after consuming all required specific properties
            properties.put(newKey, propertiesWithFullKeys.remove(key));
        }
    }
    return properties;
}

From source file:org.jboss.pnc.indyrepositorymanager.AbstractRepositoryManagerDriverTest.java

@After
public void teardown() throws Exception {
    Properties sysprops = System.getProperties();
    if (oldIni == null) {
        sysprops.remove(CONFIG_SYSPROP);
    } else {/*from w w w.j  a  v a 2  s.  c  o m*/
        sysprops.setProperty(CONFIG_SYSPROP, oldIni);
    }
    System.setProperties(sysprops);

    if (fixture != null) {
        fixture.stop();
    }
}

From source file:org.wso2.carbon.identity.event.EventManagementUtils.java

/**
 * @param prefix                 Prefix of the property key
 * @param propertiesWithFullKeys Set of properties which needs to be converted to single word key properties
 * @return Set of properties which has keys containing single word.
 *///from  w  ww  .  j  ava  2  s  .  c  om
public static Properties buildSingleWordKeyProperties(String prefix, Properties propertiesWithFullKeys) {

    // Stop proceeding if required arguments are not present
    if (StringUtils.isEmpty(prefix) || propertiesWithFullKeys == null) {
        throw new IllegalArgumentException(
                "Prefix and properties should not be null to get  properties with " + "single word keys.");
    }

    propertiesWithFullKeys = EventManagementUtils.getPropertiesWithPrefix(prefix, propertiesWithFullKeys);
    Properties properties = new Properties();
    Enumeration propertyNames = propertiesWithFullKeys.propertyNames();

    while (propertyNames.hasMoreElements()) {
        String key = (String) propertyNames.nextElement();
        String newKey = key.substring(key.lastIndexOf(".") + 1, key.length());
        if (!newKey.trim().isEmpty()) {
            // Remove from original properties to hold property schema. ie need to get the set of properties which
            // remains after consuming all required specific properties
            properties.put(newKey, propertiesWithFullKeys.remove(key));
        }
    }
    return properties;
}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

/**
 * Apply server configuration to email./*w  w  w  . j a va2 s  . co  m*/
 */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    mail.setAuthentication(configuration.getUsername(), configuration.getPassword());

    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));

    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }

    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }

    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }

    return mail;
}

From source file:org.wso2.carbon.core.persistence.metadata.ArtifactMetadataManager.java

public void removeParameter(String artifactName, ArtifactType artifactType, String propertyName)
        throws ArtifactMetadataException {
    ArtifactMetadata metadataObject = loadParameters(artifactName, artifactType);
    Properties prop = metadataObject.getProperties();

    prop.remove(propertyName);
    saveParameters(metadataObject);//from   w ww.  j  a  v a2s.c o m

}

From source file:org.wso2.carbon.identity.notification.mgt.NotificationManagementUtils.java

/**
 * @param prefix                 Prefix of the property key
 * @param propertiesWithFullKeys Set of properties which needs to be converted to single word key properties
 * @return Set of properties which has keys containing single word.
 *///from  w  w  w  . j  a v  a2  s  .  c  o  m
public static Properties buildSingleWordKeyProperties(String prefix, Properties propertiesWithFullKeys) {

    // Stop proceeding if required arguments are not present
    if (StringUtils.isEmpty(prefix) || propertiesWithFullKeys == null) {
        throw new IllegalArgumentException(
                "Prefix and properties should not be null to get  properties with " + "single word keys.");
    }

    propertiesWithFullKeys = NotificationManagementUtils.getPropertiesWithPrefix(prefix,
            propertiesWithFullKeys);
    Properties properties = new Properties();
    Enumeration propertyNames = propertiesWithFullKeys.propertyNames();

    while (propertyNames.hasMoreElements()) {
        String key = (String) propertyNames.nextElement();
        String newKey = key.substring(key.lastIndexOf(".") + 1, key.length());
        if (!newKey.trim().isEmpty()) {
            // Remove from original properties to hold property schema. ie need to get the set of properties which
            // remains after consuming all required specific properties
            properties.put(newKey, propertiesWithFullKeys.remove(key));
        }
    }
    return properties;
}