示例#1
0
  public static Properties getCyclosProperties() throws IOException {
    final Properties properties = new Properties();
    properties.put(MAX_MAIL_SENDER_THREADS, "5");
    properties.put(MAX_SMS_SENDER_THREADS, "50");
    properties.put(MAX_PAYMENT_REQUEST_SENDER_THREADS, "50");

    properties.load(CyclosConfiguration.class.getResourceAsStream(CYCLOS_PROPERTIES_FILE));

    final String dbMaxPoolSizeStr = properties.getProperty(HIBERNATE_C3P0_MAX_POOL_SIZE);
    final Integer dbMaxPoolSize =
        StringUtils.isEmpty(dbMaxPoolSizeStr)
            ? HIBERNATE_C3P0_MAX_POOL_SIZE_DEFAULT
            : Integer.parseInt(dbMaxPoolSizeStr);

    ensureProperty(TRANSACTION_CORE_POOL_SIZE, dbMaxPoolSize, properties);
    ensureProperty(TRANSACTION_MAX_POOL_SIZE, dbMaxPoolSize * 3, properties);
    ensureProperty(TRANSACTION_QUEUE_CAPACITY, dbMaxPoolSize * 5, properties);

    if (!properties.containsKey(Environment.HBM2DDL_AUTO)) {
      properties.put(Environment.HBM2DDL_AUTO, "validate");
    }
    if (!properties.containsKey(SCHEMA_EXPORT_FILE)) {
      properties.put(SCHEMA_EXPORT_FILE, DEFAULT_SCHEMA_EXPORT_FILE);
    }

    return properties;
  }
  public DigitalLibraryServer() {
    try {
      Properties properties = new Properties();
      properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
      properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
      properties.put(Context.PROVIDER_URL, "localhost");

      InitialContext jndi = new InitialContext(properties);
      ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory");
      connection = conFactory.createConnection();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      try {
        counterTopic = (Topic) jndi.lookup("counterTopic");
      } catch (NamingException NE1) {
        System.out.println("NamingException: " + NE1 + " : Continuing anyway...");
      }

      if (null == counterTopic) {
        counterTopic = session.createTopic("counterTopic");
        jndi.bind("counterTopic", counterTopic);
      }

      consumer = session.createConsumer(counterTopic);
      consumer.setMessageListener(this);
      System.out.println("Server started waiting for client requests");
      connection.start();
    } catch (NamingException NE) {
      System.out.println("Naming Exception: " + NE);
    } catch (JMSException JMSE) {
      System.out.println("JMS Exception: " + JMSE);
      JMSE.printStackTrace();
    }
  }
示例#3
0
  public static Session createSmtpSession(
      String host, Integer port, boolean tls, String user, String password) {
    if (Str.isBlank(host)) throw new IllegalArgumentException("host ist blank");

    if (Str.isBlank(user)) user = null;
    if (Str.isBlank(password)) password = null;

    Properties p = new Properties();
    p.setProperty("mail.mime.charset", charset);
    p.setProperty("mail.transport.protocol", "smtp");
    p.setProperty("mail.smtp.host", host);
    if (port != null) p.put("mail.smtp.port", port);
    p.put("mail.smtp.starttls.enable", String.valueOf(tls));

    boolean auth = user != null && password != null;
    p.setProperty("mail.smtp.auth", String.valueOf(auth));
    if (user != null) p.setProperty("mail.smtp.auth.user", user);
    if (password != null) p.setProperty("mail.smtp.auth.password", password);

    Session session = Session.getInstance(p);

    if (auth) {
      session.setPasswordAuthentication(
          new URLName("local"), new PasswordAuthentication(user, password));
    }

    return session;
  }
 static {
   properties.put("mail.smtp.host", "smtp.gmail.com");
   properties.put("mail.smtp.socketFactory.port", "465");
   properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   properties.put("mail.smtp.auth", "true");
   properties.put("mail.smtp.port", "465");
 }
