Example usage for java.util Properties loadFromXML

List of usage examples for java.util Properties loadFromXML

Introduction

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

Prototype

public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException 

Source Link

Document

Loads all of the properties represented by the XML document on the specified input stream into this properties table.

Usage

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

private Map<Object, Object> importFromXMLFormat(InputStream is) throws IOException {
    Properties properties = new Properties();
    byte[] buffer = getBytesFromInputStream(is);
    ByteArrayInputStream byteIs = new ByteArrayInputStream(buffer);
    properties.loadFromXML(byteIs);
    return properties;
}

From source file:org.kchine.rpf.PoolUtils.java

private static void injectSystemProperties(InputStream is, boolean override) {
    if (is != null) {
        try {/*from  w w w .jav a2s . c om*/
            Properties props = new Properties();

            props.loadFromXML(is);

            System.out.println("Properties : " + props);

            Enumeration<Object> keys = props.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                boolean setProp = override || System.getProperty(key) == null
                        || System.getProperty(key).equals("");
                if (setProp)
                    System.setProperty(key, props.getProperty(key));
            }

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

From source file:org.jsecurity.realm.text.PropertiesRealm.java

private Properties loadProperties(String resourcePath) {
    Properties props = new Properties();

    InputStream is = null;/*www.ja  v a 2s. c  o  m*/
    try {

        if (log.isDebugEnabled()) {
            log.debug("Opening input stream for path [" + resourcePath + "]...");
        }

        is = ResourceUtils.getInputStreamForPath(resourcePath);
        if (useXmlFormat) {

            if (log.isDebugEnabled()) {
                log.debug("Loading properties from path [" + resourcePath + "] in XML format...");
            }

            props.loadFromXML(is);
        } else {

            if (log.isDebugEnabled()) {
                log.debug("Loading properties from path [" + resourcePath + "]...");
            }

            props.load(is);
        }

    } catch (IOException e) {
        throw new JSecurityException("Error reading properties path [" + resourcePath + "].  "
                + "Initializing of the realm from this file failed.", e);
    } finally {
        ResourceUtils.close(is);
    }

    return props;
}

From source file:org.webdavaccess.LocalFileSystemStorage.java

private void saveCustomProperties(Properties newProperties, String resourceUri) {
    if (newProperties == null || newProperties.size() == 0)
        return;//  w  ww. j  a  v  a  2 s. co m

    resourceUri = normalize(resourceUri);
    File file = getPropertiesFile(resourceUri);
    if (file == null)
        return;
    Properties persisted = new Properties();
    // Properties file exists, load it so we can add new properties
    if (file.exists()) {
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            persisted.loadFromXML(in);
        } catch (Exception e) {
            log.warn("Failed to get properties from cache for " + resourceUri);
            return;
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (Exception e) {
                }
        }
    }
    // Add new properties with key format of: resourceUri + "|" + key
    Enumeration en = newProperties.keys();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        persisted.setProperty(getResourcePropertyKey(resourceUri, key), newProperties.getProperty(key));
    }
    // Store the updates properties
    OutputStream os = null;
    try {
        os = new FileOutputStream(file);
        persisted.storeToXML(os, "");
    } catch (Exception e) {
        log.warn("Failed to store properties for " + resourceUri);
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (Exception e) {
            }
    }
}

From source file:org.voyanttools.trombone.input.extract.XmlExtractor.java

