Java Code Examples for java.util.Properties

The following are top voted examples for showing how to use java.util.Properties. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: sslcertx   File: Driver.java View source code Vote up 6 votes
private void setURLParameters(String urlParameters, Properties info) {
    String [] parameters = urlParameters.split("&");
    for(String param : parameters) {
        int pos = param.indexOf('=');
        if (pos == -1)  {
            throw new IllegalArgumentException("Invalid connection URL, expected key=value pairs, found " + param);
        }
        info.setProperty(param.substring(0, pos), param.substring(pos + 1));
    }
}
 
Example 2
Project: sslcertx   File: MySQLProtocol.java View source code Vote up 6 votes
public MyX509TrustManager(Properties props) throws Exception{
    boolean trustServerCertificate  =  props.getProperty("trustServerCertificate") != null;
    if (trustServerCertificate)
        return;

    serverCertFile =  props.getProperty("serverSslCert");
    InputStream inStream;

    if (serverCertFile.startsWith("-----BEGIN CERTIFICATE-----")) {
        inStream = new ByteArrayInputStream(serverCertFile.getBytes());
    } else if (serverCertFile.startsWith("classpath:")) {
        // Load it from a classpath relative file
        String classpathFile = serverCertFile.substring("classpath:".length());
        inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathFile);
    } else {
        inStream = new FileInputStream(serverCertFile);
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate ca = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        // Note: KeyStore requires it be loaded even if you don't load anything into it:
        ks.load(null);
    } catch (Exception e) {

    }
    ks.setCertificateEntry(UUID.randomUUID().toString(), ca);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    for(TrustManager tm : tmf.getTrustManagers()) {
    	if (tm instanceof X509TrustManager) {
  	        trustManager = (X509TrustManager) tm;
  		    break;
        }
    }
    if (trustManager == null) {
        throw new RuntimeException("No X509TrustManager found");
    }
}
 
Example 3
Project: jentrata-msh   File: RemoteCommandRegistrar.java View source code Vote up 6 votes
/**
 * Adds a remote command to the central remote command handler.
 * 
 * @param extension the extension which represents the remote command.
 * @throws PluginException if unable to add the remote command.
 * @see hk.hku.cecid.piazza.commons.spa.ExtensionPointHandler#processExtensions(java.util.Collection)
 */
public void processExtension(Extension extension) throws PluginException {
    
    String commandName = extension.getParameter("command");
    String className  = extension.getParameter("class");

    try {
        Properties command = new Properties();
        command.putAll(extension.getParameters());

        if (className != null) { 
            Class theClass = extension.getPlugin().loadClass(className);
            command.put("class", theClass);
        }
        
        RemoteCommandHandler.register(commandName, command);
    }
    catch (Exception e) {
        throw new PluginException("Unable to register the remote command: "+commandName, e);
    }
}
 
Example 4
Project: jentrata-msh   File: PropertyMap.java View source code Vote up 6 votes
/**
 * Loads the properties from the specified url location.
 * 
 * @param url the url of the properties source.
 * @throws Exception if the operation is unsuccessful. 
 * @see hk.hku.cecid.piazza.commons.module.PersistentComponent#loading(java.net.URL)
 */
protected void loading(URL url) throws Exception {
    InputStream ins = url.openStream();
    props = new Properties();
    props.load(ins);
    ins.close();
}
 
Example 5
Project: aws-toolkit-eclipse   File: KeyPairManager.java View source code Vote up 6 votes
private void storeRegisteredKeyPairs(String accountId, Properties registeredKeyPairs) throws IOException {
    File pluginStateLocation = Ec2Plugin.getDefault().getStateLocation().toFile();
    File registeredKeyPairsFile = new File(pluginStateLocation, getKeyPropertiesFileName(accountId));
    registeredKeyPairsFile.createNewFile();
    FileOutputStream fileOutputStream = new FileOutputStream(registeredKeyPairsFile);
    try {
        registeredKeyPairs.store(fileOutputStream, null);
    } finally {
        fileOutputStream.close();
    }
}
 