示例#5
0
  public static void sendConfirmationRegisterMail(String mail, String name)
      throws UnsupportedEncodingException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
              }
            });

    String msgBody = "The staff wish you enjoy the contest!";

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(FROM_ADDRESS, FROM_NAME));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, name));
    msg.setSubject("Welcome to pContest!");
    msg.setText(msgBody);
    Transport.send(msg);
  }
示例#6
0
  public static void main(String[] args) {
    java.util.Properties props = new Properties();
    props.putAll(System.getProperties());
    props.put("org.omg.CORBA.ORBClass", "org.apache.yoko.orb.CORBA.ORB");
    props.put("org.omg.CORBA.ORBSingletonClass", "org.apache.yoko.orb.CORBA.ORBSingleton");

    int status = 0;
    ORB orb = null;

    try {
      orb = ORB.init(args, props);
      status = run(orb, false, args);
    } catch (Exception ex) {
      ex.printStackTrace();
      status = 1;
    }

    if (orb != null) {
      try {
        orb.destroy();
      } catch (Exception ex) {
        ex.printStackTrace();
        status = 1;
      }
    }

    System.exit(status);
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.sakaiproject.nakamura.api.message.LiteMessageTransport#send(org.sakaiproject.nakamura.api.message.MessageRoutes,
   *     org.osgi.service.event.Event, org.sakaiproject.nakamura.api.lite.content.Content)
   */
  public void send(MessageRoutes routes, Event event, Content message) {
    LOGGER.debug("Started handling an email message");

    // delay list instantiation to save object creation when not needed.
    List<String> recipients = null;
    for (MessageRoute route : routes) {
      if (TYPE.equals(route.getTransport())) {
        if (recipients == null) {
          recipients = new ArrayList<String>();
        }
        recipients.add(route.getRcpt());
      }
    }

    if (recipients != null) {
      Properties props = new Properties();
      if (event != null) {
        for (String propName : event.getPropertyNames()) {
          Object propValue = event.getProperty(propName);
          props.put(propName, propValue);
        }
      }
      // make the message deliver to one listener, that means the desination must be a queue.
      props.put(EventDeliveryConstants.DELIVERY_MODE, EventDeliveryMode.P2P);
      // make the message persistent to survive restarts.
      props.put(EventDeliveryConstants.MESSAGE_MODE, EventMessageMode.PERSISTENT);
      props.put(LiteOutgoingEmailMessageListener.RECIPIENTS, recipients);
      props.put(LiteOutgoingEmailMessageListener.CONTENT_PATH_PROPERTY, message.getPath());
      Event emailEvent = new Event(LiteOutgoingEmailMessageListener.QUEUE_NAME, (Map) props);

      LOGGER.debug("Sending event [" + emailEvent + "]");
      eventAdmin.postEvent(emailEvent);
    }
  }
  public void setup() throws Exception {

    setupProperties();

    ReportDefinition rd = createReportDefinition();

    ReportDesign design =
        h.createRowPerPatientXlsOverviewReportDesign(
            rd,
            "ChemotherapyDailyExpectedPatientList.xls",
            "ChemotherapyDailyPatientList.xls_",
            null);

    Properties props = new Properties();
    props.put("repeatingSections", "sheet:1,row:7,dataset:dataSet");
    props.put("sortWeight", "5000");
    design.setProperties(props);

    h.saveReportDesign(design);

    ReportDesign designTwo =
        h.createRowPerPatientXlsOverviewReportDesign(
            rd,
            "ChemotherapyDailyTreatmentSummary.xls",
            "ChemotherapyDailyTreatmentSummary.xls_",
            null);

    Properties propsTwo = new Properties();
    propsTwo.put("repeatingSections", "sheet:1,row:7,dataset:dataSet");
    props.put("sortWeight", "5000");
    designTwo.setProperties(propsTwo);

    h.saveReportDesign(designTwo);
  }
 /**
  * Overrides the base implementation to add in new parameters to the return url
  *
  * <ul>
  *   <li>{@link KFSConstants.DISPATCH_REQUEST_PARAMETER}
  *   <li>{@link KFSConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE}
  *   <li>{@link KFSConstants.OVERRIDE_KEYS}
  * </ul>
  *
  * {@link KFSConstants.DISPATCH_REQUEST_PARAMETER}
  *
  * @see
  *     org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getReturnUrl(org.kuali.rice.kns.bo.BusinessObject,
  *     java.util.Map, java.lang.String)
  */
 @Override
 public HtmlData getReturnUrl(
     BusinessObject businessObject,
     LookupForm lookupForm,
     List returnKeys,
     BusinessObjectRestrictions businessObjectRestrictions) {
   Properties parameters =
       getParameters(
           businessObject,
           lookupForm.getFieldConversions(),
           lookupForm.getLookupableImplServiceName(),
           returnKeys);
   parameters.put(
       KFSConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.MAINTENANCE_NEWWITHEXISTING_ACTION);
   parameters.put(
       KFSConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE, AccountDelegateGlobal.class.getName());
   parameters.put(
       KFSConstants.OVERRIDE_KEYS,
       "modelName"
           + KFSConstants.FIELD_CONVERSIONS_SEPERATOR
           + "modelChartOfAccountsCode"
           + KFSConstants.FIELD_CONVERSIONS_SEPERATOR
           + "modelOrganizationCode");
   setBackLocation(KFSConstants.MAINTENANCE_ACTION);
   return getReturnAnchorHtmlData(
       businessObject, parameters, lookupForm, returnKeys, businessObjectRestrictions);
 }
  public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session =
        Session.getInstance(
            properties,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "test123");
              }
            });

    try {

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
      message.setSubject("Reset Password");
      String content = "Your new password is " + password;
      message.setText(content);
      Transport.send(message);

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
  public void postMail(String recipients[], String subject, String message, String from)
      throws MessagingException {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.timeout", 60000);

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

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

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html");
    Transport.send(msg);
  }
示例#12
0
  protected Spammer() throws MailException {
    final boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);

    final String hostProperty = this.hostProperty(ssl);
    final String portProperty = this.portProperty(ssl);
    final String authProperty = this.authProperty(ssl);
    final String localhostProperty = this.localhostProperty(ssl);

    mailProps.put(hostProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST));
    mailProps.put(portProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PORT));

    String localhost = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_LOCALHOST);

    if (StringUtils.isNotEmpty(localhost)) {
      LOGGER.debug("localhost=" + localhost);
      mailProps.put(localhostProperty, localhost);
    }

    mailProps.put("mail.mime.address.strict", "false");
    mailProps.put("mail.mime.charset", SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
    mailProps.put(authProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_AUTH));

    username = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
    password = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);

    messageFormat =
        SystemGlobals.getValue(ConfigKeys.MAIL_MESSSAGE_FORMAT).equals("html")
            ? MESSAGE_HTML
            : MESSAGE_TEXT;

    this.session = Session.getInstance(mailProps);
  }
  private Properties getModelConnectionProperties(ModelResource mr) {

    try {
      if (ModelIdentifier.isRelationalSourceModel(mr)) {
        IConnectionInfoProvider provider = null;

        try {
          provider = getProvider(mr);
        } catch (Exception e) {
          // If provider throws exception its OK because some models may not have connection info.
        }

        if (provider != null) {
          Properties properties = provider.getProfileProperties(mr); // ConnectionProperties(mr);
          Properties p2 = provider.getConnectionProperties(mr);
          String translatorName = provider.getTranslatorName(mr);
          for (Object key : p2.keySet()) {
            properties.put(key, p2.get(key));
          }
          if (translatorName != null) {
            properties.put(getString("translatorKey"), translatorName); // $NON-NLS-1$
          }
          if (properties != null && !properties.isEmpty()) {
            return properties;
          }
        }
      }
    } catch (CoreException e) {
      DatatoolsUiConstants.UTIL.log(e);
    }

    return null;
  }
  private void generateSvrReport(String path) {
    if (loadConfig(path)) {
      ssoToken = getAdminSSOToken();
      if (ssoToken != null) {
        // All the properties should be loaded at this point
        Properties prop = SystemProperties.getAll();
        Properties amProp = new Properties();
        Properties sysProp = new Properties();

        for (Enumeration e = prop.propertyNames(); e.hasMoreElements(); ) {
          String key = (String) e.nextElement();
          String val = (String) prop.getProperty(key);
          if (key.startsWith(AM_PROP_SUN_SUFFIX)
              || key.startsWith(AM_PROP_SUFFIX)
              || key.startsWith(ENC_PWD_PROPERTY)) {
            amProp.put(key, val);
          } else {
            sysProp.put(key, val);
          }
        }
        printProperties(amProp, DEF_PROP);
        printProperties(sysProp, SYS_PROP);
        getInstanceProperties(ssoToken);
      } else {
        toolOutWriter.printError("rpt-auth-msg");
      }
    } else {
      toolOutWriter.printStatusMsg(false, "rpt-svr-gen");
    }
  }