@Override
public InputSource getExtractableInputSource(StoredDocumentSource storedDocumentSource) throws IOException {

    // no format specified, so let's have a peek at the contents to see if we can determine a sub-format
    DocumentFormat guessedFormat = DocumentFormat.UNKNOWN;
    if (parameters.getParameterValue("inputFormat", "").isEmpty()) {
        InputStream is = null;/*w w w.ja v  a 2 s  .  c om*/
        try {
            is = storedDocumentSourceStorage.getStoredDocumentSourceInputStream(storedDocumentSource.getId());
            XmlRootExtractor xmlRootExtractor = new XmlRootExtractor();
            QName qname = xmlRootExtractor.extractRootElement(is);
            String name = qname.getLocalPart();
            if (name.equals("feed") && qname.getNamespaceURI().toLowerCase().contains("atom"))
                guessedFormat = DocumentFormat.ATOM;
            else if (name.equals("TEI"))
                guessedFormat = DocumentFormat.TEI;
            else if (name.equals("teiCorpus"))
                guessedFormat = DocumentFormat.TEICORPUS;
            else if (name.equals("rss"))
                guessedFormat = DocumentFormat.RSS;
            else if (name.equals("EEBO"))
                guessedFormat = DocumentFormat.EEBODREAM;
        } finally {
            if (is != null)
                is.close();
        }
    }

    if (parameters.getParameterValue("inputFormat", "").isEmpty() == false
            || guessedFormat != DocumentFormat.UNKNOWN) {

        if (guessedFormat == DocumentFormat.UNKNOWN) {
            guessedFormat = DocumentFormat
                    .valueOf(parameters.getParameterValue("inputFormat", "").toUpperCase());
        }

        Properties properties = new Properties();

        String resourcePath = "/org/voyanttools/trombone/input-formats/" + guessedFormat.name().toLowerCase()
                + ".xml";
        URL url = this.getClass().getResource(resourcePath);
        if (url != null) {
            File file = new File(url.getPath());
            if (file.exists()) {
                FileInputStream in = null;
                try {
                    in = new FileInputStream(file);
                    properties.loadFromXML(in);

                } finally {
                    if (in != null) {
                        in.close();
                    }
                }
            }
            if (parameters.getParameterBooleanValue("splitDocuments")) {
                for (String key : properties.stringPropertyNames()) {
                    if (key.contains(".splitDocuments")) {
                        parameters.setParameter(key.split("\\.")[0], properties.getProperty(key)); // overwrite prefix key
                    }
                }
            }
            for (String key : properties.stringPropertyNames()) {
                if (parameters.getParameterValue(key, "").isEmpty() == true) {
                    parameters.setParameter(key, properties.getProperty(key));
                }
            }
        }

    }

    String[] relevantParameters = new String[] { "xmlContentXpath", "xmlTitleXpath", "xmlAuthorXpath",
            "xmlPubPlaceXpath", "xmlPublisherXpath", "xmlPubDateXpath", "xmlExtraMetadataXpath" };
    StringBuilder parametersBuilder = new StringBuilder();
    for (String p : relevantParameters) {
        if (parameters.getParameterValue(p, "").isEmpty() == false) {
            parametersBuilder.append(p);
            for (String s : parameters.getParameterValues(p)) {
                parametersBuilder.append(s);
            }
        }
    }

    /* This was skipped, but we probably need to extract anyway to strip XML comments, detect language, etc.
     * 
    // no special parameters and nothing to extract from XML, so just return the original stored document
    if (parametersBuilder.length()==0) {
       return new StoredDocumentSourceInputSource(storedDocumentSourceStorage, storedDocumentSource);
    }
    */

    return new ExtractableXmlInputSource(
            DigestUtils.md5Hex(
                    storedDocumentSource.getId() + relevantParameters + String.valueOf(serialVersionUID)),
            storedDocumentSource);
}

From source file:org.voyanttools.trombone.input.expand.XmlExpander.java

