Example usage for java.util Properties put

List of usage examples for java.util Properties put

Introduction

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

Prototype

@Override
    public synchronized Object put(Object key, Object value) 

Source Link

Usage

From source file:ntpgraphic.PieChart.java

public static void NTPClient(String[] servers) {

    Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema
    defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses
    if (servers.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);/*from   w w w.j  a v  a2s  .co  m*/
    }

    Promedio = 0;
    Cant = 0;
    int j = 1;
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : servers) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info, j++);
            } catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
        }
    } catch (SocketException e) {
        System.err.println(e.toString());
    }

    client.close();
    //System.out.println("\n Pomedio "+(Promedio/Cant));
}

From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImpl.java

/**
 * Creates a DataSource with connection pooling as provided by Apache DBCP
 *
 * @return a DataSource/*from w  ww .  j  a  va 2 s . c o m*/
 */
public static DataSource configureAndCreateDataSource() {

    log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader");

    GlobalConfiguration globalConfiguration = GlobalConfigurationImpl.getInstance();

    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();

    log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath);
    // Creates a new class loader, which will be used for loading our JDBC driver
    URLClassLoader urlClassLoader = getOxalisClassLoaderForJdbc(jdbcDriverClassPath);

    String className = globalConfiguration.getJdbcDriverClassName();
    String connectURI = globalConfiguration.getJdbcConnectionURI();
    String userName = globalConfiguration.getJdbcUsername();
    String password = globalConfiguration.getJdbcPassword();

    log.debug("className=" + className);
    log.debug("connectURI=" + connectURI);
    log.debug("userName=" + userName);
    log.debug("password=" + password);

    // Loads the JDBC Driver in a separate class loader
    Driver driver = getJdbcDriver(jdbcDriverClassPath, urlClassLoader, className);

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);

    // DBCP factory which will produce JDBC Driver instances
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties);

    // DBCP object pool holding our driver connections
    GenericObjectPool genericObjectPool = new GenericObjectPool(null);
    genericObjectPool.setMaxActive(100);
    genericObjectPool.setMaxIdle(30);
    genericObjectPool.setMaxWait(10000);

    genericObjectPool.setTestOnBorrow(true); // Test the connection returned from the pool

    genericObjectPool.setTestWhileIdle(true); // Test idle instances visited by the pool maintenance thread and destroy any that fail validation
    genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); // Test every hour

    // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            genericObjectPool, null, null, false, true);

    String validationQuery = globalConfiguration.getValidationQuery();
    poolableConnectionFactory.setValidationQuery(validationQuery);

    // Creates the actual DataSource instance
    PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool);

    return poolingDataSource;

}

From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java

private static long runTest(String testMessage) throws SerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    properties.put("useStrictParser", "true");
    properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource", SchemaUrl);
    stopwatch.start();/*  w ww  .java2  s.c o m*/
    NCPDPSerializer serializer = new NCPDPSerializer(properties);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.toXML(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:arena.mail.MailSender.java

protected static Session makeSession(String smtpServer, String smtpServerDelimiter,
        Properties extraMailProperties) {
    Properties mailProps = new Properties();
    mailProps.put("mail.transport.protocol", "smtp");

    // Support alternate syntax for core properties: "server,user,pass,localhost"
    StringTokenizer st = new StringTokenizer(smtpServer, smtpServerDelimiter);
    String property = null;/*from ww w .j  a v  a  2  s.  com*/
    for (int i = 0; st.hasMoreElements(); i++) {
        property = st.nextToken();

        if (!property.trim().equals("")) {
            mailProps.put(PROPS_KEYS[i], property);
        }
    }
    if (extraMailProperties != null) {
        mailProps.putAll(extraMailProperties);
    }

    LogFactory.getLog(MailSender.class)
            .debug("mailProps['mail.smtp.host'] ->" + mailProps.getProperty("mail.smtp.host"));
    return Session.getInstance(mailProps, null);
}

From source file:NotificationMessage.java

static void sendMail(String toUser, Severity s) {
    // Recipient's email ID needs to be mentioned.
    //String to = "abhiyank@gmail.com";//change accordingly

    // Sender's email ID needs to be mentioned
    String from = "mdtprojectteam16@gmail.com";//change accordingly
    final String username = "mdtprojectteam16";//change accordingly
    final String password = "mdtProject16";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from  w  w w . j av a 2  s  . co m
    });

    try {
        // Create a default MimeMessage object.
        javax.mail.Message message1 = new MimeMessage(session);

        // Set From: header field of the header.
        message1.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));

        // Set Subject: header field
        message1.setSubject("Alert Message From Patient");

        // Now set the actual message
        message1.setText(messageMap.get(s));

        // Send message
        Transport.send(message1);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.unigoettingen.sub.commons.util.stream.StreamUtils.java