示例#15
0
  public static void SendMail(String to, String subject, String Content) {
    try {

      // setup the mail server properties
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");

      // set up the message
      Session session = Session.getInstance(props);

      Message message = new MimeMessage(session);

      // add a TO address
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

      // add a multiple CC addresses
      // message.setRecipients(Message.RecipientType.CC,
      // InternetAddress.parse("[email protected],[email protected]"));

      message.setSubject(subject);
      message.setContent(Content, "text/plain");

      Transport transport = session.getTransport("smtp");
      transport.connect("smtp.gmail.com", 587, "aaa", "pass");
      transport.sendMessage(message, message.getAllRecipients());
      // System.out.println("Send email via gmail...");
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
 public Properties getHibernateProperties() {
   Properties properties = new Properties();
   properties.put("hibernate.show_sql", "true");
   properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
   properties.put("hibernate.current_session_context_class", "thread");
   return properties;
 }
 private Properties makeSampleProperties() {
   Properties props = new Properties();
   props.put("Key1", "value1");
   props.put("Key2", "value2");
   props.put("Key3", "false");
   return props;
 }
示例#18
0
  public static Map<String, Properties> loadDBConfig(Properties p) {
    Map<String, Properties> dbConfigs = Maps.newHashMapWithExpectedSize(1);
    for (Object o : p.keySet()) {
      String _key = String.valueOf(o);
      String value = p.getProperty(_key);

      if (StringUtils.startsWithIgnoreCase(_key, "db")) {
        int last_idx = _key.lastIndexOf(StringPool.DOT);
        if (last_idx > 2) {
          // like db.second.url
          String config_name = _key.substring(_key.indexOf(StringPool.DOT) + 1, last_idx);
          if (logger.isDebugEnabled()) {
            logger.debug("the db config is {}", config_name);
          }
          Properties db_config_props = dbConfigs.get(config_name);
          if (db_config_props == null) {
            db_config_props = new Properties();
            dbConfigs.put(config_name, db_config_props);
          }
          _key = _key.replace(StringPool.DOT + config_name, StringPool.EMPTY);
          db_config_props.put(_key, value);
        } else {
          Properties db_main_props = dbConfigs.get("main");
          if (db_main_props == null) {
            db_main_props = new Properties();
            dbConfigs.put("main", db_main_props);
          }
          db_main_props.put(_key, value);
        }
      }
    }
    return dbConfigs;
  }
示例#19
0
  public void test() throws Exception {

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtps.quitwait", "false");
    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(true);

    Transport transport = mailSession.getTransport();
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(username.getText()));
    message.setSubject(subject.getText());

    String s = msgfield.getText();
    message.setContent(s, "text/plain");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailID.getText()));
    System.out.println("8i m here ");
    try {
      transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, username.getText(), password.getText());
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "invalid username or password");
    }
    System.out.println("8i m here also yaar");
    // transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.sendMessage(message123, message123.getAllRecipients());
    transport.close();
    System.out.println(s);
  }