Example 6
Project: jentrata-msh   File: RemoteCommandHandler.java View source code Vote up 6 votes
/**
 * Executes a registered command locally with the given parameters.
 * 
 * @param cmdName the command name.
 * @param parameters parameters for the target method invocation.
 * @return the object returned by the invoked method.
 * @throws InstanceException if the instance of the target class cannot be
 *             created or the method could not be invoked.
 * @throws InvocationTargetException if the invoked method has thrown an
 *             exception.
 * @throws NullPointerException if the command is not registered.
 */
static Object executeLocal(String cmdName, Object[] parameters)
        throws InstanceException, InvocationTargetException {
    Properties command = getCommand(cmdName);
    Object clazz = command.get("class");
    String methodName = command.getProperty("method");
    String[] parameterTypeNames = ArrayUtilities.toArray(command
            .getProperty("parameters"), ", ");
    return new Instance(clazz).invoke(methodName, parameterTypeNames,
            parameters);
}
 
Example 7
Project: virgo.kernel   File: PlanDeploymentTests.java View source code Vote up 6 votes
private void checkConfigAvailable(String pid, File propertiesFile) throws IOException {
    Configuration configuration = this.configAdmin.getConfiguration(pid, null);
    Dictionary<String, Object> dictionary = configuration.getProperties();

    Properties properties = new Properties();
    properties.load(new FileReader(propertiesFile));

    Set<Entry<Object, Object>> entrySet = properties.entrySet();

    for (Entry<Object, Object> entry : entrySet) {
        Assert.assertEquals(entry.getValue(), dictionary.get(entry.getKey()));
    }

    Assert.assertEquals(pid, dictionary.get("service.pid"));
}
 
Example 8
Project: jentrata-msh   File: StringUtilities.java View source code Vote up 6 votes
public static  String propertyValue(String value, Properties props) {
    if(value == null) {
        return null;
    }
    boolean hadDefault = false;
    String result = value;
    if(result.contains("${")) {

        List<String> defaultVars = StringUtilities.extractRegexMulti(result,"\\$\\{([^{}]+)\\}",1);
        for(String defaultVar : defaultVars) {
            result = result.replace("${" + defaultVar + "}", propertyGet(defaultVar,props));
        }

        if(result != null && result.isEmpty()) {
            return null;
        }

        List<String> variables = StringUtilities.extractRegexMulti(result,"\\$\\{([^}]+)\\}",1);
        for(String var: variables) {

            //split the varible into the key and default value (if present)
            //in the form ${property:defaultValue}
            String [] variable = splitFirst(var,DEFAULT_VALUE_SEPARTOR);
            
            //Is the variable in the System Properties
            //If so replace the variable with it
            if(props.containsKey(variable[0])) {
                result = result.replace("${"+ var + "}", props.getProperty(variable[0]));
            }
            else if(variable[1] != null) {
                //Otherwise use the default value
                hadDefault = true;
                result = result.replace("${"+ var + "}", variable[1]);
            }
        }
    }
    if(hadDefault && "".equals(result)) {
        return null;
    }
    return result;
}
 
Example 9
Project: aws-toolkit-eclipse   File: Startup.java View source code Vote up 6 votes
/**
 * Returns a map of plugin versions, keyed by their plugin ID, representing
 * plugins that have previously been detected and recorded as contributing
 * to the AWS Toolkit Overview view.
 *
 * @return A map of plugin versions, keyed by their plugin ID, representing
 *         plugins that have been recorded as contributing to the AWS
 *         Toolkit Overview view.
 */
