Example usage for java.util Properties setProperty

List of usage examples for java.util Properties setProperty

Introduction

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

Prototype

public synchronized Object setProperty(String key, String value) 

Source Link

Document

Calls the Hashtable method put .

Usage

From source file:com.smartitengineering.dao.hbase.autoincrement.AutoIncrementRowIdForLongTest.java

@BeforeClass
public static void globalSetup() throws Exception {
    /*//from   w  ww  .ja  va  2  s. c o  m
     * Start HBase and initialize tables
     */
    //-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
            "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
    try {
        TEST_UTIL.startMiniCluster();
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    //Create table for testing
    InputStream classpathResource = AutoIncrementRowIdForLongTest.class.getClassLoader()
            .getResourceAsStream("ddl-config-sample1.json");
    Collection<HBaseTableConfiguration> configs = ConfigurationJsonParser.getConfigurations(classpathResource);
    try {
        new HBaseTableGenerator(configs, TEST_UTIL.getConfiguration(), true).generateTables();
    } catch (Exception ex) {
        LOGGER.error("Could not create table!", ex);
        Assert.fail(ex.getMessage());
    }
    pool = new HTablePool(TEST_UTIL.getConfiguration(), 200);
    //Start web app
    jettyServer = new Server(PORT);
    final String webapp = "./src/main/webapp/";
    if (!new File(webapp).exists()) {
        throw new IllegalStateException("WebApp file/dir does not exist!");
    }

    Properties properties = new Properties();
    properties.setProperty(GuiceUtil.CONTEXT_NAME_PROP, "com.smartitengineering.dao.impl.hbase");
    properties.setProperty(GuiceUtil.IGNORE_MISSING_DEP_PROP, Boolean.TRUE.toString());
    properties.setProperty(GuiceUtil.MODULES_LIST_PROP, TestModule.class.getName());
    GuiceUtil.getInstance(properties).register();

    WebAppContext webAppHandler = new WebAppContext(webapp, "/");
    jettyServer.setHandler(webAppHandler);
    jettyServer.setSendDateHeader(true);
    jettyServer.start();
    //Initialize client
    final MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
    manager.getParams().setDefaultMaxConnectionsPerHost(THREAD_COUNT);
    manager.getParams().setMaxTotalConnections(THREAD_COUNT);
    httpClient = new HttpClient(manager);
}

From source file:io.symcpe.hendrix.api.dao.TestTenantManager.java

@BeforeClass
public static void beforeClass() throws Exception {
    Properties config = new Properties(System.getProperties());
    File db = new File(TARGET_RULES_DB);
    if (db.exists()) {
        FileUtils.deleteDirectory(db);/*from  w w  w .j ava  2  s  .  c om*/
    }
    config.setProperty("javax.persistence.jdbc.url", CONNECTION_STRING);
    try {
        emf = Persistence.createEntityManagerFactory("hendrix", config);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * Write the pdf to the given response/*  w  w  w .j  a v  a  2  s  .c om*/
 */
@SuppressWarnings("unchecked")
public static void generateOutputForIdentifiers(IdcardsTemplate card, String baseURL,
        HttpServletResponse response, List<String> identifiers, String password)
        throws ServletException, IOException {

    Properties props = new Properties();
    props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
    props.setProperty("class.resource.loader.description", "VelocityClasspathResourceLoader");
    props.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogSystem");

    // do the velocity magic
    Writer writer = new StringWriter();
    try {
        // Allow images to be served from Unix servers.
        try {
            java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
        } catch (Throwable t) {
            log.warn(
                    "Unable to get graphics environment.  "
                            + "Make sure that -Djava.awt.headless=true is defined as a JAVA OPT during startup",
                    t);
        }
        Velocity.init(props);
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("locale", Context.getLocale());
        velocityContext.put("identifiers", identifiers);
        velocityContext.put("baseURL", baseURL);
        Velocity.evaluate(velocityContext, writer, PrintEmptyIdcardsServlet.class.getName(), card.getXml());
    } catch (ParseErrorException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (MethodInvocationException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (ResourceNotFoundException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (Exception e) {
        throw new ServletException("Error initializing Velocity engine", e);
    } finally {
        System.gc();
    }

    try {
        //Setup a buffer to obtain the content length
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        FopFactory fopFactory = FopFactory.newInstance();

        //fopFactory supports customization with a config file
        //Load the config file before creating the user agent.
        String userConfigFile = Context.getAdministrationService()
                .getGlobalProperty("idcards.fopConfigFilePath");
        if (userConfigFile != null) {
            try {
                fopFactory.setUserConfig(new java.io.File(userConfigFile));
                log.debug("Successfully loaded config file |" + userConfigFile + "|");
            } catch (Exception e) {
                log.error("Could not initialize fopFactory user config with file at " + userConfigFile
                        + ". Error message:" + e.getMessage());
            }
        }

        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        foUserAgent.getRendererOptions().put("encryption-params",
                new PDFEncryptionParams(password, null, true, false, false, false));

        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        //Setup Transformer
        Source xsltSrc = new StreamSource(new StringReader(card.getXslt()));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(xsltSrc);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Setup input
        String xml = writer.toString();
        Source src = new StreamSource(new StringReader(xml));

        //Start the transformation and rendering process
        transformer.transform(src, res);

        //Prepare response
        String time = new SimpleDateFormat("yyyy-MM-dd_Hms").format(new Date());
        String filename = card.getName().replace(" ", "_") + "-" + time + ".pdf";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentType("application/pdf");
        response.setContentLength(out.size());

        //Send content to Browser
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
    } catch (FOPException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerConfigurationException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerException e) {
        throw new ServletException("Error generating report", e);
    }
}

From source file:com.sat.common.CustomReport.java

/**
 * Sendmail.//from w w  w  .  j a v  a2s  .c o m
 * 
 * @param msg
 *            the msg
 * @throws AddressException
 *             the address exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {

    ConfigFileHandlerManager miscConfigFileHandlerManager = new ConfigFileHandlerManager();
    miscConfigFileHandlerManager.loadPropertiesBasedonPropertyFileName("com.cisco.lms.lms");
    Validate miscValidate = new Validate();

    String from = miscValidate.readsystemvariable("MAIL.FROM");
    String host = miscValidate.readsystemvariable("MAIL.SMTP.HOST");
    String to = miscValidate.readsystemvariable("MAIL.TO");

    String subject = miscValidate.readsystemvariable("MAIL.SUBJECT");
    String personal = miscValidate.readsystemvariable("MAIL.FROM.PERSONAL");

    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, personal));

        message.addRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject);
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

public static Properties getServerProperties() {
    Properties defaultproperties = new Properties();

    defaultproperties.setProperty("hostAddress", "localhost");
    defaultproperties.setProperty("port", "80");
    defaultproperties.setProperty("path", "nrdp");
    defaultproperties.setProperty("password", "");
    defaultproperties.setProperty("ssl", "false");
    defaultproperties.setProperty("connectionTimeout", "5000");

    return defaultproperties;
}

From source file:Main.java

private static Properties importProperties(NodeList nodeList) {
    Properties properties = new Properties();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element entry = (Element) nodeList.item(i);
        if (entry.hasAttribute("name")) {
            String val = (entry == null) ? "" : entry.getFirstChild().getNodeValue();
            String key = entry.getAttribute("name");
            properties.setProperty(key, val);
        }// ww  w.  ja v a2s.  co  m
    }
    return properties;
}

From source file:org.moeaframework.examples.gp.regression.SymbolicRegressionGUI.java

/**
 * Runs the given symbolic regression problem instance, displaying
 * intermediate results in a GUI.//from w w w  .  j ava2 s.  co m
 * 
 * @param problem the symbolic regression problem instance
 */
public static void runDemo(SymbolicRegression problem) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        // couldn't set system look and feel, continue with default
    }

    // setup the GUI
    SymbolicRegressionGUI gui = new SymbolicRegressionGUI(problem);

    // setup and construct the GP solver
    int generation = 0;
    int maxGenerations = 1000;
    Algorithm algorithm = null;
    Properties properties = new Properties();
    properties.setProperty("populationSize", "500");

    try {
        algorithm = AlgorithmFactory.getInstance().getAlgorithm("GA", properties, problem);

        // run the GP solver
        while ((generation < maxGenerations) && !gui.isCanceled()) {
            algorithm.step();
            generation++;

            gui.update(algorithm.getResult().get(0), generation, maxGenerations);
        }
    } finally {
        if (algorithm != null) {
            algorithm.terminate();
        }
    }
}

From source file:com.flozano.socialauth.AuthProviderFactory.java

private static AuthProvider loadProvider(final String id, final Properties props) throws Exception {
    Class<?> obj = providerMap.get(id);
    props.setProperty("id", id);
    AuthProvider provider;//  w w w .  ja  v  a 2  s  .c om
    OAuthConfig conf;

    if (obj == null) {
        try {
            new URL(id); // just validating, don't need the value
            obj = providerMap.get("openid");
            conf = new OAuthConfig(null, null);
            conf.setId(id);
        } catch (MalformedURLException me) {
            throw new SocialAuthException(id + " is not a provider or valid OpenId URL");
        }
    } else {
        String key;
        if (domainMap.containsKey(id)) {
            key = domainMap.get(id);
        } else {
            key = id;
        }
        String consumerKey = props.getProperty(key + ".consumer_key");
        if (consumerKey == null) {
            throw new IllegalStateException(key + ".consumer_key not found.");
        }

        String consumerSecret = props.getProperty(key + ".consumer_secret");
        if (consumerSecret == null) {
            throw new IllegalStateException(key + ".consumer_secret not found.");
        }
        conf = new OAuthConfig(consumerKey, consumerSecret);
        conf.setId(id);
    }

    try {
        Constructor<?> cons = obj.getConstructor(OAuthConfig.class);
        provider = (AuthProvider) cons.newInstance(conf);
    } catch (NoSuchMethodException me) {
        LOG.warn(obj.getName() + " does not implement a constructor " + obj.getName()
                + "(OAuthConfig providerConfig)");
        provider = (AuthProvider) obj.newInstance();
    } catch (Exception e) {
        throw new SocialAuthConfigurationException(e);
    }
    return provider;
}

From source file:com.adaptris.core.services.metadata.SimpleSequenceNumberService.java

private static String nextSequenceNumber(Properties p, Long maximum) {
    if (!p.containsKey(PROPERTY_KEY)) {
        p.setProperty(PROPERTY_KEY, ONE);
    }/* w ww . ja  v  a2 s.c o  m*/
    if (greaterThanMaximum(p.getProperty(PROPERTY_KEY), maximum)) {
        p.setProperty(PROPERTY_KEY, ONE);
    }
    return p.getProperty(PROPERTY_KEY);
}

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Export the supplied Keypair to an output Stream.
 *
 * @param pair The KeyPair to export.  KeyPairs should only be pairs
 * created with the createKeyPair(int) method.
 *
 * @param stream The stream to write the KeyPair to.  Key streams contain both the
 * public and private keys and should be secured.
 *
 * @throws java.io.IOException For any Stream IO related exceptions
 * @throws java.lang.NullPointerException If either parameter is null
 * @since 2.0//from  w w  w  . java  2s .  c  o m
 */
public static void exportKeyPair(KeyPair pair, OutputStream stream) throws IOException {
    if (pair == null) {
        throw new IllegalArgumentException("KeyPair may not be null");
    }

    if (stream == null) {
        throw new IllegalArgumentException("Stream may not be null");
    }

    //
    // Turn the keypair into properties
    //
    Properties p = new Properties();

    String pri = new String(Hex.encodeHex(pair.getPrivate().getEncoded()));
    String pub = new String(Hex.encodeHex((pair.getPublic().getEncoded())));
    p.setProperty("public", pub);
    p.setProperty("private", pri);

    p.store(stream, null);
    stream.flush();
    stream.close();

}