示例#20
0
  @Override
  public synchronized void init(BundleContext context, DependencyManager manager) throws Exception {
    // Console registration
    Properties properties = new Properties();
    properties.put(Constants.SERVICE_PID, "it.hash.osgi.aws.console");
    manager.add(
        createComponent()
            .setInterface(
                new String[] {Console.class.getName(), ManagedService.class.getName()}, properties)
            .setImplementation(ConsoleImpl.class)
            .add(createServiceDependency().setService(LogService.class).setRequired(false)));

    // Shell Commands registration
    properties = new Properties();
    properties.put(CommandProcessor.COMMAND_SCOPE, "aws");
    properties.put(
        CommandProcessor.COMMAND_FUNCTION,
        new String[] {
          "ec2", "s3", "sdb", "ses", "sqs", "dyndb", "createtable", "putuser", "listusers"
        });
    manager.add(
        createComponent()
            .setInterface(Object.class.getName(), properties)
            .setImplementation(ShellCommands.class)
            .add(createServiceDependency().setService(Console.class).setRequired(true)));
  }
  @Test
  public void create_map_from_properties_java() {

    Properties properties = new Properties();
    properties.put("database.username", "yourname");
    properties.put("database.password", "encrypted_password");
    properties.put("database.driver", "com.mysql.jdbc.Driver");
    properties.put("database.url", "jdbc:mysql://localhost:3306/sakila?profileSQL=true");

    Map<String, String> mapOfProperties = new HashMap<String, String>();

    Enumeration<?> propertyNames = properties.propertyNames();

    while (propertyNames.hasMoreElements()) {
      String key = (String) propertyNames.nextElement();
      mapOfProperties.put(key, properties.getProperty(key));
    }

    logger.info(mapOfProperties);

    assertThat(
        mapOfProperties.keySet(),
        containsInAnyOrder(
            "database.username", "database.password", "database.driver", "database.url"));
  }
  @Test
  public void testCustomPartitionCountOverridesPartitioningIfLarger() throws Exception {

    byte[] ratherBigPayload = new byte[2048];
    Arrays.fill(ratherBigPayload, (byte) 65);
    KafkaTestBinder binder = (KafkaTestBinder) getBinder();

    DirectChannel moduleOutputChannel = new DirectChannel();
    QueueChannel moduleInputChannel = new QueueChannel();
    Properties producerProperties = new Properties();
    producerProperties.put(BinderProperties.MIN_PARTITION_COUNT, "5");
    producerProperties.put(BinderProperties.NEXT_MODULE_COUNT, "3");
    producerProperties.put(BinderProperties.PARTITION_KEY_EXPRESSION, "payload");
    Properties consumerProperties = new Properties();
    consumerProperties.put(BinderProperties.MIN_PARTITION_COUNT, "5");
    long uniqueBindingId = System.currentTimeMillis();
    binder.bindProducer("foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties);
    binder.bindConsumer("foo" + uniqueBindingId + ".0", moduleInputChannel, consumerProperties);
    Message<?> message =
        org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload)
            .build();
    // Let the consumer actually bind to the producer before sending a msg
    binderBindUnbindLatency();
    moduleOutputChannel.send(message);
    Message<?> inbound = moduleInputChannel.receive(2000);
    assertNotNull(inbound);
    assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload());
    Collection<Partition> partitions =
        binder.getCoreBinder().getConnectionFactory().getPartitions("foo" + uniqueBindingId + ".0");
    assertThat(partitions, hasSize(5));
    binder.unbindProducers("foo" + uniqueBindingId + ".0");
    binder.unbindConsumers("foo" + uniqueBindingId + ".0");
  }