private Map<String, String> getRegisteredOverviewContributors() {
    Map<String, String> registeredPlugins = new HashMap<String, String>();

    File dataFile = getPropertiesFile();
    if (dataFile == null || dataFile.exists() == false) {
        return registeredPlugins;
    }

    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(dataFile);
        Properties properties = new Properties();
        properties.load(inputStream);

        for (Object key : properties.keySet()) {
            String value = properties.getProperty(key.toString());

            registeredPlugins.put(key.toString(), value);
        }
    } catch (IOException e) {
        String errorMessage = "Unable to read currently registered AWS Toolkit components: " + e.getMessage();
        Status status = new Status(Status.ERROR, AwsToolkitCore.PLUGIN_ID, errorMessage, e);
        StatusManager.getManager().handle(status, StatusManager.LOG);
    } finally {
        try {inputStream.close();} catch (IOException ioe) {}
    }

    return registeredPlugins;
}
 
Example 10
Project: aipo   File: JavaRuntimePortlet.java View source code Vote up 6 votes
public ConcreteElement getContent(RunData rundata) {

    Table table = new Table().setWidth("100%");

    try {
      // get Runtime status
      Runtime jvm = Runtime.getRuntime();

      table.addElement(new TR().addElement(new TD("Free Memory (in bytes)"))
          .addElement(new TD(Long.toString(jvm.freeMemory()))));

      table.addElement(new TR().addElement(new TD("Total Memory (in bytes)"))
          .addElement(new TD(Long.toString(jvm.totalMemory()))));

      // get the system properties (It can throw a SecurityException)
      Properties props = System.getProperties();

      Enumeration enu = props.propertyNames();
      while (enu.hasMoreElements()) {
        Object key = enu.nextElement();
        if (!(key instanceof String)) {
          continue;
        }

        Object value = props.getProperty(key.toString());
        table.addElement(new TR().addElement(new TD(key.toString()))
            .addElement(new TD(value.toString())));

      }
    } catch (Throwable t) {
      logger.error("Throwable", t);
      table.addElement(new TR().addElement(new TD("Error")).addElement(
          new TD("Could not read system properties")));
    }

    return table;
  }
 
Example 11
Project: sslcertx   File: MySQLConnection.java View source code Vote up 6 votes
/**
 * Sets the value of the connection's client info properties.  The <code>Properties</code> object contains the names
 * and values of the client info properties to be set.  The set of client info properties contained in the
 * properties list replaces the current set of client info properties on the connection.  If a property that is
 * currently set on the connection is not present in the properties list, that property is cleared.  Specifying an
 * empty properties list will clear all of the properties on the connection.  See <code>setClientInfo (String,
 * String)</code> for more information.
 * <p/>
 * If an error occurs in setting any of the client info properties, a <code>SQLClientInfoException</code> is thrown.
 * The <code>SQLClientInfoException</code> contains information indicating which client info properties were not
 * set. The state of the client information is unknown because some databases do not allow multiple client info
 * properties to be set atomically.  For those databases, one or more properties may have been set before the error
 * occurred.
 * <p/>
 *
 * @param properties the list of client info properties to set
 *                   <p/>
 * @throws java.sql.SQLClientInfoException
 *          if the database server returns an error while setting the clientInfo values on the database server or
 *          this method is called on a closed connection
 *          <p/>
 * @see java.sql.Connection#setClientInfo(String, String) setClientInfo(String, String)
 * @since 1.6
 *        <p/>
 */
public void setClientInfo(final Properties properties) throws java.sql.SQLClientInfoException {
    // TODO: actually use these!
    for (final String key : properties.stringPropertyNames()) {
        this.clientInfoProperties.setProperty(key, properties.getProperty(key));
    }
}
 
Example 12
Project: camel-trade   File: TradexService.java View source code Vote up 6 votes
/**
 * Returns the system props in json format
 * @return the system props in json format
 */
@GET
@Produces("application/json")
@Path("sysprops")
public Response sysprops(){
	Properties p = System.getProperties();
	List<String> props = new ArrayList<String>(p.size());
	for(String key: p.stringPropertyNames()) {
		props.add(key + ":" + p.getProperty(key));
	}
	GenericEntity<List<String>> entity = new GenericEntity<List<String>>(props) { };
	return Response.ok().entity(entity).build();
}
 
