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:cn.ict.zyq.bestConf.cluster.Utils.RemoteFileAccess.java

public void download(SFtpConnectInfo connectInfo, String localPath, final String remotePath) {
    JSch jsch = new JSch();
    Session session = null;//from  w  w  w  .j  ava 2s .  com
    ChannelSftp channel = null;
    OutputStream outs = null;
    try {
        session = jsch.getSession(connectInfo.getUsername(), connectInfo.getHost(), connectInfo.getPort());
        session.setPassword(connectInfo.getPassword());
        Properties props = new Properties();
        props.put("StrictHostKeyChecking", "no");
        session.setConfig(props);
        session.connect(5000);
        channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect(5000);
        outs = new BufferedOutputStream(new FileOutputStream(new File(localPath)));
        channel.get(remotePath, outs, new SftpProgressMonitor() {

            private long current = 0;

            @Override
            public void init(int op, String src, String dest, long max) {

            }

            @Override
            public void end() {

            }

            @Override
            public boolean count(long count) {
                current += count;

                return true;
            }
        });
    } catch (JSchException e) {
        System.err.println(String.format(
                "connect remote host[%s:%d] occurs error " + connectInfo.getHost() + +connectInfo.getPort()));
        e.printStackTrace();
    } catch (SftpException e) {
        System.err.println(String.format("get remote file:%s occurs error", remotePath));
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.err.println(String.format("can not find local file:%s", localPath));
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(outs);
        if (null != channel) {
            channel.disconnect();
        }
        if (null != session) {
            session.disconnect();
        }
    }
}

From source file:com.carrotgarden.maven.aws.grv.TestCarrotGroovyRunner.java

@Test
public void testString() throws Exception {

    final Properties properties = new Properties();
    properties.put("prop-key", "prop-value-1");

    assertEquals(properties.get("prop-key"), "prop-value-1");

    final MavenProject project = mock(MavenProject.class);

    when(project.getProperties()).thenReturn(properties);

    final CarrotGroovyRunner runner = new CarrotGroovyRunner(project);

    final File file = new File("./src/test/resources/script.groovy");

    final String script = FileUtils.readFileToString(file);

    final Object result = runner.execute(script);

    assertEquals(result, "result");

    assertEquals(properties.get("prop-key"), "prop-value-2");

}

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/*  ww w  .  ja v a  2 s. co  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 boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session 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$
    }

    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 {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        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);
        }

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

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

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

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

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException 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 ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}

From source file:org.springframework.social.vkontakte.api.impl.WallTemplate.java

public Post getPost(String userId, String postId) {
    requireAuthorization();//from  w  w  w .  j  av a  2s. com
    Properties props = new Properties();
    props.put("posts", userId + "_" + postId);

    // http://vk.com/dev/wall.getById
    URI uri = makeOperationURL("wall.getById", props, ApiVersion.VERSION_5_27);
    VKGenericResponse response = restTemplate.getForObject(uri, VKGenericResponse.class);
    checkForError(response);
    try {
        return objectMapper.readValue(response.getResponse().get(0).toString(), Post.class);
    } catch (IOException e) {
        throw new UncategorizedApiException("vkontakte", "Error deserializing: " + response.getResponse(), e);
    }
}

From source file:de.iritgo.aktario.jdbc.LoadAllUsers.java

/**
 * Perform the command./* w w  w  . j a  v  a 2s .c o  m*/
 */
public void perform() {
    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    final UserRegistry userRegistry = Server.instance().getUserRegistry();

    try {
        QueryRunner query = new QueryRunner(dataSource);
        List userIds = (List) query.query("select id from IritgoUser", new ArrayListHandler());

        for (Iterator i = userIds.iterator(); i.hasNext();) {
            Long userId = (Long) ((Object[]) i.next())[0];

            Properties props = new Properties();

            props.put("id", userId);
            CommandTools.performSimple("persist.LoadUser", props);
        }

        Log.logVerbose("persist", "LoadAllUsers", "Successfully loaded " + userIds.size() + " users");
    } catch (Exception x) {
        Log.logError("persist", "LoadAllUsers", "Error while loading the users: " + x);
    }
}