示例#23
0
  /**
   * Получение соединения внутри сервлета
   *
   * @param servletContext
   * @return
   * @throws SQLException
   */
  public static Connection getConnection(ServletContext servletContext) throws SQLException {

    Connection connection = null;

    //
    String connectionUrl = servletContext.getInitParameter("webdicom.connection.url");
    if (connectionUrl != null) {
      Properties props = new Properties(); // connection properties
      props.put("user", "user1"); // FIXME взять из конфига
      props.put("password", "user1"); // FIXME взять из конфига

      connection = DriverManager.getConnection(connectionUrl + ";create=true", props);
    } else {
      // for Tomcat
      try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource) envCtx.lookup("jdbc/webdicom");
        connection = ds.getConnection();
      } catch (NamingException e) {
        throw new SQLException("JNDI error " + e);
      }
    }

    return connection;
  }
  public static void main(String[] args) {

    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.FSContextFactory");
    props.put(Context.PROVIDER_URL, "file:///");

    try {
      Context ctx = new InitialContext(props);
      System.out.println("Contexto obetido com sucesso");

      if (args[1].equals("-t")) {
        buscaTodosArquivo(ctx, 1, args[0]);
      }

      if (args[1].equals("-p")) {
        buscaArquivo(ctx, 1, args[0]);
      }

    } catch (NamingException e) {
      e.printStackTrace();
    }

    if (!achou) {
      System.out.println("não encontrou");
    }

    System.out.println("Finalizou");
  }