Example 13
Project: UnicentaPOS_AD   File: ImageUtils.java View source code Vote up 6 votes
public static Properties readProperties(byte b[]) {
    Properties prop = new Properties();
    try {
        if (b != null) {
            prop.loadFromXML(new ByteArrayInputStream(b));
        }
    } catch (IOException e) {
    }
    return prop;
}
 
Example 14
Project: abiquo   File: ResourceManager.java View source code Vote up 6 votes
/**
 * Save properties to xml.
 * 
 * @param p the p
 * @param args the args
 */
public void savePropertiesToXML(Properties p, String... args)
{
    File file =
        createPropertiesFile(args, ResourceConstants.RESOURCES_PROPERTIES_XML_ROOT_DIR, ".xml");

    try
    {
        p.storeToXML(new FileOutputStream(file), null, "UTF-8");
    }
    catch (Exception e)
    {
        logger.error("Unable to write the properties  to the file: " + file, e);
    }

}
 
Example 15
Project: genome-weaver-align   File: LaunchJava.java View source code Vote up 6 votes
public static String[] prepareEnvironmentVariables() {
    Properties env = new Properties();
    for (Entry<String, String> eachEnv : System.getenv().entrySet()) {
        env.setProperty(eachEnv.getKey(), eachEnv.getValue());
    }
    if (!env.contains("JAVA_HOME") || env.getProperty("JAVA_HOME").contains("jre")) {
        env.setProperty("JAVA_HOME", System.getProperty("java.home"));
    }

    String[] envp = new String[env.size()];
    int index = 0;
    for (Object each : env.keySet()) {
        String key = each.toString();
        envp[index++] = String.format("%s=%s", key, env.getProperty(key));
    }

    _logger.trace("environment variables: " + env);
    return envp;
}
 
Example 16
Project: Joustick   File: JoyInitializer.java View source code Vote up 6 votes
public void doit() {
    try {
        Properties p = new Properties();
        p.load(new FileInputStream("user.ini"));
        System.out.println("user = " + p.getProperty("DBuser"));
        System.out.println("password = " + p.getProperty("DBpassword"));
        System.out.println("location = " + p.getProperty("DBlocation"));
        p.list(System.out);
        /*
        p.setProperty("DBuser", "dbuzer");
        p.setProperty("DBpassword", "dpass");
        p.setProperty("DBlocation", "locat");
        p.store(new FileOutputStream("user.ini"), null);*/
    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(null, "Merhaba");
    }
}
 
Example 17
Project: xmind   File: ModifyStyleCommandBuilder.java View source code Vote up 6 votes
private IStyle findSimilarStyle(Properties sourceProperties,
        IStyleSheet styleSheet) {
    Set<IStyle> styles = styleSheet.getStyles(IStyleSheet.NORMAL_STYLES);
    for (IStyle style : styles) {
        Properties contents = getProperties(style);
        if (contents.equals(sourceProperties))
            return style;
    }
    return null;
}
 
Example 18
Project: aokp-gerrit   File: GarbageCollection.java View source code Vote up 6 votes
private static void logGcInfo(Project.NameKey projectName, String msg,
    Properties statistics) {
  StringBuilder b = new StringBuilder();
  b.append("[").append(projectName.get()).append("] ");
  b.append(msg);
  if (statistics != null) {
    b.append(" ");
    String s = statistics.toString();
    if (s.startsWith("{") && s.endsWith("}")) {
      s = s.substring(1, s.length() - 1);
    }
    b.append(s);
  }
  gcLog.info(b.toString());
}
 