public List<StoredDocumentSource> getExpandedStoredDocumentSources(StoredDocumentSource storedDocumentSource)
        throws IOException {

    List<StoredDocumentSource> childStoredDocumentSources = new ArrayList<StoredDocumentSource>();

    String xmlDocumentsXpath = parameters.getParameterValue("xmlDocumentsXpath", "");

    // no format specified, so let's have a peek at the contents to see if we can determine a sub-format
    DocumentFormat guessedFormat = DocumentFormat.UNKNOWN;
    if (parameters.getParameterValue("inputFormat", "").isEmpty()) {
        InputStream is = null;/*from w ww  .  j  av  a2s.c  o m*/
        try {
            is = storedDocumentSourceStorage.getStoredDocumentSourceInputStream(storedDocumentSource.getId());
            XmlRootExtractor xmlRootExtractor = new XmlRootExtractor();
            QName qname = xmlRootExtractor.extractRootElement(is);
            String name = qname.getLocalPart();
            if (name.equals("feed") && qname.getNamespaceURI().toLowerCase().contains("atom"))
                guessedFormat = DocumentFormat.ATOM;
            else if (name.equals("TEI"))
                guessedFormat = DocumentFormat.TEI;
            else if (name.equals("teiCorpus"))
                guessedFormat = DocumentFormat.TEICORPUS;
            else if (name.equals("rss"))
                guessedFormat = DocumentFormat.RSS;
            else if (name.equals("EEBO"))
                guessedFormat = DocumentFormat.EEBODREAM;
        } finally {
            if (is != null)
                is.close();
        }
    }

    // check to see if we need to set xmlDocumentsXpath using defaults for format
    if (xmlDocumentsXpath.isEmpty() && (parameters.getParameterValue("inputFormat", "").isEmpty() == false
            || guessedFormat != DocumentFormat.UNKNOWN)) {

        if (guessedFormat == DocumentFormat.UNKNOWN) {
            guessedFormat = DocumentFormat
                    .valueOf(parameters.getParameterValue("inputFormat", "").toUpperCase());
        }
        Properties properties = new Properties();
        String resourcePath = "/org/voyanttools/trombone/input-formats/" + guessedFormat.name().toLowerCase()
                + ".xml";
        URL url = this.getClass().getResource(resourcePath);
        if (url != null) {
            File file = new File(url.getPath());
            if (file.exists()) {
                FileInputStream in = null;
                try {
                    in = new FileInputStream(file);
                    properties.loadFromXML(in);

                } finally {
                    if (in != null) {
                        in.close();
                    }
                }
            }
            if (properties.containsKey("xmlDocumentsXpath")) {
                xmlDocumentsXpath = properties.getProperty("xmlDocumentsXpath");
            }
        }

    }

    String xmlGroupByXpath = parameters.getParameterValue("xmlGroupByXpath", "");

    if (xmlDocumentsXpath.isEmpty()) {
        childStoredDocumentSources.add(storedDocumentSource);
        return childStoredDocumentSources;
    }

    DocumentMetadata parentMetadata = storedDocumentSource.getMetadata();
    String parentId = storedDocumentSource.getId();
    String multipleExpandedStoredDocumentSourcesPrefix = DigestUtils
            .md5Hex(xmlDocumentsXpath + xmlGroupByXpath);
    childStoredDocumentSources = storedDocumentSourceStorage.getMultipleExpandedStoredDocumentSources(parentId,
            multipleExpandedStoredDocumentSourcesPrefix);
    if (childStoredDocumentSources != null && childStoredDocumentSources.isEmpty() == false) {
        return childStoredDocumentSources;
    }

    // for some reason XPathAPI doesn't work properly with the default
    // XPathFactory, so we'll use Saxon
    System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
            "net.sf.saxon.xpath.XPathFactoryImpl");

    InputStream inputStream = null;
    Document doc;
    try {

        inputStream = storedDocumentSourceStorage
                .getStoredDocumentSourceInputStream(storedDocumentSource.getId());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setIgnoringComments(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(inputStream);

    } catch (ParserConfigurationException e) {
        throw new IOException("Error with XML parser configuration for " + storedDocumentSource, e);
    } catch (SAXException e) {
        throw new IOException("Error with XML parsing for " + storedDocumentSource, e);
    } finally {
        if (inputStream != null)
            inputStream.close();
    }

    List<NodeInputSource> nodeInputSources = getChildStoredDocumentSources(doc, xmlDocumentsXpath, parentId,
            parentMetadata);

    if (nodeInputSources.isEmpty() == false) {
        if (xmlGroupByXpath.isEmpty() == false) {
            Map<String, List<NodeInputSource>> groupedNodeInputSources = new HashMap<String, List<NodeInputSource>>();
            for (NodeInputSource nodeInputSource : nodeInputSources) {
                List<String> keys;
                try {
                    Node fragment = doc.createDocumentFragment();
                    fragment.appendChild(nodeInputSource.node);
                    keys = XPathAPI.selectNodeListAsStrings(fragment, xmlGroupByXpath);
                } catch (XPathException e) {
                    throw new IllegalArgumentException("Unable to use this XPath: " + xmlGroupByXpath, e);
                }
                if (keys.isEmpty() == false) {
                    String key = StringUtils.join(keys, " ");
                    if (groupedNodeInputSources.containsKey(key) == false) {
                        groupedNodeInputSources.put(key, new ArrayList<NodeInputSource>());
                    }
                    groupedNodeInputSources.get(key).add(nodeInputSource);
                }
            }
            for (Map.Entry<String, List<NodeInputSource>> mappedNodeInputSources : groupedNodeInputSources
                    .entrySet()) {
                List<NodeInputSource> mappedNodeInputSourcesList = mappedNodeInputSources.getValue();
                //               if (mappedNodeInputSourcesList.size()==1) { // just one, so use it
                //                  childStoredDocumentSources.add(getStoredDocumentSource(mappedNodeInputSourcesList.get(0)));
                //               }
                //               else { // multiple, we need to wrap with root node
                String key = mappedNodeInputSources.getKey();
                Node newParentNode = doc.getDocumentElement().cloneNode(false);
                for (NodeInputSource nodeInputSource : mappedNodeInputSourcesList) {
                    newParentNode.appendChild(nodeInputSource.node);
                }
                NodeInputSource newNodeInputSource = getChildStoredDocumentSource(newParentNode, parentId,
                        parentMetadata, parentId + ";group:" + key);
                newNodeInputSource.documentMetadata.setTitle(key);
                childStoredDocumentSources.add(getStoredDocumentSource(newNodeInputSource));
                //               }
            }
        } else {
            for (NodeInputSource nodeInputSource : nodeInputSources) {
                childStoredDocumentSources.add(getStoredDocumentSource(nodeInputSource));
            }
        }

    }
    // each node is a separate document
    //      if (xmlDocumentsXpaths.length == 1) {
    //         childStoredDocumentSources.addAll(getChildStoredDocumentSources(
    //               doc, xmlDocumentsXpaths[0], parentId, parentMetadata));
    //      }
    //
    //      // each xpath is a separate document
    //      else {
    //         childStoredDocumentSources.addAll(getChildStoredDocumentSources(
    //               doc, xmlDocumentsXpaths, parentId, parentMetadata));
    //      }

    storedDocumentSourceStorage.setMultipleExpandedStoredDocumentSources(parentId, childStoredDocumentSources,
            multipleExpandedStoredDocumentSourcesPrefix);

    return childStoredDocumentSources;
}