示例#25
0
 static {
   defaults.put("rpc.ntlm.lanManagerKey", "false");
   defaults.put("rpc.ntlm.sign", "false");
   defaults.put("rpc.ntlm.seal", "false");
   defaults.put("rpc.ntlm.keyExchange", "false");
   defaults.put("rpc.connectionContext", "rpc.security.ntlm.NtlmConnectionContext");
 }
示例#26
0
  public static void sendEmail(String toEmail, String subject, String body) {
    try {

      Properties props = System.getProperties();
      props.put("mail.smtp.host", "mail.excellenceserver.com"); // SMTP Host
      //	        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
      props.put("mail.smtp.port", "27"); // TLS Port
      props.put("mail.smtp.auth", "true"); // enable authentication
      props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS

      Authenticator auth =
          new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication("*****@*****.**", "user@#123");
            }
          };
      Session session = Session.getInstance(props, auth);

      MimeMessage msg = new MimeMessage(session);
      // set message headers
      msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
      msg.addHeader("format", "flowed");
      msg.addHeader("Content-Transfer-Encoding", "8bit");
      msg.setFrom(new InternetAddress("*****@*****.**", "user@#123"));
      msg.setReplyTo(InternetAddress.parse("*****@*****.**", false));
      msg.setSubject(subject, "UTF-8");
      msg.setText(body, "UTF-8");
      msg.setSentDate(new Date());
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

      Transport.send(msg);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public static void loadVMProfile(Properties properties) {
   Properties profileProps = findVMProfile(properties);
   String systemExports = properties.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES);
   // set the system exports property using the vm profile; only if the property is not already set
   if (systemExports == null) {
     systemExports = profileProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES);
     if (systemExports != null) properties.put(Constants.FRAMEWORK_SYSTEMPACKAGES, systemExports);
   }
   // set the org.osgi.framework.bootdelegation property according to the java profile
   String type =
       properties.getProperty(
           Constants.OSGI_JAVA_PROFILE_BOOTDELEGATION); // a null value means ignore
   String profileBootDelegation = profileProps.getProperty(Constants.FRAMEWORK_BOOTDELEGATION);
   if (Constants.OSGI_BOOTDELEGATION_OVERRIDE.equals(type)) {
     if (profileBootDelegation == null)
       properties.remove(Constants.FRAMEWORK_BOOTDELEGATION); // override with a null value
     else
       properties.put(
           Constants.FRAMEWORK_BOOTDELEGATION,
           profileBootDelegation); // override with the profile value
   } else if (Constants.OSGI_BOOTDELEGATION_NONE.equals(type))
     properties.remove(
         Constants
             .FRAMEWORK_BOOTDELEGATION); // remove the bootdelegation property in case it was set
   // set the org.osgi.framework.executionenvironment property according to the java profile
   if (properties.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT) == null) {
     // get the ee from the java profile; if no ee is defined then try the java profile name
     String ee =
         profileProps.getProperty(
             Constants.FRAMEWORK_EXECUTIONENVIRONMENT,
             profileProps.getProperty(Constants.OSGI_JAVA_PROFILE_NAME));
     if (ee != null) properties.put(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, ee);
   }
 }
  private static ConsumerConfig createConsumerConfig(
      String zookeeper, String groupId, String optionalConfigs) {
    try {
      Properties props = new Properties();
      props.put(KafkaEventAdapterConstants.ADAPTOR_SUSCRIBER_ZOOKEEPER_CONNECT, zookeeper);
      props.put(KafkaEventAdapterConstants.ADAPTOR_SUSCRIBER_GROUP_ID, groupId);

      if (optionalConfigs != null) {
        String[] optionalProperties = optionalConfigs.split(",");

        if (optionalProperties != null && optionalProperties.length > 0) {
          for (String header : optionalProperties) {
            String[] configPropertyWithValue = header.split(":", 2);
            if (configPropertyWithValue.length == 2) {
              props.put(configPropertyWithValue[0], configPropertyWithValue[1]);
            } else {
              log.warn(
                  "Optional configuration property not defined in the correct format.\nRequired - property_name1:property_value1,property_name2:property_value2\nFound - "
                      + optionalConfigs);
            }
          }
        }
      }
      return new ConsumerConfig(props);
    } catch (NoClassDefFoundError e) {
      throw new InputEventAdapterRuntimeException(
          "Cannot access kafka context due to missing jars", e);
    }
  }
 public EmailChannel(String configuration) {
   Properties props = new Properties();
   try {
     props.load(new StringReader(configuration));
   } catch (IOException e) {
     // really shouldn't happen
     throw new IllegalStateException(
         "Bug: can't load email properties " + "for the channel instance", e);
   }
   String smtpUser = props.getProperty(CFG_USER);
   String smtpPassword = props.getProperty(CFG_PASSWD);
   Authenticator smtpAuthn =
       (smtpUser != null && smtpPassword != null)
           ? new SimpleAuthenticator(smtpUser, smtpPassword)
           : null;
   String trustAll = props.getProperty(CFG_TRUST_ALL);
   if (trustAll != null && "true".equalsIgnoreCase(trustAll)) {
     MailSSLSocketFactory trustAllSF;
     try {
       trustAllSF = new MailSSLSocketFactory();
     } catch (GeneralSecurityException e) {
       // really shouldn't happen
       throw new IllegalStateException("Can't init trust-all SSL socket factory", e);
     }
     trustAllSF.setTrustAllHosts(true);
     props.put("mail.smtp.ssl.socketFactory", trustAllSF);
   } else {
     X509CertChainValidator validator = pkiManagement.getMainAuthnAndTrust().getValidator();
     SSLSocketFactory factory = SocketFactoryCreator.getSocketFactory(null, validator);
     props.put("mail.smtp.ssl.socketFactory", factory);
   }
   session = Session.getInstance(props, smtpAuthn);
 }
  /**
   * Transform JNDI properties passed in the form <tt>hibernate.jndi.*</tt> to the format accepted
   * by <tt>InitialContext</tt> by triming the leading "<tt>hibernate.jndi</tt>".
   */
  public static Properties getJndiProperties(Properties properties) {

    HashSet specialProps = new HashSet();
    specialProps.add(Environment.JNDI_CLASS);
    specialProps.add(Environment.JNDI_URL);

    Iterator iter = properties.keySet().iterator();
    Properties result = new Properties();
    while (iter.hasNext()) {
      String prop = (String) iter.next();
      if (prop.indexOf(Environment.JNDI_PREFIX) > -1 && !specialProps.contains(prop)) {
        result.setProperty(
            prop.substring(Environment.JNDI_PREFIX.length() + 1), properties.getProperty(prop));
      }
    }

    String jndiClass = properties.getProperty(Environment.JNDI_CLASS);
    String jndiURL = properties.getProperty(Environment.JNDI_URL);
    // we want to be able to just use the defaults,
    // if JNDI environment properties are not supplied
    // so don't put null in anywhere
    if (jndiClass != null) result.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass);
    if (jndiURL != null) result.put(Context.PROVIDER_URL, jndiURL);

    return result;
  }