Example 19
Project: atg-dust-11   File: MockDynamoHttpServletRequest.java View source code Vote up 6 votes
@Override
@SuppressWarnings("unchecked")
public Enumeration getAttributeNames() {

  // Cheesy way converting an iterator to an enumeration
  final Properties properties = new Properties();
  for (final Iterator<String> it = attributes.keySet().iterator(); it
      .hasNext();) {
    final String s = it.next();
    properties.put(s, s);
  }
  return properties.elements();
}
 
Example 20
Project: strongback-java   File: PropertiesUtils.java View source code Vote up 6 votes
/**
 * Combines multiple [email protected] Properties} into a single [email protected] Properties} without 
 * modifying any of the original [email protected] Properties}. If the same key is defined in two [email protected] Properties},
 * it will be assigned the value appearing in the latest [email protected] Properties} in the list.
 * @param props the [email protected] Properties} to concatenate
 * @return a single [email protected] Properties} containing all of the key value pairs
 */
public static Properties concat(Properties... props) {
    Properties out = new Properties();
    for(Properties prop : props) {
        prop.forEach(out::put);
    }
    return out;
}
 
Example 21
Project: datagen   File: Archetype.java View source code Vote up 6 votes
private static String resolveDescription(String id, URL infoUrl) throws IOException {
  URL descriptionUrl = new URL(infoUrl.toString() + "/description.properties");
  String desc = null;
  try {
   InputStream descriptionFileStream = descriptionUrl.openStream();
   Properties descriptions = new Properties();
descriptions.load(descriptionFileStream);
         // try to get the name in the user's default locale...
   desc = descriptions.getProperty(Locale.getDefault().getLanguage());
   if (desc == null) // ...if no such name was defined, fall back to the English name (if it exists)
   	desc = descriptions.getProperty("en");
   if (desc == null) { // if there is even no English name, choose an arbitrary one
   	Collection<Object> values = descriptions.values();
   	if (values.size() > 0)
   		desc = values.iterator().next().toString();
   }
  } catch (FileNotFoundException e) {
  	// no description file defined
  }
  // if no description was found, choose the archetype id as description
  return (desc != null ? desc : id);
 }
 
Example 22
Project: wpcleaner   File: LoginWorker.java View source code Vote up 5 votes
@Override
public Object construct() {
  try {
    setText(GT._("Retrieving MediaWiki API"));
    API api = APIFactory.getAPI();
    EnumWikipedia wiki = getWikipedia();

    // Login
    if (!reloadOnly) {
      setText(GT._("Login"));
      LoginResult result = api.login(wiki, username, new String(password), login);
      if (login) {
        if ((result == null) || (!result.isLoginSuccessful())) {
          throw new APIException("Login unsuccessful: " + ((result != null) ? result.toString() : ""));
        }
      }
      User user = api.retrieveUser(wiki, username);
      username = (user != null) ? user.getName() : null;
      wiki.getConnection().setUser(user);
      api.retrieveTokens(wiki);
      logged = true;
    }

    // Load configuration
    setText(GT._("Loading configuration"));
    api.loadConfiguration(wiki, username);

    // Saving settings
    Configuration configuration = Configuration.getConfiguration();
    configuration.setWikipedia(wiki);
    configuration.setLanguage(language);
    if (login && !reloadOnly && (saveUser != ConfigurationConstants.VALUE_SAVE_USER_NO_CHANGE)) {
      Properties props = configuration.getProperties(wiki, Configuration.PROPERTIES_USERS);
      if (saveUser == ConfigurationConstants.VALUE_SAVE_USER_NONE) {
        props.remove(username);
        configuration.setString(wiki, ConfigurationValueString.LAST_USER, (String) null);
      } else {
        props.setProperty(
            username,
            (saveUser == ConfigurationConstants.VALUE_SAVE_USER_BOTH) ? new String(password) : "");
        configuration.setString(wiki, ConfigurationValueString.LAST_USER, username);
      }
      configuration.setProperties(wiki, Configuration.PROPERTIES_USERS, props);
      configuration.setInt(
          null,
          ConfigurationValueInteger.SAVE_USER,
          saveUser);
    }
    Configuration.getConfiguration().save();

    // Retrieving disambiguation templates
    setText(GT._("Retrieving disambiguation templates"));
    wiki.initDisambiguationTemplates(api);

    // Retrieving suggestions for text replacements
    setText(GT._("Retrieving suggestions for text replacements"));
    wiki.getConfiguration().initSuggestions(api, reloadOnly);

    // Retrieving Check Wiki configuration
    setText(GT._("Retrieving Check Wiki configuration"));
    APIFactory.getCheckWiki().retrieveConfiguration(wiki, this);

    // Retrieving special configuration
    CheckErrorAlgorithm algo524 = CheckErrorAlgorithms.getAlgorithm(wiki, 524);
    if ((algo524 != null) &&
        algo524.isAvailable() &&
        CheckErrorAlgorithms.isAlgorithmActive(wiki, 524)) {
      ((CheckErrorAlgorithm524) algo524).setTrackingCategory(api.loadMessage(wiki, "duplicate-args-category"));
    }
  } catch (APIException e) {
    return e;
  }
  return null;
}
 