/************************************************************************************
 * get MimeType as {@link String} from given URL including proxy details
 * /*from   www . ja va  2  s .  c  o  m*/
 * @param url the url from where to get the MimeType
 * @param httpproxyhost host of proxy
 * @param httpproxyport port of proxy
 * @param httpproxyusername username for proxy
 * @param httpproxypassword password for proxy
 * @return MimeType as {@link String}
 * @throws IOException
 ************************************************************************************/

public static String getMimeTypeFromUrl(URL url, String httpproxyhost, String httpproxyport,
        String httpproxyusername, String httpproxypassword) throws IOException {
    if (httpproxyhost != null) {
        Properties properties = System.getProperties();
        properties.put("http.proxyHost", httpproxyhost);
        if (httpproxyport != null) {
            properties.put("http.proxyPort", httpproxyport);
        } else {
            properties.put("http.proxyPort", "80");
        }
    }
    URLConnection con = url.openConnection();
    if (httpproxyusername != null) {
        String login = httpproxyusername + ":" + httpproxypassword;
        String encodedLogin = new String(Base64.encodeBase64(login.getBytes()));
        con.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
    }
    return con.getContentType();
}

From source file:ntpgraphic.LineChart.java

public static void NTPClient(String[] servers, int i) {

    Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema
    defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses
    if (servers.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);/*from   ww w .j av a  2  s  .c  om*/
    }

    Promedio = 0;
    Cant = 0;
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : servers) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info, i);
            } catch (IOException ioe) {
                System.err.println(ioe.toString());
            }
        }
    } catch (SocketException e) {
        System.err.println(e.toString());
    }

    client.close();
    //System.out.println("\n Pomedio "+(Promedio/Cant));
}

From source file:dk.netarkivet.common.utils.EMailUtils.java

/**
 * Send an email, possibly forgiving errors.
 *
 * @param to The recipient of the email. Separate multiple recipients with
 *           commas. Supports only adresses of the type 'john@doe.dk', not
 *           'John Doe <john@doe.dk>'
 * @param from The sender of the email./*www. j  av  a 2  s . co  m*/
 * @param subject The subject of the email.
 * @param body The body of the email.
 * @param forgive On true, will send the email even on invalid email
 *        addresses, if at least one recipient can be set, on false, will
 *        throw exceptions on any invalid email address.
 *
 *
 * @throws ArgumentNotValid If either parameter is null, if to, from or
 *                          subject is the empty string, or no recipient
 *                          can be set. If "forgive" is false, also on
 *                          any invalid to or from address.
 * @throws IOFailure If the message cannot be sent for some reason.
 */
public static void sendEmail(String to, String from, String subject, String body, boolean forgive) {
    ArgumentNotValid.checkNotNullOrEmpty(to, "String to");
    ArgumentNotValid.checkNotNullOrEmpty(from, "String from");
    ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject");
    ArgumentNotValid.checkNotNull(body, "String body");

    Properties props = new Properties();
    props.put(MAIL_FROM_PROPERTY_KEY, from);
    props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER));

    Session session = Session.getDefaultInstance(props);
    Message msg = new MimeMessage(session);

    // to might contain more than one e-mail address
    for (String toAddressS : to.split(",")) {
        try {
            InternetAddress toAddress = new InternetAddress(toAddressS.trim());
            msg.addRecipient(Message.RecipientType.TO, toAddress);
        } catch (AddressException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address",
                        e);
            }
        } catch (MessagingException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' could not be set in email", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e);
            }
        }
    }
    try {
        if (msg.getAllRecipients().length == 0) {
            throw new ArgumentNotValid("No valid recipients in '" + to + "'");
        }
    } catch (MessagingException e) {
        throw new ArgumentNotValid("Message invalid after setting" + " recipients", e);
    }

    try {
        InternetAddress fromAddress = null;
        fromAddress = new InternetAddress(from);
        msg.setFrom(fromAddress);
    } catch (AddressException e) {
        throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e);
    } catch (MessagingException e) {
        if (forgive) {
            log.warn("From address '" + from + "' could not be set in email", e);
        } else {
            throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e);
        }
    }

    try {
        msg.setSubject(subject);
        msg.setContent(body, MIMETYPE);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to
                + "'. Body:\n" + body, e);
    }
}

From source file:com.kixeye.chassis.bootstrap.TestUtils.java

@SuppressWarnings("unchecked")
public static void writePropertiesToFile(String path, Set<Path> filesCreated,
        SimpleEntry<String, String>... entries) {
    Properties properties = new Properties();
    for (SimpleEntry<String, String> entry : entries) {
        properties.put(entry.getKey(), entry.getValue());
    }// www.j  a v a 2  s .c  om
    Path p = Paths.get(SystemPropertyUtils.resolvePlaceholders(path));
    try (OutputStream os = createFile(p.toString())) {
        properties.store(os, "test properties");
        filesCreated.add(p);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*from   www . j  av a 2s .  c  o m*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

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

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}