From source file:org.liveSense.misc.configloader.ConfigurationLoader.java

/**
 * Set the configuration based on the config file.
 *
 * @param f/*from   w ww  .  j  a  v a  2  s .com*/
 *            Configuration file
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
boolean setConfig(URL f) throws Exception {
    Properties p = new Properties();

    @SuppressWarnings("rawtypes")
    Dictionary ht = new Hashtable();

    InputStream in = new BufferedInputStream(f.openStream());
    try {
        // If the file name ends with .config, we using the Felix configuration format
        if (f.getFile().endsWith(".config")) {
            ht = ConfigurationHandler.read(in);
        } else {
            in.mark(1);
            boolean isXml = in.read() == '<';
            in.reset();
            if (isXml) {
                p.loadFromXML(in);
            } else {
                p.load(in);
            }
            ((Hashtable) ht).putAll(p);
        }
    } finally {
        in.close();
    }

    // Searching for templated config entry.
    // If we found one we get Java System properties
    // named as the macros. The config became activated if that
    // system proprty is set.

    Pattern macros = Pattern.compile("\\$\\{(.*?)\\}");
    boolean valid = true;

    Enumeration enumr = ht.keys();
    while (enumr.hasMoreElements()) {
        Object key = enumr.nextElement();
        if (ht.get(key) instanceof String) {
            String str = (String) ht.get(key);
            if (str != null) {
                Matcher matcher = macros.matcher(str);

                HashSet<String> propNames = new HashSet<String>();
                while (matcher.find()) {
                    propNames.add(matcher.group(1));
                }

                for (String prop : propNames) {
                    String sysProp = System.getProperty(prop);
                    if (sysProp == null) {
                        valid = false;
                    }
                    if (valid) {
                        str = StringUtils.replace(str, "${" + prop + "}", sysProp);
                        //str = str.replaceAll("\\$\\{"+prop+"\\}", sysProp);
                    }
                }
                if (valid) {
                    ht.put(key, str);
                }
            }
        }
    }

    if (valid) {
        Util.performSubstitution(p);
        String pid[] = parsePid(getName(f.getFile()));
        ht.put(CONFIGURATION_PROPERTY_NAME, getPidName(pid[0], pid[1]));

        Configuration config = getConfiguration(pid[0], pid[1]);

        /*
        // Backuping parameters for restore
        String persistanceName = pid[0]+(pid[1] == null ? "" : "-" + pid[1]);
        if (config.getProperties() != null && config.getProperties().get(CONFIGURATION_PROPERTY_NAME) == null) {
           if (persistence.load(persistanceName).isEmpty()) {
              persistence.store(persistanceName, config.getProperties());
           }
        }
         */
        if (config.getBundleLocation() != null) {
            config.setBundleLocation(null);
        }

        // If the configuration does not created by configuration loader we update it
        // In other cases (for example the user modified the loaded config) there is no configuration overwrite
        if (config.getProperties() == null || config.getProperties().get(CONFIGURATION_PROPERTY_NAME) == null
                || !config.getProperties().get(CONFIGURATION_PROPERTY_NAME).equals(getName(f.getFile()))) {
            config.update(ht);
        }
    }
    return true;
}