Example 23
Project: dlna   File: HttpServer.java View source code Vote up 5 votes
/**
 * Sends given response to the socket.
 */
private void sendResponse( String status, String mime, Properties header, InputStream data )
{
	try
	{
		if ( status == null )
			throw new Error( "sendResponse(): Status can't be null." );

		OutputStream out = mySocket.getOutputStream();
		PrintWriter pw = new PrintWriter( out );
		pw.print("HTTP/1.0 " + status + " \r\n");

		if ( mime != null )
			pw.print("Content-Type: " + mime + "\r\n");

		if ( header == null || header.getProperty( "Date" ) == null )
			pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");

		if ( header != null )
		{
			Enumeration e = header.keys();
			while ( e.hasMoreElements())
			{
				String key = (String)e.nextElement();
				String value = header.getProperty( key );
				pw.print( key + ": " + value + "\r\n");
			}
		}

		pw.print("\r\n");
		pw.flush();

		if ( data != null )
		{
			int pending = data.available();	// This is to support partial sends, see serveFile()
			byte[] buff = new byte[2048];
			while (pending>0)
			{
				int read = data.read( buff, 0, ( (pending>2048) ?  2048 : pending ));
				if (read <= 0)	break;
				out.write( buff, 0, read );
				pending -= read;
			}
		}
		out.flush();
		out.close();
		if ( data != null )
			data.close();
	}
	catch( IOException ioe )
	{
		// Couldn't write? No can do.
		try { mySocket.close(); } catch( Throwable t ) {}
	}
}
 
Example 24
Project: wso2-synapse   File: FileBaseSecretRepository.java View source code Vote up 5 votes
/**
 * Initializes the repository based on provided properties
 *
 * @param properties Configuration properties
 * @param id         Identifier to identify properties related to the corresponding repository
 */