From source file:com.github.javarch.support.config.EMailConfig.java

protected Properties mailProperties() {
    Properties javaMailProperties = new Properties();

    javaMailProperties.put("mail.smtp.auth", env.getProperty("mail.smtp.auth", Boolean.class, false));
    javaMailProperties.put("mail.smtp.starttls.enable",
            env.getProperty("mail.smtp.starttls.enable", Boolean.class, false));

    return javaMailProperties;
}

From source file:reviewbot.configuration.DatabaseConfig.java

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource());
    sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
    Properties hibernateProperties = new Properties();
    hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
    hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
    hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
    sessionFactoryBean.setHibernateProperties(hibernateProperties);

    return sessionFactoryBean;
}

From source file:io.gravitee.repository.jdbc.config.JdbcRepositoryConfiguration.java

@Bean
public LocalContainerEntityManagerFactoryBean graviteeEntityManagerFactory(DataSource dataSource) {
    final Properties hibernateProperties = new Properties();
    hibernateProperties.put("hibernate.show_sql", showSql);

    final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("io.gravitee.repository.jdbc.model");
    entityManagerFactoryBean.setJpaProperties(hibernateProperties);
    entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
    entityManagerFactoryBean.setPersistenceUnitName("graviteePU");
    entityManagerFactoryBean.setDataSource(dataSource);
    return entityManagerFactoryBean;
}

From source file:ar.com.zauber.commons.web.proxy.impl.dao.properties.PropertiesChainedRegexURLRequestMapperDAOTest.java

/** @throws Exception on error */
public final void testLoad() throws Exception {
    final Properties p = new Properties();
    p.put("0", "^/nexus/(.*)$=http://localhost:9095/nexus/$1");
    p.put("1", "^/([^/]+)/([^/]+)/([^/]+)/(.*)$"
            + "=http://localhost:9095/nexus/content/repositories/$1-$2-$3/$4");

    final PropertiesChainedRegexURLRequestMapperDAO dao = new PropertiesChainedRegexURLRequestMapperDAO(
            new SimplePropertiesProvider(p), new NullPropertiesPersister());

    final URLRequestMapper c = dao.load();
    assertFalse(c.getProxiedURLFromRequest(new MockHttpServletRequest("GET", "/foo")).hasResult());
    assertEquals(new URL("http://localhost:9095/nexus/foo/bar"),
            c.getProxiedURLFromRequest(new MockHttpServletRequest("GET", "/nexus/foo/bar")).getURL());
    assertEquals(new URL("http://localhost:9095/nexus/content/repositories/" + "zauber-code-releases/foo/bar"),
            c.getProxiedURLFromRequest(new MockHttpServletRequest("GET", "/zauber/code/releases/foo/bar"))
                    .getURL());/*from w w w  . java2  s  .c o m*/
}

From source file:io.joynr.messaging.http.UrlResolverTest.java

@Before
public void setUp() throws Exception {

    Properties properties = new Properties();
    properties.put(MessagingPropertyKeys.CHANNELID, channelId);

    Injector injector = Guice.createInjector(new JoynrPropertiesModule(properties), new MessagingTestModule(),
            new AtmosphereMessagingModule(), new AbstractModule() {
                @Override//w w  w.  j av a2  s .co m
                protected void configure() {
                    bind(RequestConfig.class).toProvider(HttpDefaultRequestConfigProvider.class)
                            .in(Singleton.class);
                    bind(LocalChannelUrlDirectoryClient.class).to(DummyLocalChannelUrlDirectoryClient.class);
                }
            });
    urlResolver = injector.getInstance(UrlResolver.class);
}