From source file:org.sleeksnap.ScreenSnapper.java

/**
 * Load the settings for an uploader/* w  ww. j  a v a 2s.c  om*/
 * 
 * @param uploader
 *            The uploader
 */
private void loadUploaderSettings(final Uploader<?> uploader) {
    if (!uploader.hasSettings()) {
        return;
    }
    final File file = getSettingsFile(uploader.getClass());
    if (!file.exists()) {
        final File old = getSettingsFile(uploader.getClass(), "xml");
        if (old.exists()) {
            logger.info("Converting old xml style file for " + uploader.getName() + " to json...");
            final Properties props = new Properties();
            try {
                final FileInputStream input = new FileInputStream(old);
                try {
                    props.loadFromXML(input);
                } finally {
                    input.close();
                }
                try {
                    // Update the settings
                    setUploaderSettings(uploader, new JSONObject(new JSONTokener(input)));
                    // Save it
                    if (uploader.hasSettings()) {
                        uploader.getSettings().save(file);
                    } else if (uploader.hasParent() && uploader.getParentUploader().hasSettings()) {
                        uploader.getParentUploader().getSettings().save(file);
                    }
                    // If everything went well, delete the old file
                    old.delete();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            } catch (final IOException e) {
                // It's invalid, don't try to use it
                old.delete();
            }
        }
    } else if (file.exists()) {
        try {
            final FileInputStream input = new FileInputStream(file);
            try {
                setUploaderSettings(uploader, new JSONObject(new JSONTokener(input)));
            } finally {
                input.close();
            }
        } catch (final Exception e) {
            file.delete();
        }
    }
}

From source file:de.blinkt.openvpn.ActivityDashboard.java

@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
    Log.i("ibVPN", "onCreate dashboard.");
    super.onCreate(savedInstanceState);
    // set theme by code, this will improve the speed.
    setTheme(R.style.blinkt_lolTheme);// w w w  . java 2s. c om
    setContentView(R.layout.mydash);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    myToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(myToolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
    getSupportActionBar().setTitle("");
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    myToolbar.setNavigationIcon(R.drawable.ic_action_menu);
    myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDrawerLayout.openDrawer(Gravity.LEFT);
            //  Toast.makeText(ActivityDashboard.this, "Back clicked!",     Toast.LENGTH_SHORT).show();
            Log.d("Clicked", "drawer open");
        }
    });

    findViewById(R.id.textview_checkip).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ActivityDashboard.this, ActivityContactUs.class);
            startActivity(intent);
        }
    });

    // Set the adapter for the list view
    //   mDrawerList.setAdapter(new ArrayAdapter<String>(this,
    //           R.layout.drawer_list_item, mDrawerTitles));
    mDrawerTitles = new ArrayList<>();
    mDrawerTitles.add(new NavDrawerItem(R.drawable.ic_action_menu, "Settings"));
    mDrawerTitles.add(new NavDrawerItem(R.drawable.ic_action_menu, "Connection Log"));
    mDrawerTitles.add(new NavDrawerItem(R.drawable.ic_action_menu, "Purchase"));
    mDrawerTitles.add(new NavDrawerItem(R.drawable.ic_action_menu, "Log out"));

    mDrawerList.setAdapter(new NavDrawerAdapter(this, R.layout.drawer_list_item, mDrawerTitles));
    //         Set the list's click listener
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    //        Log.d("toolbartitle",myToolbar.getTitle().toString());

    m_manager = ProfileManager.getInstance(this);

    //        mPager = (ViewPager) findViewById(R.id.pager);

    // new the handler here, so it will not leak.
    if (m_handler == null)
        m_handler = new ExtendHandler(this);
    else
        m_handler.setContext(this);
    m_remote = new RemoteAPI(this, m_handler);
    m_timer = new Timer();

    setStatus(Status.Disconnected);

    // get data from intent.
    final Intent intent = getIntent();
    m_username = intent.getStringExtra("username");
    m_password = intent.getStringExtra("password");
    m_userid = intent.getStringExtra("userid");

    // delete the vpn log.
    File file = new File(getCacheDir(), "vpnlog.txt");
    if (file.exists())
        file.delete();
    //TODO fix On Register
    // get package and server name.
    Log.d("m_password", m_password);
    m_remote.getUserService(m_userid, m_password);
    m_waitdlg = ProgressDialog.show(this, "Loading Servers", "Waiting for server reply...", true, false);

    TextView view2 = (TextView) findViewById(R.id.textview_serverlist);
    VpnStatus.addStateListener(this);

    // start internet checker timer, will not stop this.

    view2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(ActivityDashboard.this, ActivityServerList.class);
            intent.putExtra("userid", m_userid);
            intent.putExtra("username", m_userid);
            intent.putExtra("password", m_password);

            startActivity(i);

        }
    });
    m_timer.schedule(new NetStateCheckTask(this), 3000, 3000);
    try {
        FileInputStream fi = new FileInputStream(getFilesDir() + "/setting.xml");
        Log.d("d", "get files directory : " + getFilesDir().toString());

        Properties xml = new Properties();
        xml.loadFromXML(fi);
        String first_login = xml.getProperty("FIRST_LOGIN");
        if (first_login == null) {
            xml.setProperty("FIRST_LOGIN", String.valueOf(new Date().getTime()));
            FileOutputStream fo = new FileOutputStream(getFilesDir() + "/setting.xml");
            xml.storeToXML(fo, null);
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:de.blinkt.openvpn.ActivityDashboard.java

public void onConnect(View v) {
    Log.d("ibVPN", "getCurrentServer:" + getCurrentServer());

    if (!isInternetAvailable(this)) {
        Toast toast = Toast.makeText(this, "Network is unreachable.", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();/*from www.j a  v  a 2s . c  o  m*/
        return;
    }

    if (((Button) v).getText().toString().equalsIgnoreCase(getString(R.string.text_connect))) {
        setStatus(Status.Connecting);
        dicojugar = false;
        //            m_openvpn = new OpenVPN(m_handler, this);    // new it here, so cancel will not crash.
        String server = getCurrentServer();
        // get session name.
        TextView locationServer = (TextView) findViewById(R.id.view_location);
        String session = locationServer.toString();
        Log.d("Seleceted item", session);

        // connecting to server.
        String port = getProperty("PORT");
        String proto = getProperty("PROTOCOL");

        setLogin(m_username, m_password);
        setRemote(server, port == null ? "1197" : port);
        setSession(session);
        setProtocol(proto == null ? "tcp" : proto);

        //            m_openvpn.connect();    // start the service, but it is not connected.

        updateOvpnConfigFromAssets(m_server, m_port, m_proto, m_extra);

        m_vpnprofile = createVPNProfile();
        m_vpnprofile.mUsername = m_username;
        m_vpnprofile.mPassword = m_password;
        m_manager.addProfile(m_vpnprofile);
        m_manager.saveProfile(this, m_vpnprofile);
        m_manager.saveProfileList(this);

        //            gotoMainActivity();
        //            ProfileManager.updateLRU(this, m_vpnprofile);
        //            VPNLaunchHelper.startOpenVpn(m_vpnprofile, getBaseContext());

        startVPN(m_vpnprofile);
        //            permissionConnect();
        m_date = System.currentTimeMillis();
    } else if (((Button) v).getText().toString().equalsIgnoreCase(getString(R.string.text_cancel))) {
        //            m_openvpn.cancel();
        if (VpnStatus.isVPNActive()) {
            if (mService != null) {
                try {
                    mService.stopVPN(false);
                } catch (RemoteException e) {
                    VpnStatus.logException(e);
                }
            }
        }
        setStatus(Status.Disconnected);
        //mixpanelTrack("Cancel Connection", null);
    } else if (((Button) v).getText().toString().equalsIgnoreCase(getString(R.string.text_disconnect))) {
        //            .disconnect();

        if (VpnStatus.isVPNActive()) {
            if (mService != null) {
                try {
                    mService.stopVPN(false);
                } catch (RemoteException e) {
                    VpnStatus.logException(e);
                }
            }
        }
        setStatus(Status.Disconnected);
        dicojugar = true;

        String dura = formatTime(System.currentTimeMillis() - m_date);
        Log.d("ibVPN", "Session Duration: " + dura);

        JSONObject props = new JSONObject();
        mixpanelAdd(props, "Session Duration", dura);
        //mixpanelTrack("Disconnect", props);
        Log.d("ibVPN", "props: " + props);

        try {
            FileInputStream fi = new FileInputStream(getFilesDir() + "/setting.xml");
            Log.d("d", "get files directory : " + getFilesDir().toString());
            Properties xml = new Properties();
            xml.loadFromXML(fi);

            String first_login = xml.getProperty("FIRST_LOGIN");
            String first_conn = xml.getProperty("FIRST_CONNECTED");
            if (first_conn == null) {
                first_conn = String.valueOf(new Date().getTime());
                xml.setProperty("FIRST_CONNECTED", first_conn);
                FileOutputStream fo = new FileOutputStream(getFilesDir() + "/setting.xml");
                xml.storeToXML(fo, null);

                JSONObject json = new JSONObject();
                mixpanelAdd(json, "First Login Time", first_login);
                mixpanelAdd(json, "First Connected Time", first_conn);
                mixpanelAdd(json, "Accomodation Time",
                        String.valueOf(Long.parseLong(first_conn) - Long.parseLong(first_login)));
                //mixpanelTrack("Application 1st Time Connected", json);
                Log.d("ibVPN", "props: " + json);
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        JSONObject logs = new JSONObject();
        mixpanelAdd(logs, "Data", loadLogFromFile());
        //mixpanelTrack("Connection Log", logs);
    }
}