public void init(Properties properties, String id) {
    StringBuffer sb = new StringBuffer();
    sb.append(id);
    sb.append(DOT);
    sb.append(LOCATION);

    String filePath = MiscellaneousUtil.getProperty(properties,
            sb.toString(), DEFAULT_CONF_LOCATION);

    Properties cipherProperties = MiscellaneousUtil.loadProperties(filePath);
    if (cipherProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Cipher texts cannot be loaded form : " + filePath);
        }
        return;
    }

    StringBuffer sbTwo = new StringBuffer();
    sbTwo.append(id);
    sbTwo.append(DOT);
    sbTwo.append(ALGORITHM);
    //Load algorithm
    String algorithm = MiscellaneousUtil.getProperty(properties,
            sbTwo.toString(), DEFAULT_ALGORITHM);
    StringBuffer buffer = new StringBuffer();
    buffer.append(DOT);
    buffer.append(KEY_STORE);

    //Load keyStore
    String keyStore = MiscellaneousUtil.getProperty(properties,
            buffer.toString(), null);
    KeyStoreWrapper keyStoreWrapper;
    if (TRUSTED.equals(keyStore)) {
        keyStoreWrapper = trust;

    } else {
        keyStoreWrapper = identity;
    }

    //Creates a cipherInformation

    CipherInformation cipherInformation = new CipherInformation();
    cipherInformation.setAlgorithm(algorithm);
    cipherInformation.setCipherOperationMode(CipherOperationMode.DECRYPT);
    cipherInformation.setInType(EncodingType.BASE64); //TODO
    DecryptionProvider baseCipher =
            CipherFactory.createCipher(cipherInformation, keyStoreWrapper);

    for (Object alias : cipherProperties.keySet()) {
        //decrypt the encrypted text 
        String key = String.valueOf(alias);
        String encryptedText = cipherProperties.getProperty(key);
        encryptedData.put(key, encryptedText);
        if (encryptedText == null || "".equals(encryptedText.trim())) {
            if (log.isDebugEnabled()) {
                log.debug("There is no secret for the alias : " + alias);
            }
            continue;
        }

        String decryptedText = new String(baseCipher.decrypt(encryptedText.trim().getBytes()));
        secrets.put(key, decryptedText);
    }
    initialize = true;
}
 
Example 25
Project: aipo   File: HeaderAction.java View source code Vote up 5 votes
public void editHeader(RunData rundata, Context context, Hashtable ht)
        throws Exception
{
    try
    {
        String logo = (String) ht.get("logo");
        String bgImage = (String) ht.get("BgImage");
        String bgColor = (String) ht.get("BgColor");
        String fontSize = (String) ht.get("FontSize");
        String fontColor = (String) ht.get("FontColor");
        String title = (String) ht.get("PortalTitle");

        boolean setLogo = Boolean.valueOf((String) ht.get("SetLogo")).booleanValue();
        boolean setBgImage = Boolean.valueOf((String) ht.get("SetBgImage"))
                .booleanValue();
        boolean setBgColor = Boolean.valueOf((String) ht.get("SetBgColor"))
                .booleanValue();
        boolean setFontSize = Boolean.valueOf((String) ht.get("SetFontSize"))
                .booleanValue();
        boolean setFontColor = Boolean.valueOf((String) ht.get("SetFontColor"))
                .booleanValue();
        boolean setPortalTitle = Boolean.valueOf((String) ht.get("SetTitle"))
                .booleanValue();

        String DEFAULT_ROOT = File.separator + "WEB-INF" + File.separator
                + "conf" + File.separator;
        String root = rundata.getServletConfig().getServletContext()
                .getRealPath(DEFAULT_ROOT)
                + File.separator;

        Properties prop = new Properties();
        prop.clear();
        prop.load(new FileInputStream(root + "JetspeedResources.properties"));

        TurbineResources trProp = (TurbineResources) TurbineResources
                .getResources(root + "JetspeedResources.properties");

        int counter = 0;
        if (setBgImage && !setBgColor && (counter == 0))
        {
            setBgColor = true;
            bgColor = "FFFFFF";
            counter = 1;
        }
        if (!setBgImage && setBgColor && (counter == 0))
        {
            setBgImage = true;
            bgImage = "";
            counter = 1;
        }
        if (setBgImage && setBgColor && (counter == 0))
        {
            setBgColor = true;
            bgColor = "FFFFFF";
            counter = 1;
        }

        if (setLogo)
        {
            TurbineResources.setProperty("topnav.logo.file", logo);
            prop.setProperty("topnav.logo.file", logo);
        }
        if (setBgImage)
        {
            TurbineResources.setProperty("topnav.bg.image", bgImage);
            prop.setProperty("topnav.bg.image", bgImage);
        }
        if (setBgColor)
        {
            TurbineResources.setProperty("topnav.bg.color", bgColor);
            prop.setProperty("topnav.bg.color", bgColor);
        }
        if (setFontSize)
        {
            TurbineResources.setProperty("topnav.font.size", fontSize);
            prop.setProperty("topnav.font.size", fontSize);
        }
        if (setFontColor)
        {
            TurbineResources.setProperty("topnav.font.color", fontColor);
            prop.setProperty("topnav.font.color", fontColor);
        }
        if (setPortalTitle)
        {
            TurbineResources.setProperty("portal.title", title);
            prop.setProperty("portal.title", title);
        }
        	
        FileOutputStream stream = new FileOutputStream(root + "JetspeedResources.properties");
        prop.store(stream, "topnav.logo.file");
        prop.store(stream, "topnav.bg.image");
        prop.store(stream, "topnav.bg.color");
        prop.store(stream, "topnav.font.size");
        prop.store(stream, "topnav.font.color");
        stream.close();
        
        String logoJR = prop.getProperty("topnav.logo.file");
        String bgImageJR = prop.getProperty("topnav.bg.image");
        String bgColorJR = prop.getProperty("topnav.bg.color");
        String fontSizeJR = prop.getProperty("topnav.font.size");
        String fontColorJR = prop.getProperty("topnav.font.color");

        log.info("new Logo : " + logoJR);
        log.info("new bgImageJR : " + bgImageJR);
        log.info("new bgColorJR : " + bgColorJR);
        log.info("new fontSizeJR : " + fontSizeJR);
        log.info("new fontColorJR : " + fontColorJR);

        prop = null;
        System.gc();

        context.put("settingStatus", "Successfully changed settings.");
    } catch (Exception e)
    {
        context.put("settingStatus",
                "Error occurred while changing settings.");
        log.error(e);
    }
}
 
Example 26
Project: aipo   File: HeaderAction.java View source code Vote up 5 votes
public void doDefault(RunData rundata, Context context) throws Exception
{
    try
    {
        String logo = IMAGES_DIRECTORY + "jetspeed-logo.gif";
        String bgImage = "";
        String fontSize = "10";
        String title = "Jakarta Jetspeed";

        String DEFAULT_ROOT = File.separator + "WEB-INF" + File.separator
                + "conf" + File.separator;
        String root = rundata.getServletConfig().getServletContext()
                .getRealPath(DEFAULT_ROOT)
                + File.separator;

        Properties prop = new Properties();
        prop
                .load(new FileInputStream(root
                        + "JetspeedResources.properties"));
        prop.clone();

        TurbineResources trProp = (TurbineResources) TurbineResources
                .getResources(root + "JetspeedResources.properties");

        TurbineResources.setProperty("portal.title", title);
        prop.setProperty("portal.title", title);
        TurbineResources.setProperty("topnav.logo.file", logo);
        prop.setProperty("topnav.logo.file", logo);
        TurbineResources.setProperty("topnav.bg.image","");
        prop.setProperty("topnav.bg.image","");
        TurbineResources.setProperty("topnav.bg.color", "");
        prop.setProperty("topnav.bg.color", ""); 
  
        TurbineResources.setProperty("topnav.font.size", ""); 
        prop.setProperty("topnav.font.size", "");
  
        TurbineResources.setProperty("topnav.font.color", ""); 
 prop.setProperty("topnav.font.color", "");  


        FileOutputStream stream = new FileOutputStream(root + "JetspeedResources.properties");
                    
        prop.save(stream, "topnav.logo.file");
        
        prop.save(stream, "portal.title");
        prop.save(stream, "topnav.bg.image");
        prop.save(stream, "topnav.bg.color");
        prop.save(stream, "ptopnav.font.size");
        prop.save(stream, "ptopnav.font.size");
        stream.close();
        
        context.put("settingStatus",
                "Successfully changed to default settings.");
    } catch (Exception e)
    {
        context.put("settingStatus",
                "Error occurred while changing to default settings. ");
        log.error(e);
    }
}