Example usage for java.lang ThreadGroup ThreadGroup

List of usage examples for java.lang ThreadGroup ThreadGroup

Introduction

In this page you can find the example usage for java.lang ThreadGroup ThreadGroup.

Prototype

public ThreadGroup(String name) 

Source Link

Document

Constructs a new thread group.

Usage

From source file:org.apache.hadoop.hdfs.server.datanode.DataNode.java

/**
 * This method starts the data node with the specified conf.
 * //ww  w.  ja  v a2 s  .com
 * @param conf - the configuration
 *  if conf's CONFIG_PROPERTY_SIMULATED property is set
 *  then a simulated storage based data node is created.
 * 
 * @param dataDirs - only for a non-simulated storage data node
 * @throws IOException
 * @throws MalformedObjectNameException 
 * @throws MBeanRegistrationException 
 * @throws InstanceAlreadyExistsException 
 */
void startDataNode(Configuration conf, AbstractList<File> dataDirs, SecureResources resources)
        throws IOException {
    if (UserGroupInformation.isSecurityEnabled() && resources == null)
        throw new RuntimeException("Cannot start secure cluster without " + "privileged resources.");

    this.secureResources = resources;
    // use configured nameserver & interface to get local hostname
    if (conf.get("slave.host.name") != null) {
        machineName = conf.get("slave.host.name");
    }
    if (machineName == null) {
        machineName = DNS.getDefaultHost(conf.get("dfs.datanode.dns.interface", "default"),
                conf.get("dfs.datanode.dns.nameserver", "default"));
    }
    InetSocketAddress nameNodeAddr = NameNode.getServiceAddress(conf, true);

    this.socketTimeout = conf.getInt("dfs.socket.timeout", HdfsConstants.READ_TIMEOUT);
    this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT);
    /* Based on results on different platforms, we might need set the default 
     * to false on some of them. */
    this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed", true);
    this.writePacketSize = conf.getInt("dfs.write.packet.size", 64 * 1024);

    InetSocketAddress socAddr = DataNode.getStreamingAddr(conf);
    int tmpPort = socAddr.getPort();
    storage = new DataStorage();
    // construct registration
    this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);

    // connect to name node
    this.namenode = (DatanodeProtocol) RPC.waitForProxy(DatanodeProtocol.class, DatanodeProtocol.versionID,
            nameNodeAddr, conf);
    // get version and id info from the name-node
    NamespaceInfo nsInfo = handshake();
    StartupOption startOpt = getStartupOption(conf);
    assert startOpt != null : "Startup option must be set.";

    boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false);
    if (simulatedFSDataset) {
        setNewStorageID(dnRegistration);
        dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
        dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
        // it would have been better to pass storage as a parameter to
        // constructor below - need to augment ReflectionUtils used below.
        conf.set("StorageId", dnRegistration.getStorageID());
        try {
            //Equivalent of following (can't do because Simulated is in test dir)
            //  this.data = new SimulatedFSDataset(conf);
            this.data = (FSDatasetInterface) ReflectionUtils.newInstance(
                    Class.forName("org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"), conf);
        } catch (ClassNotFoundException e) {
            throw new IOException(StringUtils.stringifyException(e));
        }
    } else { // real storage
        // read storage info, lock data dirs and transition fs state if necessary
        storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
        // adjust
        this.dnRegistration.setStorageInfo(storage);
        // initialize data node internal structure
        this.data = new FSDataset(storage, conf);
    }

    // register datanode MXBean
    this.registerMXBean(conf); // register the MXBean for DataNode

    // Allow configuration to delay block reports to find bugs
    artificialBlockReceivedDelay = conf.getInt("dfs.datanode.artificialBlockReceivedDelay", 0);

    // find free port or use privileged port provide
    ServerSocket ss;
    if (secureResources == null) {
        ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
        Server.bind(ss, socAddr, 0);
    } else {
        ss = resources.getStreamingSocket();
    }
    ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
    // adjust machine name with the actual port
    tmpPort = ss.getLocalPort();
    selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(), tmpPort);
    this.dnRegistration.setName(machineName + ":" + tmpPort);
    LOG.info("Opened info server at " + tmpPort);

    this.threadGroup = new ThreadGroup("dataXceiverServer");
    this.dataXceiverServer = new Daemon(threadGroup, new DataXceiverServer(ss, conf, this));
    this.threadGroup.setDaemon(true); // auto destroy when empty

    this.blockReportInterval = conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
    this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay", BLOCKREPORT_INITIAL_DELAY)
            * 1000L;
    if (this.initialBlockReportDelay >= blockReportInterval) {
        this.initialBlockReportDelay = 0;
        LOG.info("dfs.blockreport.initialDelay is greater than " + "dfs.blockreport.intervalMsec."
                + " Setting initial delay to 0 msec:");
    }
    this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
    DataNode.nameNodeAddr = nameNodeAddr;

    //initialize periodic block scanner
    String reason = null;
    if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
        reason = "verification is turned off by configuration";
    } else if (!(data instanceof FSDataset)) {
        reason = "verifcation is supported only with FSDataset";
    }
    if (reason == null) {
        blockScanner = new DataBlockScanner(this, (FSDataset) data, conf);
    } else {
        LOG.info("Periodic Block Verification is disabled because " + reason + ".");
    }

    //create a servlet to serve full-file content
    InetSocketAddress infoSocAddr = DataNode.getInfoAddr(conf);
    String infoHost = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    this.infoServer = (secureResources == null)
            ? new HttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0, conf,
                    SecurityUtil.getAdminAcls(conf, DFSConfigKeys.DFS_ADMIN))
            : new HttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0, conf,
                    SecurityUtil.getAdminAcls(conf, DFSConfigKeys.DFS_ADMIN), secureResources.getListener());
    if (conf.getBoolean("dfs.https.enable", false)) {
        boolean needClientAuth = conf.getBoolean("dfs.https.need.client.auth", false);
        InetSocketAddress secInfoSocAddr = NetUtils
                .createSocketAddr(conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
        Configuration sslConf = new Configuration(false);
        sslConf.addResource(conf.get("dfs.https.server.keystore.resource", "ssl-server.xml"));
        this.infoServer.addSslListener(secInfoSocAddr, sslConf, needClientAuth);
    }
    this.infoServer.addInternalServlet(null, "/streamFile/*", StreamFile.class);
    this.infoServer.addInternalServlet(null, "/getFileChecksum/*", FileChecksumServlets.GetServlet.class);

    this.infoServer.setAttribute("datanode", this);
    this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
    this.infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
    this.infoServer.addServlet(null, "/blockScannerReport", DataBlockScanner.Servlet.class);

    if (WebHdfsFileSystem.isEnabled(conf, LOG)) {
        infoServer.addJerseyResourcePackage(
                DatanodeWebHdfsMethods.class.getPackage().getName() + ";" + Param.class.getPackage().getName(),
                WebHdfsFileSystem.PATH_PREFIX + "/*");
    }
    this.infoServer.start();
    // adjust info port
    this.dnRegistration.setInfoPort(this.infoServer.getPort());
    myMetrics = DataNodeInstrumentation.create(conf, dnRegistration.getStorageID());

    // set service-level authorization security policy
    if (conf.getBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
        ServiceAuthorizationManager.refresh(conf, new HDFSPolicyProvider());
    }

    // BlockTokenSecretManager is created here, but it shouldn't be
    // used until it is initialized in register().
    this.blockTokenSecretManager = new BlockTokenSecretManager(false, 0, 0);
    //init ipc server
    InetSocketAddress ipcAddr = NetUtils.createSocketAddr(conf.get("dfs.datanode.ipc.address"));
    ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
            conf.getInt("dfs.datanode.handler.count", 3), false, conf, blockTokenSecretManager);
    dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());

    LOG.info("dnRegistration = " + dnRegistration);
}

From source file:com.dell.asm.asmcore.asmmanager.app.AsmManagerApp.java

private void initAsmManagerApp() {
    try {//from   w w  w  .  j a v  a2s  .  c  o m
        Properties props = ConfigurationUtils.resolveAndReadPropertiesFile(ASM_MANAGER_CONFIG_FILE,
                this.getClass().getClassLoader());

        ASM_REPO_LOCATION = props.getProperty("asm_repo_location");
        razorApiUrl = props.getProperty(RAZOR_API_URL_PROPERTY);
        razorRepoStoreLocation = props.getProperty(RAZOR_REPO_STORE_PROPERTY);
        _logger.info("razorApiUrl = " + razorApiUrl);
        razorCron = props.getProperty(RAZOR_JOB_CRON_PROPERTY);
        _logger.info("razorCron = " + razorCron);
        asmDeployerApiUrl = props.getProperty(ASM_DEPLOYER_URL_PROPERTY);
        _logger.info("asmDeployerApiUrl = " + asmDeployerApiUrl);
        scheduledInventoryCron = props.getProperty(SCHEDULEDINVENTORY_JOB_CRON_PROPERTY);
        _logger.info("Scheduled Inventory cron expression =" + scheduledInventoryCron);
        fileSystemMaintenanceCron = props.getProperty(FILE_SYSTEM_MAINTENANCE_JOB_CRON_PROPERTY);
        _logger.info("Scheduled File SystemMaintenance cron expression =" + fileSystemMaintenanceCron);

        // must call as soon as we read URLs from property file
        ProxyUtil.initAsmDeployerProxy();

        final GenericDAO genericDAO = GenericDAO.getInstance();
        SettingEntity portsToPingSetting = genericDAO.getByName(ASM_PORTS_TO_PING, SettingEntity.class);
        if (portsToPingSetting == null) {
            String value = props.getProperty(PORTS_TO_PING_PROPERTY);
            if (value == null) {
                value = "22,80,135";
            }
            portsToPingSetting = new SettingEntity();
            portsToPingSetting.setName(ASM_PORTS_TO_PING);
            portsToPingSetting.setValue(value);
            genericDAO.create(portsToPingSetting);
        }
        List<String> items = Arrays.asList(portsToPingSetting.getValue().split("\\s*,\\s*"));
        _logger.info("Ports to ping configured to " + Arrays.toString(items.toArray()) + " ("
                + portsToPingSetting.getValue() + ")");

        setAsmManagerAppConfig(new AsmManagerAppConfig());

        String sConnectTimeout = props.getProperty(DISCOVERY_THREAD_CONNECT_TIMEOUT_PROPERTY);
        _logger.info("sConnectTimeout = " + sConnectTimeout);
        try {
            CONNECT_TIMEOUT = Integer.parseInt(sConnectTimeout);
            CONNECT_TIMEOUT = CONNECT_TIMEOUT * 1000;
        } catch (Exception e) {
            _logger.error("Unable to parse CONNECT_TIMEOUT", e);
        }

        String staggerDeploymentsSecs = props.getProperty(MULTI_DEPLOYMENTS_STAGGER_SECS_KEY);
        try {
            MULTI_DEPLOYMENTS_STAGGER_SECS = Integer.parseInt(staggerDeploymentsSecs);
        } catch (NumberFormatException nfe) {
            _logger.error("Unable to parse MULTI_DEPLOYMENTS_STAGGER_SECS_KEY: " + staggerDeploymentsSecs
                    + ", defaulting to 30 minutes");
            MULTI_DEPLOYMENTS_STAGGER_SECS = 30 * 60;
        }

        String sPuppetModulestoFilter = props.getProperty(PUPPET_MODULE_FILTER_PROPERTY);
        _logger.info("sPuppetModulestoFilter = " + sPuppetModulestoFilter);
        String[] parts = sPuppetModulestoFilter.split(",");
        if (parts != null) {
            for (String sModule : parts) {
                if (sModule != null) {
                    puppetModulesToFilter.add(sModule.trim());
                    _logger.info("Puppet module to filter:" + sModule.trim());
                }
            }
        }

        // this prevents exceptions on copyProperties with null Date
        ConvertUtilsBean convertUtilsBean = BeanUtilsBean.getInstance().getConvertUtils();
        convertUtilsBean.register(false, true, -1);
    } catch (IOException e) {
        _logger.info("Exception while parsing asmmanager properties file", e);
        throw new AsmManagerRuntimeException(e);
    }

    try {
        registerJobClasses();
        createDefaultRazorSyncJob();
    } catch (Exception t) {
        _logger.error("Unable to initialize AsmManagerApp. Register Jobs Failed.", t);
    }

    // Perform all initialization on a new thread to avoid holding up server initialization.
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            _logger.info("Starting AsmManagerApp initialization thread.");

            AsmManagerInitLifecycleListener.setStatus(AsmManagerInitLifecycleListener.UPDATING_INVENTORY);

            // Install Quartz Job Listeners
            try {
                FirmwareUpdateScheduleListener scheduleListener = new FirmwareUpdateScheduleListener();
                JobManager.getInstance().getScheduler().getListenerManager()
                        .addSchedulerListener(scheduleListener);

                GroupMatcher<JobKey> groupMatcher = GroupMatcher
                        .groupEquals(FirmwareUpdateJob.class.getSimpleName());
                JobManager.getInstance().getScheduler().getListenerManager().addJobListener(scheduleListener,
                        groupMatcher);

            } catch (Exception t) {
                _logger.error("Failed to install FirmwareUpdateScheduleListener", t);
            }

            try {
                setServiceContextUser(DBInit.DEFAULT_USER);
            } catch (Exception t) {
                _logger.error(
                        "Unable to initialize AsmManagerApp. Set service context default user to Admin failed.",
                        t);
            }

            try {
                // On Startup - Where we check to see if it exists (reverse) - If file does NOT exist - Run Inventory and create the file
                if (isRestore() || isRestartAfterApplianceUpdate()) {
                    // Run inventory on all Devices
                    runInventory();
                }
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Running Inventory Failed.", t);
            }

            AsmManagerInitLifecycleListener.setStatus(AsmManagerInitLifecycleListener.UPDATING_TEMPLATES);

            try {
                createDefaultIOMCredential();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Creation of Default IOM Credential Failed.",
                        t);
            }

            try {
                updateExistingAddOnModules();
                updateAddOnModules();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Updating AddOnModules Failed.", t);
            }

            try {
                loadDefaultTemplates();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Loading of Default Templates Failed.", t);
            }

            try {
                updateFirmwareRepositoryBundleComponents();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Updating Firmware Bundle Components Failed.",
                        t);
            }
            try {
                loadEmbeddedFirmware();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Load embedded Firmware Failed.", t);
            }
            try {
                failCopyingAndPendingFirmwareRepositories();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Cleanup of rogue Firmware states Failed.",
                        t);
            }

            try {
                cleanUpDevices();
                cleanUpJobs();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Cleanup of Devices and Jobs Failed.", t);
            }

            try {
                ensureRazorReposExist();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Ensuring Razor Repos Exist Failed.", t);
            }

            try {
                syncAppStateVars();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Sync Application State Variables Failed.",
                        t);
            }

            /**
             * Important to run this prior to revalidating ServiceTemplates since a broken OS
             * repository would then invalidate the template, which is the desired behavior.
             */
            try {
                cleanUpOsRepositories();
            } catch (Exception t) {
                _logger.error("Problem initializing AsmManagerApp.  Cleaning up OSRepositories failed.", t);
            }

            try {
                final ServiceTemplate defaultTemplate = getServiceTemplateService().getDefaultTemplate();
                //build a map of add on module components for future use.
                final List<AddOnModuleComponentEntity> addOnModuleComponentEntities = getAddOnModuleComponentsDAO()
                        .getAll(true);
                Map<String, ServiceTemplateComponent> addOnModuleComponentsMap = new HashMap<>();
                for (AddOnModuleComponentEntity entity : addOnModuleComponentEntities) {
                    ServiceTemplateComponent component = MarshalUtil.unmarshal(ServiceTemplateComponent.class,
                            entity.getMarshalledData());
                    addOnModuleComponentsMap.put(component.getId(), component);
                }

                // Correct differences between entity object values and entity marshaledTemplateData values
                reconcileServiceTemplateEntityData();
                revalidateStoredTemplates(defaultTemplate, addOnModuleComponentsMap);
                revalidateDeployedTemplates(defaultTemplate, addOnModuleComponentEntities,
                        addOnModuleComponentsMap);
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Revalidating Templates Failed.", t);
            }

            try {
                createDefaultScheduledInventoryJob();
                createDefaultFileSystemMaintenanceJob();
                // please make sure there that all update deployment DAO calls made _before_ this line!!!
                createScheduledDeploymentStatusSyncJob(JOB_DELAY_SECS);
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Creation of default jobs failed.", t);
            }

            AsmManagerInitLifecycleListener.setStatus(AsmManagerInitLifecycleListener.READY);
            _logger.info("Finished AsmManagerApp initialization.");

        }
    };

    // Run the initialization code in our thread group.
    Thread initThread = new Thread(new ThreadGroup(AsmManagerApp_THREADGROUP_NAME), runnable);
    initThread.setName(AsmManagerApp_INIT_THREAD_NAME);
    initThread.setDaemon(true);
    initThread.start();
}

From source file:ECallCenter21.java

/**
 *
 * @throws SQLException/*from   w  ww .  j av  a2  s  . co m*/
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws Exception
 */
@SuppressWarnings({ "static-access", "static-access", "static-access" })
public ECallCenter21() throws SQLException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, NoSuchMethodException, InvocationTargetException, Exception {
    eCallCenterReference = this; // A thread doesn't inherit local varables, but it does local finals / constants

    String[] status = new String[2];

    //        sipstateUpdateThreadPool = Executors.newCachedThreadPool();
    //        responseUpdateThreadPool = Executors.newCachedThreadPool();

    platform = System.getProperty("os.name").toLowerCase();
    if (platform.indexOf("windows") != -1) {
        fileSeparator = "\\";
        lineTerminator = "\r\n";
    } else {
        fileSeparator = "/";
        lineTerminator = "\r\n";
    }

    plaf = new String[4];
    plafSelected = new String();
    plaf[0] = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
    plaf[1] = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
    plaf[2] = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
    plaf[3] = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";

    setLookAndFeel(PLAF_NIMBUS);

    setMinimumSize(new Dimension(710, 598));
    setMaximumSize(new Dimension(710, 830));
    setPreferredSize(getMaximumSize());
    setResizable(false);
    setVisible(false);
    setVisible(true);
    initComponents();

    Thread defaultConstructorThread = new Thread(allThreadsGroup, new Runnable() {
        @Override
        public void run() {
            String[] status = new String[2];
            String imgName = "/images/voipstormboxicon.jpg";
            URL imgURL = getClass().getResource(imgName);
            Image image = Toolkit.getDefaultToolkit().getImage(imgURL);
            setIconImage(image);
            setImagePanelVisible(true);
            initSlidersSmooth();

            sysMonitor = new SysMonitor();

            dataDir = "data" + fileSeparator;
            soundsDir = dataDir + "sounds" + fileSeparator;
            vergunningDir = dataDir + "license" + fileSeparator;
            databasesDir = dataDir + "databases" + fileSeparator;
            configDir = dataDir + "config" + fileSeparator;
            binDir = dataDir + "bin" + fileSeparator;
            logDir = dataDir + "log" + fileSeparator;

            currentTimeCalendar = Calendar.getInstance();
            logDateString = "" + String.format("%04d", currentTimeCalendar.get(Calendar.YEAR))
                    + String.format("%02d", currentTimeCalendar.get(Calendar.MONTH) + 1)
                    + String.format("%02d", currentTimeCalendar.get(Calendar.DAY_OF_MONTH)) + "_"
                    + String.format("%02d", currentTimeCalendar.get(Calendar.HOUR_OF_DAY))
                    + String.format("%02d", currentTimeCalendar.get(Calendar.MINUTE))
                    + String.format("%02d", currentTimeCalendar.get(Calendar.SECOND));
            logFileString = logDir + logDateString + "_" + THISPRODUCT + ".log";

            //        System.out.println("\r\nChecking Directories...");
            showStatus(Vergunning.PRODUCT + "Checking Directories...", true, false);
            boolean missingDirsDetected = false;
            boolean missingCriticalDirsDetected = false;
            file = new File(logDir);
            if (!file.exists()) {
                if (new File(logDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Info:     Creating missing directory: " + logDir, true, false);
                }
            }
            file = new File(dataDir);
            if (!file.exists()) {
                if (new File(dataDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Warning:  Creating missing directory: " + dataDir, true, true);
                }
            }
            file = new File(soundsDir);
            if (!file.exists()) {
                if (new File(soundsDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Critical: Creating missing directory: " + soundsDir, true, true);
                    missingCriticalDirsDetected = true;
                }
            }
            file = new File(vergunningDir);
            if (!file.exists()) {
                if (new File(vergunningDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Info:     Creating missing directory: " + vergunningDir, true, true);
                }
            }
            file = new File(databasesDir);
            if (!file.exists()) {
                if (new File(databasesDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Info:     Creating missing directory: " + databasesDir, true, true);
                }
            }
            file = new File(configDir);
            if (!file.exists()) {
                if (new File(configDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Info:     Creating missing directory: " + configDir, true, true);
                }
            }
            file = new File(binDir);
            if (!file.exists()) {
                if (new File(binDir).mkdir()) {
                    missingDirsDetected = true;
                    showStatus("Critical: Creating missing directory: " + binDir, true, true);
                    missingCriticalDirsDetected = true;
                }
            }
            if (missingCriticalDirsDetected) {
                showStatus(
                        "Critical directories were missing!!! Please download the entire VoipStorm package at: "
                                + Vergunning.WEBLINK,
                        true, true);
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException ex) {
                }
            }
            if (missingDirsDetected) {
                showStatus("VoipStorm directory structure built", true, true);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }

            try {
                weblog = new WebLog();
            } catch (Exception ex) {
            }

            Thread webLogThread = new Thread(new Runnable() {
                @Override
                @SuppressWarnings({ "static-access" })
                public void run() {
                    try {
                        weblog.send(THISPRODUCT + " Starting");
                    } catch (Exception ex) {
                    }
                }
            });
            webLogThread.setName("webLogThread");
            webLogThread.setDaemon(runThreadsAsDaemons);
            webLogThread.start();

            registerSpeedValue.setText(Integer.toString(registrationBurstDelay));
            registrationBurstDelay = registerSpeedSlider.getValue();
            inboundRingingResponseDelayValue
                    .setText(Integer.toString(inboundRingingResponseDelaySlider.getValue()));
            inboundRingingResponseBusyRatioValue
                    .setText(Integer.toString(inboundRingingResponseBusyRatioSlider.getValue()));
            inboundEndDelayValue.setText(Integer.toString(inboundEndDelaySlider.getValue()));

            vmUsagePauseValue.setText(Integer.toString(vmUsageThresholdSlider.getValue()));
            vmUsagePauseThreashold = vmUsageThresholdSlider.getValue();
            memFreeThresholdValue.setText(Integer.toString(memFreeThresholdSlider.getValue()));
            memFreeThreshold = memFreeThresholdSlider.getValue();
            heapMemFreeThresholdValue.setText(Integer.toString(heapMemFreeThresholdSlider.getValue()));
            heapMemFreeThreshold = heapMemFreeThresholdSlider.getValue();
            connectingTallyLimitValue.setText(Integer.toString(connectingTallyLimitSlider.getValue()));
            connectingTallyLimit = connectingTallyLimitSlider.getValue();
            callingTallyLimitValue.setText(Integer.toString(callingTallyLimitSlider.getValue()));
            callingTallyLimit = callingTallyLimitSlider.getValue();
            establishedTallyLimitValue.setText(Integer.toString(establishedTallyLimitSlider.getValue()));
            establishedTallyLimit = establishedTallyLimitSlider.getValue();
            callSpeedValue.setText(Integer.toString(callSpeedSlider.getValue()));
            outboundBurstDelay = callSpeedSlider.getValue();

            status = new String[2];
            status[0] = "0";
            status[1] = "";

            nlLocale = new Locale("nl");
            boundMode = "Outbound";
            callCenterStatus = POWEREDOFF;

            //        status = shell.getPID(); if (status[0].equals("0"))
            //        {
            //            pid = Integer.parseInt(status[1]);
            //            outboundCallsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "In/Outbound Campaign Controls " + Integer.toString(pid), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("STHeiti", 0, 14), new java.awt.Color(255, 255, 255))); // NOI18N
            //        }
            //        else { pid = 0; }

            softphonesQuantity = 0;

            setTitle(getWindowTitle());
            //   mainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, getBrand() + " " + getProduct() + " " + getVersion(), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("STHeiti", 0, 12), new java.awt.Color(102, 102, 102))); // NOI18N
            //   configurationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Proxy Configuration", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("STHeiti", 0, 12), new java.awt.Color(255, 255, 255))); // NOI18N

            // Starting the Database Server

            ultraShortMessagePeriod = 0;
            smoothMovementPeriod = 40;
            //   eyeBlinkMessagePeriod = 250;
            //           shortMessagePeriod = 1000;
            mediumMessagePeriod = 2000;
            myCoordinate = new Coordinate();

            brandLabel.setText(Vergunning.BRAND);
            brandDescriptionLabel.setText(Vergunning.BRAND_DESCRIPTION);
            productLabel.setText(Vergunning.PRODUCT);
            productDescriptionLabel.setText(Vergunning.PRODUCT_DESCRIPTION);
            copyrightLabel.setText(getWarning() + " " + getCopyright() + " " + getBrand() + " " + getBusiness()
                    + " - Author: " + getAuthor());

            debugging = false;
            allThreadsGroup = new ThreadGroup("AllThreads");
            vmUsageStatus = new String[2];
            memFreeStatus = new String[2];

            localDisplayData = new DisplayData();
            //   localSpeakerData    = new SpeakerData();

            vmUsageStatus[0] = "0";
            vmUsageStatus[1] = "";
            memFreeStatus[0] = "0";
            memFreeStatus[1] = "";

            //   inboundSoftPhonesAvailableCounter = 0;
            inboundInstanceCounter = 0;
            outboundInstanceCounter = 0;
            //        outboundPowerToggleButton.setEnabled(false);

            //        myClickOnSoundTool          = new SoundTool(SoundTool.CLICKONTONE);
            //        myClickOffSoundTool         = new SoundTool(SoundTool.CLICKOFFTONE);
            //        mySuccessSoundTool          = new SoundTool(SoundTool.SUCCESSTONE);
            //        myPowerSuccessSoundTool     = new SoundTool(SoundTool.POWERSUCCESSTONE);
            //        myFailureSoundTool          = new SoundTool(SoundTool.FAILURETONE);
            //        myTickSoundTool             = new SoundTool(SoundTool.TICKTONE);
            //        myRegisterEnabledSoundTool  = new SoundTool(SoundTool.REGISTERENABLEDTONE);
            //        myRegisterDisabledSoundTool = new SoundTool(SoundTool.REGISTERDISABLEDTONE);
            //        myAnswerEnabledSoundTool    = new SoundTool(SoundTool.ANSWERENABLEDTONE);
            //        myAnswerDisabledSoundTool   = new SoundTool(SoundTool.ANSWERDISABLEDTONE);
            //        myCancelEnabledSoundTool    = new SoundTool(SoundTool.CANCELENABLEDTONE);
            //        myCancelDisabledSoundTool   = new SoundTool(SoundTool.CANCELDISABLEDTONE);
            //        myMuteEnabledSoundTool      = new SoundTool(SoundTool.MUTEENABLEDTONE);
            //        myMuteDisabledSoundTool     = new SoundTool(SoundTool.MUTEDISABLEDTONE);
            //
            //        myRingToneSoundTool         = new SoundTool(SoundTool.RINGTONE);
            //        myDialToneSoundTool         = new SoundTool(SoundTool.DEADTONE);
            //        myCallToneSoundTool         = new SoundTool(SoundTool.CALLTONE);
            //        myBusyToneSoundTool         = new SoundTool(SoundTool.BUSYTONE);
            //        myDeadToneSoundTool         = new SoundTool(SoundTool.DEADTONE);
            //        myErrorToneSoundTool        = new SoundTool(SoundTool.ERRORTONE);

            configurationCallCenter = new Configuration();
            showStatus("Loading CallCenter Configuration...", true,
                    true); /* true = logToApplic, true = logToFile */
            status = configurationCallCenter.loadConfiguration("3");
            if (status[0].equals("1")) // loadConfig failed
            {
                logToApplication("Loading CallCenter Configuration Failed: " + status[1]);
                showStatus("Loading CallCenter Configuration Failed, creating new Inbound Config", true,
                        true); /* true = logToApplic, true = logToFile */
                configurationCallCenter.createConfiguration();
                clientIPField.setText(configurationCallCenter.getClientIP());
                pubIPField.setText(configurationCallCenter.getPublicIP());
                clientPortField.setText(configurationCallCenter.getClientPort());
                domainField.setText(configurationCallCenter.getDomain());
                serverIPField.setText(configurationCallCenter.getServerIP());
                serverPortField.setText(configurationCallCenter.getServerPort());
                prefPhoneLinesSlider.setMaximum(vergunning.getPhoneLines());
                prefPhoneLinesSlider.setValue(vergunning.getPhoneLines());
                usernameField.setText(configurationCallCenter.getUsername());
                toegangField.setText(configurationCallCenter.getToegang());
                if (configurationCallCenter.getRegister().equals("1")) {
                    registerCheckBox.setSelected(true);
                } else {
                    registerCheckBox.setSelected(false);
                }
                if (configurationCallCenter.getIcons().equals("1")) {
                    iconsCheckBox.setSelected(true);
                } else {
                    iconsCheckBox.setSelected(false);
                }
                showStatus("Saving new CallCenter Configuration...", true,
                        true); /* true = logToApplic, true = logToFile */
                configurationCallCenter.saveConfiguration("3");
                //            myFailureSoundTool.play();
            } else // loadConfig Succeeded
            {
                //            myPowerSuccessSoundTool.play();
                clientIPField.setText(configurationCallCenter.getClientIP());
                pubIPField.setText(configurationCallCenter.getPublicIP());
                clientPortField.setText(configurationCallCenter.getClientPort());
                domainField.setText(configurationCallCenter.getDomain());
                serverIPField.setText(configurationCallCenter.getServerIP());
                serverPortField.setText(configurationCallCenter.getServerPort());

                prefPhoneLinesSlider.setMaximum(Integer.parseInt(configurationCallCenter.getPrefPhoneLines()));
                prefPhoneLinesSlider.setValue(Integer.parseInt(configurationCallCenter.getPrefPhoneLines()));

                usernameField.setText(configurationCallCenter.getUsername());
                toegangField.setText(configurationCallCenter.getToegang());
                if (configurationCallCenter.getRegister().equals("1")) {
                    registerCheckBox.setSelected(true);
                } else {
                    registerCheckBox.setSelected(false);
                }
                if (configurationCallCenter.getIcons().equals("1")) {
                    iconsCheckBox.setSelected(true);
                } else {
                    iconsCheckBox.setSelected(false);
                }
                showStatus("CallCenter Configuration Loaded Successfully", true,
                        true); /* true = logToApplic, true = logToFile */
            }

            icons = new Icons(PHONESPOOLTABLECOLUMNWIDTH, PHONESPOOLTABLECOLUMNHEIGHT,
                    iconsCheckBox.isSelected());

            lastTimeDashboardCalendar = Calendar.getInstance();
            currentTimeDashboardCalendar = Calendar.getInstance(); // Prevent nullpointer in dashboard timer

            updateSystemStatsTimer = new Timer();
            updateSystemStatsTimer.scheduleAtFixedRate(new UpdateSystemStatsTimer(eCallCenterReference),
                    (long) (0), updateSystemStatsTimerFastInterval);
            showStatus(
                    "updateSystemStatsTimer Scheduled immediate at "
                            + Math.round(updateSystemStatsTimerFastInterval / 1000) + " Sec Interval",
                    true, true); /* true = logToApplic, true = logToFile */
            updateStallerTimer = new Timer();
            updateStallerTimer.scheduleAtFixedRate(new UpdateStallerDetectorTimer(eCallCenterReference),
                    (long) (0), updateStallerTimerInterval);
            showStatus(
                    "updateStallerTimer     Scheduled immediate at "
                            + Math.round(updateStallerTimerInterval / 1000) + " Sec Interval",
                    true, true); /* true = logToApplic, true = logToFile */
            updateVergunningTimer = new Timer();
            updateVergunningTimer.scheduleAtFixedRate(new UpdateVergunningTimer(eCallCenterReference),
                    (long) (0), updateVergunningTimerInterval);
            showStatus(
                    "updateLicenseTimer     Scheduled immediate at "
                            + Math.round(updateVergunningTimerInterval / 1000) + " Sec Interval",
                    true, true); /* true = logToApplic, true = logToFile */
            updateDashboardTimer = new Timer();
            updateDashboardTimer.scheduleAtFixedRate(new UpdateDashboardTimer(eCallCenterReference), (long) (0),
                    updateDashboardTimerInterval);
            showStatus(
                    "updateDashboardTimer   Scheduled immediate at "
                            + Math.round(updateDashboardTimerInterval / 1000) + " Sec Interval",
                    true, true); /* true = logToApplic, true = logToFile */
            updateAutoSpeedTimer = new Timer();
            updateAutoSpeedTimer.scheduleAtFixedRate(new UpdateAutoSpeedTimer(eCallCenterReference), (long) (0),
                    updateAutoSpeedTimerInterval);
            showStatus(
                    "updateAutoSpeedTimer   Scheduled immediate at "
                            + Math.round(updateAutoSpeedTimerInterval / 1000) + " Sec Interval",
                    true, true); /* true = logToApplic, true = logToFile */

            shell = new Shell();
            platform = shell.getPlatform().toLowerCase();
            if (platform.indexOf("mac os x") != -1) {
                systemStatsTable.setValueAt("RealMemFree", 2, 0);
            } else if (platform.indexOf("linux") != -1) {
                systemStatsTable.setValueAt("TotMemFree", 2, 0);
            } //phonesPoolTable.setFont(new java.awt.Font("STHeiti", 0, 12));
            else if (platform.indexOf("sunos") != -1) {
                systemStatsTable.setValueAt("TotMemFree", 2, 0);
            } else if (platform.indexOf("hpux") != -1) {
                systemStatsTable.setValueAt("TotMemFree", 2, 0);
            } else if (platform.indexOf("aix") != -1) {
                systemStatsTable.setValueAt("TotMemFree", 2, 0);
            } else if (platform.indexOf("bsd") != -1) {
                systemStatsTable.setValueAt("TotMemFree", 2, 0);
            } else if (platform.indexOf("windows") != -1) {
                systemStatsTable.setValueAt("TotMemFree", 2, 0);
            } else {
                systemStatsTable.setValueAt(platform + "?", 2, 0);
                setAutoSpeed(false);
            }

            //   if (snmpCheckBox.isSelected())
            //   {
            //       mySNMP = new SNMPClient();
            //       showStatus("Checking your SNMP server...", true, true); status = mySNMP.getStat(mySNMP.CPUIDLEOID);
            //       if (status[0].equals("1")) { showStatus("Is your SNMP server running?", true, true); System.exit(1);}
            //
            //       // Setup the infrequent SystemStats Timer
            //       updateSystemStatsTimer.cancel(); updateSystemStatsTimer.purge();
            //            showStatus("updateSystemStatsTimer Canceled!", true, true); /* true = logToApplic, true = logToFile */
            //       updateSystemStatsTimer = new Timer(); updateSystemStatsTimer.scheduleAtFixedRate(new UpdateSystemStatsTimer(this), (long)(0), (updateSystemStatsTimerFastInterval));
            //            showStatus("updateSystemStatsTimer Scheduled immediate at " + Math.round(updateSystemStatsTimerFastInterval / 1000) + " Sec Interval", true, true); /* true = logToApplic, true = logToFile */
            //   }

            //   captionTable.setValueAt(onSymbol                    + " ON", 0, 0);
            //   captionTable.setValueAt("IDL/REG", 0, 1);
            //   captionTable.setValueAt(connectingSymbol            + " CON", 0, 2);
            //   captionTable.setValueAt(callingSymbol               + " CLL", 0, 3);
            //   captionTable.setValueAt(ringingSymbol               + " RNG", 0, 4);
            //   captionTable.setValueAt(acceptingSymbol             + " ACC", 0, 5);
            //   captionTable.setValueAt(talkingSymbol               + " TLK" , 0, 6);
            //   captionTable.setValueAt(localcancelSymbol           + " CAN", 0, 7);
            //   captionTable.setValueAt(localbusySymbol             + " BSY", 0, 8);
            //   captionTable.setValueAt(localbyeSymbol              + " " + remotebyeSymbol  + " BYE", 0, 9);

            captionTable.setValueAt("ON", 0, 0);
            captionTable.setValueAt("IDL/REG", 0, 1);
            captionTable.setValueAt("CON", 0, 2);
            captionTable.setValueAt("TRY", 0, 3);
            captionTable.setValueAt("CLL", 0, 4);
            captionTable.setValueAt("RNG", 0, 5);
            captionTable.setValueAt("ACC", 0, 6);
            captionTable.setValueAt("TLK", 0, 7);
            captionTable.setValueAt("CAN", 0, 8);
            captionTable.setValueAt("BSY", 0, 9);
            captionTable.setValueAt("BYE", 0, 10);

            // Set the CallRatio Pie Chart
            callRatioChartData = new DefaultPieDataset(); // callRatioChartData.setValue("Slack", 0); callRatioChartData.setValue("Busy", 0); callRatioChartData.setValue("Success", 0);
            callRatioChart = ChartFactory.createPieChart("Waiting for Campaign...", callRatioChartData, true,
                    true, false); // legend? // tooltips? // URLs?
            chartPanel = new ChartPanel(callRatioChart);

            org.jdesktop.layout.GroupLayout graphInnerPanelLayout = new org.jdesktop.layout.GroupLayout(
                    graphInnerPanel);
            graphInnerPanel.setLayout(graphInnerPanelLayout);
            graphInnerPanelLayout.setHorizontalGroup(
                    graphInnerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
                            chartPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 706, Short.MAX_VALUE));
            graphInnerPanelLayout.setVerticalGroup(
                    graphInnerPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
                            chartPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE));
            chartPanel.setFont(new java.awt.Font("STHeiti", 0, 10)); // NOI18N
            graphInnerPanel.setVisible(false);
            chartPanel.setVisible(false);
            chartPanel.setDoubleBuffered(true);

            // Set the PerformanceMeter Dial
            performanceMeter = new PerformanceMeter("Performance", vmUsageDecelerationThreashold,
                    (Vergunning.CALLSPERHOUR_ENTERPRISE / 100));
            performanceChartPanel = new ChartPanel(performanceMeter.chart1);

            org.jdesktop.layout.GroupLayout graphInnerPanelLayout2 = new org.jdesktop.layout.GroupLayout(
                    performanceMeterPanel);
            performanceMeterPanel.setLayout(graphInnerPanelLayout2);
            graphInnerPanelLayout2.setHorizontalGroup(
                    graphInnerPanelLayout2.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
                            performanceChartPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
                            performanceDialSize, Short.MAX_VALUE));
            graphInnerPanelLayout2.setVerticalGroup(
                    graphInnerPanelLayout2.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
                            performanceChartPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
                            performanceDialSize, Short.MAX_VALUE));
            performanceChartPanel.setFont(new java.awt.Font("STHeiti", 0, 10)); // NOI18N
            performanceMeterPanel.setVisible(true);
            performanceChartPanel.setVisible(true);
            performanceMeter.setCallPerHourNeedle(0);

            destination = new Destination();
            //                destinationElement = new Destination();
            campaignStat = new CampaignStat();
            lastStallerCampaignStat = new CampaignStat();
            lastTimeDashboardCampaignStat = new CampaignStat();

            // Last but not least, loading the Database Client
            try {
                dbClient = new JavaDBClient(eCallCenterReference, DATABASE);
            } catch (SQLException ex) {
            } catch (ClassNotFoundException ex) {
            } catch (InstantiationException ex) {
            } catch (IllegalAccessException ex) {
            } catch (NoSuchMethodException ex) {
            } catch (InvocationTargetException ex) {
            } catch (Exception ex) {
            }

            // Check for Open Campaigns
            String[] openCampaigns = dbClient.getOpenCampaigns();
            if ((openCampaigns != null) && (openCampaigns.length > 0)) {
                campaignComboBox.setModel(new javax.swing.DefaultComboBoxModel(openCampaigns));
                campaignComboBox.setEnabled(true);
            } else {
                campaignComboBox.setEnabled(false);
                runCampaignToggleButton.setEnabled(false);
                stopCampaignButton.setEnabled(false);
            }

            callCenterIsNetManaged = false;

            vergunningStartCalendar = Calendar.getInstance();
            vergunningEndCalendar = Calendar.getInstance();
            vergunningStartCalendar.set(Calendar.HOUR_OF_DAY, (int) 0);
            vergunningStartCalendar.set(Calendar.MINUTE, (int) 0);
            vergunningStartCalendar.set(Calendar.SECOND, (int) 0);

            vergunning = new Vergunning();
            executeVergunning();
            if (!vergunning.isValid()) {
                vergunningCodeField.setText("");
            } else {
                performanceMeter.setCallPerHourScale(0, (vergunning.getCallsPerHour() / 100),
                        (vergunning.getCallsPerHour() / 1000));
            }

            timeTool = new TimeTool();
            defaultConstructorIsReady = true;
        }
    });
    defaultConstructorThread.setName("defaultConstructorThread");
    defaultConstructorThread.setDaemon(runThreadsAsDaemons);
    defaultConstructorThread.setPriority(5);
    defaultConstructorThread.start();
}

From source file:org.apache.solr.cloud.Overseer.java

public synchronized void start(String id) {
    this.id = id;
    closed = false;//ww w . j ava 2  s  . c o  m
    doClose();
    stats = new Stats();
    log.info("Overseer (id=" + id + ") starting");
    createOverseerNode(reader.getZkClient());
    //launch cluster state updater thread
    ThreadGroup tg = new ThreadGroup("Overseer state updater.");
    updaterThread = new OverseerThread(tg, new ClusterStateUpdater(reader, id, stats),
            "OverseerStateUpdate-" + id);
    updaterThread.setDaemon(true);

    ThreadGroup ccTg = new ThreadGroup("Overseer collection creation process.");

    OverseerNodePrioritizer overseerPrioritizer = new OverseerNodePrioritizer(reader, adminPath,
            shardHandler.getShardHandlerFactory());
    overseerCollectionConfigSetProcessor = new OverseerCollectionConfigSetProcessor(reader, id, shardHandler,
            adminPath, stats, Overseer.this, overseerPrioritizer);
    ccThread = new OverseerThread(ccTg, overseerCollectionConfigSetProcessor,
            "OverseerCollectionConfigSetProcessor-" + id);
    ccThread.setDaemon(true);

    ThreadGroup ohcfTg = new ThreadGroup("Overseer Hdfs SolrCore Failover Thread.");

    OverseerAutoReplicaFailoverThread autoReplicaFailoverThread = new OverseerAutoReplicaFailoverThread(config,
            reader, updateShardHandler);
    arfoThread = new OverseerThread(ohcfTg, autoReplicaFailoverThread, "OverseerHdfsCoreFailoverThread-" + id);
    arfoThread.setDaemon(true);

    updaterThread.start();
    ccThread.start();
    arfoThread.start();
}

From source file:com.zoffcc.applications.zanavi.Navit.java

/** Called when the activity is first created. */
// ----------- remove later -------------
// ----------- remove later -------------
@SuppressLint("NewApi")
// ----------- remove later -------------
// ----------- remove later -------------
@TargetApi(Build.VERSION_CODES.FROYO)/*from  ww w .  j  a  v  a  2 s .  c  om*/
@Override
public void onCreate(Bundle savedInstanceState) {
    // if (Navit.METHOD_DEBUG) Navit.my_func_name(0);

    // ------- only after API level 9 -------
    // ------- only after API level 9 -------
    //      try
    //      {
    //         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDeath().penaltyLog().build());
    //         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    //
    //         StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
    //         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old).permitDiskWrites().build());
    //         old = StrictMode.getThreadPolicy();
    //         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old).permitDiskReads().build());
    //
    //      }
    //      catch (NoClassDefFoundError e)
    //      {
    //      }
    // ------- only after API level 9 -------
    // ------- only after API level 9 -------

    // Log.e("Navit", "OnCreate");

    //      if (checkPlayServices())
    //      {
    //      }

    ZANaviMainApplication.restore_error_msg(this.getApplicationContext());

    // app_status_lastalive = PreferenceManager.getDefaultSharedPreferences(this).getLong(PREF_KEY_LASTALIVE, -1L);
    app_status_string = PreferenceManager.getDefaultSharedPreferences(this).getString(PREF_KEY_CRASH, "down");

    if (FDBL) {
        p.PREF_enable_debug_crashdetect = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("enable_debug_crashdetect", true);
    } else {
        p.PREF_enable_debug_crashdetect = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("enable_debug_crashdetect", PLAYSTORE_VERSION_CRASHDETECT);
    }

    System.out.println("app_status_string get:[onCreate]" + app_status_string);
    System.out.println("app_status_string=" + app_status_string);
    // System.out.println("app_status_string:app_status_lastalive=" + app_status_lastalive);

    if (app_status_string.compareToIgnoreCase("down") != 0) {
        if (Navit.CI_ALLOWCRASHREPORTS) {
            intro_flag_crash = true;
            System.out.println("app_status_string:1:" + "intro_flag_crash=" + intro_flag_crash);
        } else {
            intro_flag_crash = false;
        }
    } else {
        intro_flag_crash = false;
    }

    //      if (System.currentTimeMillis() > app_status_lastalive + allowed_seconds_alive_for_crash)
    //      {
    //         // reset crash flag after X seconds
    //         intro_flag_crash = false;
    //      }

    if (checkForUpdate()) {
        // reset crash flag if we just updated
        intro_flag_crash = false;
    }

    if (!p.PREF_enable_debug_crashdetect) {
        // reset crash flag if we preference set to "false"
        intro_flag_crash = false;
    }

    // --- if we have no stacktrace -> don't show crash screen ----------
    if (intro_flag_crash) {
        try {
            if (ZANaviMainApplication.last_stack_trace_as_string == null) {
                intro_flag_crash = false;
            } else if (ZANaviMainApplication.last_stack_trace_as_string.length() < 2) {
                intro_flag_crash = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // --- if we have no stacktrace -> don't show crash screen ----------

    System.out.println("app_status_string:2:" + "intro_flag_crash=" + intro_flag_crash);

    try {
        app_status_string = "running";
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString(PREF_KEY_CRASH, "running")
                .commit();
        System.out.println("app_status_string set:[onCreate]" + app_status_string);
    } catch (Exception e) {
        e.printStackTrace();
    }

    api_version_int = Integer.valueOf(android.os.Build.VERSION.SDK);
    System.out.println("XXX:API=" + api_version_int);
    if (api_version_int > 10) {
        Navit.PAINT_OLD_API = false;
    } else {
        Navit.PAINT_OLD_API = true;
    }

    getPrefs_theme();
    getPrefs_theme_main();
    Navit.applySharedTheme(this, p.PREF_current_theme_M);

    super.onCreate(savedInstanceState);

    Global_Navit_Object = this;
    asset_mgr = getAssets();

    PackageInfo pInfo;
    try {
        pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        ZANAVI_VERSION = pInfo.versionName;
    } catch (NameNotFoundException e4) {
    }

    // Intent intent = new Intent(this, ZANaviAboutPage.class);
    // startActivity(intent);

    // --------- check permissions -----------
    // --------- check permissions -----------
    // --------- check permissions -----------

    /*
     * 
     * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     * <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
     * <uses-permission android:name="android.permission.WAKE_LOCK" />
     * <uses-permission android:name="android.permission.INTERNET" />
     * <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     */

    //if (EasyPermissions.hasPermissions(this, perms))
    //{
    //   // have permissions!
    //}
    //else
    //{
    //   // ask for permissions
    //   EasyPermissions.requestPermissions(this, Navit.get_text("ZANavi needs some permissions..."), RC_PERM_001, perms);
    //}
    // --------- check permissions -----------
    // --------- check permissions -----------
    // --------- check permissions -----------

    OSD_blueish_bg_color = getResources().getColor(R.color.blueish_bg_color);

    // getBaseContext_ = getBaseContext().getApplicationContext();
    getBaseContext_ = getBaseContext();

    last_orientation = getResources().getConfiguration().orientation;

    content_resolver = getContentResolver();
    // get_reglevel();

    Display display_ = getWindowManager().getDefaultDisplay();
    metrics = new DisplayMetrics();
    display_.getMetrics(Navit.metrics);

    road_book_items = new ArrayList<ListViewItem>();
    fragmentManager = getSupportFragmentManager();

    setContentView(R.layout.main_layout);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        try {
            setSupportActionBar(toolbar);
            // System.out.println("TTT01:" + toolbar);
        } catch (NoClassDefFoundError e) {
        }
    }

    try {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setIcon(R.drawable.icon);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    } catch (NoClassDefFoundError e) {
    } catch (Exception e) {
        e.printStackTrace();
    }

    progressbar_main_activity = (ProgressBar) findViewById(R.id.progressbar_main_activity);
    progressbar_main_activity.setVisibility(View.GONE);
    progressbar_main_activity.setProgress(0);

    // ------------ bottom bar slider ----------------
    // ------------ bottom bar slider ----------------
    // ------------ bottom bar slider ----------------

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        smaller_top_bar(true);
    } else {
        smaller_top_bar(false);
    }

    bottom_bar_px = (int) getResources().getDimension(R.dimen.gui_top_container_height);
    // System.out.println("VVV:bottom_bar_height:" + bottom_bar_px);
    bottom_bar_slider_shadow_px = (int) getResources()
            .getDimension(R.dimen.bottom_slide_view_shadow_compat_height);
    // System.out.println("VVV:bottom_bar_slider_shadow_px:" + bottom_bar_slider_shadow_px);

    // final RelativeLayout a = (RelativeLayout) findViewById(R.id.bottom_bar_container);
    final FrameLayout a = (FrameLayout) findViewById(R.id.bottom_bar_slide);
    final RelativeLayout.LayoutParams pp22 = (RelativeLayout.LayoutParams) a.getLayoutParams();

    // Calculate ToolBar height
    try {
        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
                    getResources().getDisplayMetrics());
            System.out.println("VVV:abh:" + actionBarHeight);
        } else {
            actionBarHeight = NavitGraphics.dp_to_px(144);
        }
    } catch (Exception e) {
        actionBarHeight = NavitGraphics.dp_to_px(144);
    }

    final android.support.v7.widget.Toolbar view_toolbar_top = (android.support.v7.widget.Toolbar) findViewById(
            R.id.toolbar);
    ViewTreeObserver vto = view_toolbar_top.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            view_toolbar_top.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            // int width = view_toolbar_top.getMeasuredWidth();
            int height = view_toolbar_top.getMeasuredHeight();
            Navit.actionBarHeight = height;
            // System.out.println("hhh:88=" + Navit.actionBarHeight);
            Navit.cur_y_margin_bottom_bar_touch = Navit.map_view_height + Navit.actionBarHeight + bottom_bar_px
                    - Navit.bottom_bar_slider_shadow_px; // try to put view at bottom

            pp22.setMargins(0, (int) Navit.cur_y_margin_bottom_bar_touch, 0, 0); // left, top, right, bottom
            a.setLayoutParams(pp22);
            a.requestLayout();
        }
    });

    // actionBarHeight = 168;

    //      final int SWIPE_MIN_DISTANCE = NavitGraphics.dp_to_px(25);
    //      final float SWIPE_THRESHOLD_VELOCITY = 5.5f;
    //      final float FLING_PIXELS_PER_SECOND = 100;
    //      final float maxFlingVelocity = ViewConfiguration.get(this).getScaledMaximumFlingVelocity();
    final ViewConfiguration vc = ViewConfiguration.get(this);
    final int swipeMinDistance = vc.getScaledPagingTouchSlop();
    final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity();
    swipeMaxOffPath = vc.getScaledTouchSlop();
    // (there is also vc.getScaledMaximumFlingVelocity() one could check against)

    // setup some values --------
    NavitGraphics.long_press_on_screen_max_distance = swipeMaxOffPath;
    // setup some values --------

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                //               float velocityPercentY = velocityY / maxFlingVelocity; // the percent is a value in the range of (0, 1]
                //               float normalizedVelocityY = velocityPercentY * FLING_PIXELS_PER_SECOND; // where PIXELS_PER_SECOND is a device-independent measurement

                //               System.out.println("VVV:" + (e1.getY() - e2.getY()) + " " + NavitGraphics.dp_to_px((int) (e1.getY() - e2.getY())) + " " + maxFlingVelocity + " " + velocityY + " " + velocityPercentY + " " + normalizedVelocityY + " " + SWIPE_THRESHOLD_VELOCITY);

                // System.out.println("VVV:2:" + swipeMinDistance + " " + swipeThresholdVelocity + " " + swipeMaxOffPath);

                // bottom to top
                if (e1.getY() - e2.getY() > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) {
                    //int featureWidth = getMeasuredWidth();
                    //mActiveFeature = (mActiveFeature < (mItems.size() - 1)) ? mActiveFeature + 1 : mItems.size() - 1;
                    //smoothScrollTo(mActiveFeature * featureWidth, 0);
                    //System.out.println("GS:002:up:" + velocityY + " " + e2.getY() + " " + e1.getY());

                    animate_bottom_bar_up();

                    return true;
                }
                // top to bottom
                else if (e2.getY() - e1.getY() > swipeMinDistance
                        && Math.abs(velocityY) > swipeThresholdVelocity) {
                    //int featureWidth = getMeasuredWidth();
                    //mActiveFeature = (mActiveFeature > 0) ? mActiveFeature - 1 : 0;
                    //smoothScrollTo(mActiveFeature * featureWidth, 0);
                    //System.out.println("GS:003:down:" + velocityY + " " + e1.getY() + " " + e2.getY());

                    animate_bottom_bar_down();

                    return true;
                }
            } catch (Exception e) {
                //System.out.println("GS:009:EE:" + e.getMessage());
            }
            return false;
        }
    }
    mGestureDetector = new GestureDetector(new MyGestureDetector());

    push_pin_view = (ImageView) findViewById(R.id.bottom_slide_left_side);
    push_pin_view.setOnClickListener(new ImageView.OnClickListener() {
        public void onClick(View v) {
            try {
                toggle_follow_button();
            } catch (Exception e) {
            }
        }
    });

    cur_y_margin_bottom_bar_touch = 0; // try to put view at bottom

    a.setOnTouchListener(new View.OnTouchListener() {
        @Override
        synchronized public boolean onTouch(View v, MotionEvent m) {

            int action = m.getAction();

            if (mGestureDetector.onTouchEvent(m)) {
                //System.out.println("GS:001:fling!!");
                // System.out.println("FRAG:fling:011");
                return true;
            } else if (action == MotionEvent.ACTION_DOWN) {
                last_y_bottom_bar_touch = m.getY();

                // put roadbook into layout -----------
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                try {
                    if (road_book == null) {
                        road_book = new ZANaviRoadbookFragment();
                        // System.out.println("FRAG:attach:001");
                        fragmentTransaction.replace(R.id.roadbook_fragment_container, road_book, "");
                        fragmentTransaction.commitAllowingStateLoss();
                        // fragmentTransaction.show(road_book);
                    } else {
                        // System.out.println("FRAG:attached:003");
                    }
                } catch (Exception ef) {
                }
                // put roadbook into layout -----------

                return true;
            } else if ((action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_CANCEL)) {
                // System.out.println("FRAG:up/cancel:012");

                // release
                if (cur_y_margin_bottom_bar_touch > (bottom_y_margin_bottom_bar_touch / 2)) {
                    // snap back to bottom
                    animate_bottom_bar_down();
                } else {
                    // snap top top
                    animate_bottom_bar_up();
                }
            } else
            // if (action == MotionEvent.ACTION_MOVE)
            {
                // System.out.println("FRAG:*else*:012");

                if (Math.abs(last_y_bottom_bar_touch - m.getY()) > 2) {
                    float last_margin = cur_y_margin_bottom_bar_touch;
                    cur_y_margin_bottom_bar_touch = cur_y_margin_bottom_bar_touch
                            - (last_y_bottom_bar_touch - m.getY());

                    if ((cur_y_margin_bottom_bar_touch >= 0)
                            && (cur_y_margin_bottom_bar_touch <= bottom_y_margin_bottom_bar_touch)) {
                        // System.out.println("VVV:move:" + cur_y_margin_bottom_bar_touch + " " + bottom_y_margin_bottom_bar_touch);

                        last_y_bottom_bar_touch = m.getY() + (last_y_bottom_bar_touch - m.getY());
                        RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) a
                                .getLayoutParams();
                        relativeParams.setMargins(0, (int) cur_y_margin_bottom_bar_touch, 0, 0); // left, top, right, bottom
                        a.setLayoutParams(relativeParams);
                        a.requestLayout();
                    } else {
                        // System.out.println("VVV:revert");

                        // revert position
                        cur_y_margin_bottom_bar_touch = last_margin;
                    }
                }

            }
            return true;
        }
    });
    // ------------ bottom bar slider ----------------
    // ------------ bottom bar slider ----------------
    // ------------ bottom bar slider ----------------

    // init cancel dialog!! ----------
    // init cancel dialog!! ----------
    Message msg2 = new Message();
    Bundle b2 = new Bundle();
    b2.putString("text", "");
    msg2.what = 0;
    msg2.setData(b2);
    ZANaviDownloadMapCancelActivity.canceldialog_handler.sendMessage(msg2);
    // init cancel dialog!! ----------
    // init cancel dialog!! ----------

    app_window = getWindow();

    // ---------------- set some directories -----------------
    // ---------------- set some directories -----------------
    NAVIT_DATA_DIR = this.getFilesDir().getPath();
    this.getFilesDir().mkdirs();
    // ---
    // System.out.println("data dir=" + NAVIT_DATA_DIR);
    NAVIT_DATA_SHARE_DIR = NAVIT_DATA_DIR + "/share/";
    File tmp3 = new File(NAVIT_DATA_SHARE_DIR);
    tmp3.mkdirs();
    // ---
    FIRST_STARTUP_FILE = NAVIT_DATA_SHARE_DIR + "/has_run_once.txt";
    VERSION_FILE = NAVIT_DATA_SHARE_DIR + "/version.txt";
    // ---------------- set some directories -----------------
    // ---------------- set some directories -----------------

    try {
        toneG = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
    } catch (Exception e) {
    }

    try {
        Class.forName("android.app.backup.BackupManager");
        backupManager = new BackupManager(this);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    int width_ = display_.getWidth();
    int height_ = display_.getHeight();
    Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
    Log.e("Navit", "Navit -> dpi=" + Navit.metrics.densityDpi);
    Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
    Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);

    try {
        // send overspill factor to C-code
        Message msg33 = new Message();
        Bundle b33 = new Bundle();
        b33.putInt("Callback", 104);
        msg33.setData(b33);
        NavitGraphics.callback_handler.sendMessage(msg33);
    } catch (Exception eee) {
    }

    // ----- service -----
    // ----- service -----
    ZANaviMapDownloaderServiceIntent = new Intent(Navit.getBaseContext_, ZANaviMapDownloaderService.class);
    // ----- service -----
    // ----- service -----

    System.out.println("Navit:onCreate:JTHREAD ID=" + Thread.currentThread().getId());
    System.out.println("Navit:onCreate:THREAD ID=" + NavitGraphics.GetThreadId());

    // bitmaps for lanes
    lane_left = BitmapFactory.decodeResource(getResources(), R.drawable.lane_left);
    lane_right = BitmapFactory.decodeResource(getResources(), R.drawable.lane_right);
    lane_merge_to_left = BitmapFactory.decodeResource(getResources(), R.drawable.lane_merge_to_left);
    lane_merge_to_right = BitmapFactory.decodeResource(getResources(), R.drawable.lane_merge_to_right);
    lane_none = BitmapFactory.decodeResource(getResources(), R.drawable.lane_none);
    // bitmaps for lanes

    // paint for bitmapdrawing on map
    NavitGraphics.paint_for_map_display.setAntiAlias(true);
    NavitGraphics.paint_for_map_display.setFilterBitmap(true);

    // sky
    NavitGraphics.paint_sky_day.setAntiAlias(true);
    NavitGraphics.paint_sky_day.setColor(Color.parseColor("#79BAEC"));
    NavitGraphics.paint_sky_night.setAntiAlias(true);
    NavitGraphics.paint_sky_night.setColor(Color.parseColor("#090909"));
    // stars
    NavitGraphics.paint_sky_night_stars.setColor(Color.parseColor("#DEDDEF"));
    // twilight
    NavitGraphics.paint_sky_twilight1.setColor(Color.parseColor("#090909"));
    NavitGraphics.paint_sky_twilight2.setColor(Color.parseColor("#113268"));
    NavitGraphics.paint_sky_twilight3.setColor(Color.parseColor("#79BAEC"));

    Random m = new Random();
    int i6 = 0;
    for (i6 = 0; i6 < (NavitGraphics.max_stars + 1); i6++) {
        NavitGraphics.stars_x[i6] = m.nextFloat();
        NavitGraphics.stars_y[i6] = m.nextFloat();
        NavitGraphics.stars_size[i6] = m.nextInt(3) + 1;
    }

    res_ = getResources();
    int ii = 0;
    NavitGraphics.dl_thread_cur = 0;
    for (ii = 0; ii < NavitGraphics.dl_thread_max; ii++) {
        NavitGraphics.dl_thread[ii] = null;
    }

    String font_file_name = "Roboto-Regular.ttf"; // "LiberationSans-Regular.ttf";
    NavitStreetnameFont = Typeface.createFromAsset(getBaseContext().getAssets(), font_file_name);
    // System.out.println("NavitStreetnameFont" + NavitStreetnameFont);

    Navit_maps_loaded = false;

    // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
    Navit.startup_intent = this.getIntent();
    // hack! remeber timstamp, and only allow 4 secs. later in onResume to set target!
    Navit.startup_intent_timestamp = System.currentTimeMillis();
    Log.e("Navit", "**1**A " + startup_intent.getAction());
    Log.e("Navit", "**1**D " + startup_intent.getDataString());
    Log.e("Navit", "**1**I " + startup_intent.toString());
    try {
        Log.e("Navit", "**1**DH E " + startup_intent.getExtras().describeContents());
    } catch (Exception ee) {
    }

    startup_status = Navit_Status_NORMAL_STARTUP;

    //      glSurfaceView = (GLSurfaceView) findViewById(R.id.glSurfaceView_001);
    //      glSurfaceView.setEGLContextClientVersion(2); // enable OpenGL 2.0
    //      glSurfaceView.setRenderer(new GlRenderer());
    //      glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // only render on demand
    //
    //      // draw some sample lines ----
    //      // draw some sample lines ----
    //      // draw some sample lines ----
    //      ZANaviGlLine vertLine = new ZANaviGlLine();
    //      vertLine.SetVerts(1000f, 1000f, 0f, -1000f, -1000f, 0f);
    //      vertLine.SetColor(.8f, .8f, 0f, 1.0f);
    //
    //      float[] mMVPMatrix = new float[16];
    //
    //      // Position the eye behind the origin.
    //      final float eyeX = 0.0f;
    //      final float eyeY = 0.0f;
    //      final float eyeZ = 1.5f;
    //
    //      // We are looking toward the distance
    //      final float lookX = 0.0f;
    //      final float lookY = 0.0f;
    //      final float lookZ = -5.0f;
    //
    //      // Set our up vector. This is where our head would be pointing were we holding the camera.
    //      final float upX = 0.0f;
    //      final float upY = 1.0f;
    //      final float upZ = 0.0f;
    //
    //      // Set the view matrix. This matrix can be said to represent the camera position.
    //      // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and
    //      // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.
    //      Matrix.setLookAtM(mMVPMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);
    //
    //      vertLine.draw(mMVPMatrix);
    //
    //      glSurfaceView.postInvalidate();
    //      glSurfaceView.requestRender();
    //      glSurfaceView.postInvalidate();
    //      // draw some sample lines ----
    //      // draw some sample lines ----
    //      // draw some sample lines ----

    // setup graphics objects
    // setup graphics objects
    // setup graphics objects
    NG__vehicle = new NavitGraphics(this, 1, 0, 0, 50, 50, 65535, 0, 0);
    NG__map_main = new NavitGraphics(this, 0, 0, 0, 100, 100, 0, 0, 0);
    Navit.N_NavitGraphics = NG__map_main;
    // setup graphics objects
    // setup graphics objects
    // setup graphics objects

    NV = new NavitVehicle(this);
    NSp = new NavitSpeech2(this);

    // init translated text ------------------------------------
    // NavitTextTranslations.init();
    final Runnable r = new Runnable() {
        public void run() {
            NavitTextTranslations.init();
        }
    };
    ThreadGroup group = new ThreadGroup("Group1");
    new Thread(group, r, "ZTransInit1", 100000).start(); // use 0.1MByte stack
    // init translated text ------------------------------------

    // set the new locale here -----------------------------------
    getPrefs_loc();
    activatePrefs_loc();
    // set the new locale here -----------------------------------

    // get the local language -------------
    Locale locale = java.util.Locale.getDefault();
    String lang = locale.getLanguage();
    String langu = lang;
    String langc = lang;
    Log.e("Navit", "lang=" + lang);
    int pos = langu.indexOf('_');
    if (pos != -1) {
        langc = langu.substring(0, pos);
        langu = langc + langu.substring(pos).toUpperCase(locale);
        Log.e("Navit", "substring lang " + langu.substring(pos).toUpperCase(locale));
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = langu.substring(pos).toUpperCase(locale);
    } else {
        String country = locale.getCountry();
        Log.e("Navit", "Country1 " + country);
        Log.e("Navit", "Country2 " + country.toUpperCase(locale));
        langu = langc + "_" + country.toUpperCase(locale);
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = country.toUpperCase(locale);
    }
    Log.e("Navit", "Language " + lang);
    // get the local language -------------

    TextView no_maps_text = (TextView) this.findViewById(R.id.no_maps_text);
    no_maps_text.setText("\n\n\n" + Navit.get_text("No Maps installed") + "\n"
            + Navit.get_text("Please download a map") + "\n\n");

    //      if (api_version_int < 11)
    //      {
    try {
        try {
            no_maps_text.setVisibility(View.INVISIBLE);
        } catch (NoSuchMethodError e) {
        }

        try {
            no_maps_text.setActivated(false);
        } catch (NoSuchMethodError e) {
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //      }

    // no_maps_text.postInvalidate();

    // set map cache size here -----------------------------------
    getPrefs_mapcache();
    activatePrefs_mapcache();
    // set map cache size here -----------------------------------

    // get map data dir and set it -----------------------------
    getPrefs_mapdir();
    activatePrefs_mapdir(true);
    // get map data dir and set it -----------------------------

    // get special prefs here ------------------------------------
    get_prefs_highdpi();
    // get special prefs here ------------------------------------

    // make sure the new path for the navitmap.bin file(s) exist!!
    File navit_maps_dir = new File(MAP_FILENAME_PATH);
    navit_maps_dir.mkdirs();
    // create nomedia files
    File nomedia_file = new File(MAP_FILENAME_PATH + ".nomedia");
    try {
        nomedia_file.createNewFile();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    // create nomedia files

    // check if we already have a borders.bin file (if not, then extract the included simplified one)
    File b_ = new File(MAP_FILENAME_PATH + "/borders.bin");
    try {
        if (!b_.exists()) {
            try {
                File c_ = new File(MAPMD5_FILENAME_PATH + "/borders.bin.md5");
                c_.delete();
            } catch (Exception e2) {

            }
            Log.e("Navit",
                    "trying to extract borders simple resource to:" + MAP_FILENAME_PATH + "/borders.bin");
            if (!extractRes("borders_simple", MAP_FILENAME_PATH + "/borders.bin")) {
                Log.e("Navit",
                        "Failed to extract borders simple resource to:" + MAP_FILENAME_PATH + "/borders.bin");
            }
        }
    } catch (Exception e) {

    }
    // check if we already have a borders.bin file

    // make sure the new path for config files exist
    File navit_cfg_dir = new File(CFG_FILENAME_PATH);
    navit_cfg_dir.mkdirs();

    // make sure the new path for the navitmap.bin file(s) exist!!
    File navit_mapsmd5_dir = new File(MAPMD5_FILENAME_PATH);
    navit_mapsmd5_dir.mkdirs();

    // make sure the share dir exists, otherwise the infobox will not show
    File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
    navit_data_share_dir.mkdirs();

    File dd = new File(NAVIT_DATA_DEBUG_DIR);
    dd.mkdirs();

    // try to create cat. file if it does not exist
    File navit_maps_catalogue = new File(CFG_FILENAME_PATH + NavitMapDownloader.CAT_FILE);
    if (!navit_maps_catalogue.exists()) {
        FileOutputStream fos_temp;
        try {
            fos_temp = new FileOutputStream(navit_maps_catalogue);
            fos_temp.write((NavitMapDownloader.MAP_CAT_HEADER + "\n").getBytes()); // just write header to the file
            fos_temp.flush();
            fos_temp.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // ---------- downloader threads ----------------
    PackageInfo pkgInfo;
    Navit_DonateVersion_Installed = false;
    try {
        // is the donate version installed?
        pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_donate", 0);
        String sharedUserId = pkgInfo.sharedUserId;
        System.out.println("str nd=" + sharedUserId);
        if (sharedUserId.equals("com.zoffcc.applications.zanavi")) {
            System.out.println("##bonus 001##");
            Navit_DonateVersion_Installed = true;
            NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (get_reglevel() == 1) {
            System.out.println("##U:bonus 001##");
            Navit_DonateVersion_Installed = true;
            NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        // is the "large map" donate version installed?
        pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_largemap_donate", 0);
        String sharedUserId = pkgInfo.sharedUserId;
        System.out.println("str lm=" + sharedUserId);

        if (sharedUserId.equals("com.zoffcc.applications.zanavi")) {
            System.out.println("##bonus 002##");
            Navit_DonateVersion_Installed = true;
            Navit_Largemap_DonateVersion_Installed = true;
            NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (get_reglevel() == 1) {
            System.out.println("##U:bonus 002##");
            Navit_DonateVersion_Installed = true;
            Navit_Largemap_DonateVersion_Installed = true;
            NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // update map list
    NavitMapDownloader.init_maps_without_donate_largemaps();
    // ---------- downloader threads ----------------

    // ---- detect menu button ----
    detect_menu_button();

    if (Navit.metrics.densityDpi >= 320) //&& (PREF_shrink_on_high_dpi))
    {
        Navit.menu_button = BitmapFactory.decodeResource(getResources(), R.drawable.menu_001);
    } else {
        Navit.menu_button = BitmapFactory.decodeResource(getResources(), R.drawable.menu_001_small);
    }

    Navit.long_green_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.long_green_arrow);

    Navit.follow_on = BitmapFactory.decodeResource(getResources(), R.drawable.follow);
    Navit.follow_off = BitmapFactory.decodeResource(getResources(), R.drawable.follow_off);
    Navit.follow_current = Navit.follow_on;

    if ((Navit.metrics.densityDpi >= 320) && (p.PREF_shrink_on_high_dpi)) {
        float factor;
        factor = (float) NavitGraphics.Global_Scaled_DPI_normal / (float) Navit.metrics.densityDpi;
        factor = factor * 1.7f;
        //
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inDither = true;
        //o.inScaled = true;
        //o.inTargetDensity = NavitGraphics.Global_Scaled_DPI_normal;
        Navit.nav_arrow_stopped = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_stopped, o);
        Navit.nav_arrow_moving = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_moving, o);
        Navit.nav_arrow_moving_grey = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_moving_grey, o);
        Navit.nav_arrow_moving_shadow = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_moving_shadow, o);

        Navit.nav_arrow_stopped_small = Bitmap.createScaledBitmap(Navit.nav_arrow_stopped,
                (int) (Navit.nav_arrow_stopped.getWidth() / NavitGraphics.strech_factor_3d_map * factor),
                (int) (Navit.nav_arrow_stopped.getHeight() / NavitGraphics.strech_factor_3d_map * factor),
                true);
        Navit.nav_arrow_moving_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving,
                (int) (Navit.nav_arrow_moving.getWidth() / NavitGraphics.strech_factor_3d_map * factor),
                (int) (Navit.nav_arrow_moving.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true);
        Navit.nav_arrow_moving_shadow_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving_shadow,
                (int) (Navit.nav_arrow_moving_shadow.getWidth() / NavitGraphics.strech_factor_3d_map * factor),
                (int) (Navit.nav_arrow_moving_shadow.getHeight() / NavitGraphics.strech_factor_3d_map * factor),
                true);
    } else {
        Navit.nav_arrow_stopped = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_stopped);
        Navit.nav_arrow_moving = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_moving);
        Navit.nav_arrow_moving_grey = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_moving_grey);
        Navit.nav_arrow_moving_shadow = BitmapFactory.decodeResource(getResources(),
                R.drawable.navigation_arrow_moving_shadow);

        Navit.nav_arrow_stopped_small = Bitmap.createScaledBitmap(Navit.nav_arrow_stopped,
                (int) (Navit.nav_arrow_stopped.getWidth() / NavitGraphics.strech_factor_3d_map),
                (int) (Navit.nav_arrow_stopped.getHeight() / NavitGraphics.strech_factor_3d_map), true);
        Navit.nav_arrow_moving_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving,
                (int) (Navit.nav_arrow_moving.getWidth() / NavitGraphics.strech_factor_3d_map),
                (int) (1.5 * Navit.nav_arrow_moving.getHeight() / NavitGraphics.strech_factor_3d_map), true);
        Navit.nav_arrow_moving_shadow_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving_shadow,
                (int) (Navit.nav_arrow_moving_shadow.getWidth() / NavitGraphics.strech_factor_3d_map),
                (int) (1.5 * Navit.nav_arrow_moving_shadow.getHeight() / NavitGraphics.strech_factor_3d_map),
                true);
    }

    Navit.zoomin = BitmapFactory.decodeResource(getResources(), R.drawable.zoom_in_32_32);
    Navit.zoomout = BitmapFactory.decodeResource(getResources(), R.drawable.zoom_out_32_32);

    //Navit.oneway_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway);
    Navit.oneway_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway_large);
    Navit.oneway_bicycle_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway_bicycle_large);

    // *******************
    // *******************
    // *******************
    // *******************
    // check/init the catalogue file for downloaded maps
    NavitMapDownloader.init_cat_file();
    // *******************
    // *******************
    // *******************
    // *******************

    xmlconfig_unpack_file = false;
    write_new_version_file = false;
    try {
        NavitAppVersion = "" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
        NavitAppVersion_string = ""
                + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        NavitAppVersion = "1";
        NavitAppVersion_string = "1";
    } catch (Exception e) {
        e.printStackTrace();
        NavitAppVersion = "2";
        NavitAppVersion_string = "2";
    }

    try {
        File navit_version = new File(VERSION_FILE);
        if (!navit_version.exists()) {
            System.out.println("version file does not exist");
            NavitAppVersion_prev = "-1";
            write_new_version_file = true;
        } else {
            // files exists, read in the prev. verison number
            System.out.println("version file is here");
            FileInputStream fos_temp;
            byte[] buffer = new byte[101];
            fos_temp = new FileInputStream(navit_version);
            int len = fos_temp.read(buffer, 0, 100);
            if (len != -1) {
                // use only len bytes to make the string (the rest is garbage!!)
                NavitAppVersion_prev = new String(buffer).substring(0, len);
            } else {
                NavitAppVersion_prev = "-1";
                write_new_version_file = true;
            }
            fos_temp.close();
        }

    } catch (Exception e) {
        NavitAppVersion_prev = "-1";
        write_new_version_file = true;
        e.printStackTrace();
    }

    System.out.println("vprev:" + NavitAppVersion_prev + " vcur:" + NavitAppVersion);

    intro_flag_update = false;
    if (NavitAppVersion_prev.compareTo(NavitAppVersion) != 0) {
        // different version
        System.out.println("different version!!");
        write_new_version_file = true;
        xmlconfig_unpack_file = true;

        //if ((NavitAppVersion_prev.compareTo("-1") != 0) && (NavitAppVersion.compareTo("-1") != 0))
        //{
        // user has upgraded to a new version of ZANavi
        startup_status = Navit_Status_UPGRADED_TO_NEW_VERSION;
        intro_flag_update = true;
        //}
    } else {
        // same version
        System.out.println("same version");
        xmlconfig_unpack_file = false;
    }

    // write new version file
    if (write_new_version_file) {
        try {
            System.out.println("write version file");
            FileOutputStream fos_temp;
            File navit_version = new File(VERSION_FILE);
            navit_version.delete();
            fos_temp = new FileOutputStream(navit_version);
            fos_temp.write(NavitAppVersion.getBytes());
            fos_temp.flush();
            fos_temp.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Sample useragent strings:
    //
    //      Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0a1) Gecko/20110616 Firefox/7.0a1 SeaMonkey/2.4a1
    //      Dalvik/1.4.0 (Linux; U; Android 2.3.3; GT-I9100 Build/GINGERBREAD)
    //      Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-S5830 Build/FROYO)
    //      Dalvik/1.4.0 (Linux; U; Android 2.3.3; HTC Desire S Build/GRI40)
    //      Dalvik/1.2.0 (Linux; U; Android 2.2.2; MB525 Build/3.4.2-179)
    //      Dalvik/1.4.0 (Linux; U; Android 2.3.3; HTC Wildfire S A510e Build/GRI40)
    //      Wget/1.10.2
    //      Dalvik/1.4.0 (Linux; U; Android 2.3.3; sdk Build/GRI34)
    //      Dalvik/1.2.0 (Linux; U; Android 2.2.2; MB525 Build/3.4.2-164)
    //      Dalvik/1.2.0 (Linux; U; Android 2.2; GT-I9000 Build/FROYO)
    //      Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-S5570L Build/FROYO)
    //      Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-I9000 Build/FROYO)
    //      Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1)
    String ANDROID = android.os.Build.VERSION.SDK; //The current development codename, or the string "REL" if this is a release build.
    //String BOARD = android.os.Build.BOARD; //The name of the underlying board, like "goldfish".    
    //String BOOTLOADER = android.os.Build.BOOTLOADER; //  The system bootloader version number.
    String BRAND = android.os.Build.BRAND; //The brand (e.g., carrier) the software is customized for, if any.
    //String CPU_ABI = android.os.Build.CPU_ABI; //The name of the instruction set (CPU type + ABI convention) of native code.
    //String CPU_ABI2 = android.os.Build.CPU_ABI2; //  The name of the second instruction set (CPU type + ABI convention) of native code.
    String DEVICE = android.os.Build.DEVICE; //  The name of the industrial design.
    String DISPLAY = android.os.Build.DISPLAY; //A build ID string meant for displaying to the user
    //String FINGERPRINT = android.os.Build.FINGERPRINT; //A string that uniquely identifies this build.
    //String HARDWARE = android.os.Build.HARDWARE; //The name of the hardware (from the kernel command line or /proc).
    //String HOST = android.os.Build.HOST;
    //String ID = android.os.Build.ID; //Either a changelist number, or a label like "M4-rc20".
    String MANUFACTURER = android.os.Build.MANUFACTURER; //The manufacturer of the product/hardware.
    //String MODEL = android.os.Build.MODEL; //The end-user-visible name for the end product.
    //String PRODUCT = android.os.Build.PRODUCT; //The name of the overall product.
    //String RADIO = android.os.Build.RADIO; //The radio firmware version number.
    //String TAGS = android.os.Build.TAGS; //Comma-separated tags describing the build, like "unsigned,debug".
    //String TYPE = android.os.Build.TYPE; //The type of build, like "user" or "eng".
    //String USER = android.os.Build.USER;

    String android_version = "Android " + ANDROID;
    String android_device = MANUFACTURER + " " + BRAND + " " + DEVICE;

    if (MANUFACTURER.equalsIgnoreCase("amazon")) {
        // we are on amazon device
        ZANaviNormalDonateActivity.on_amazon_device = true;
    }

    // debug
    // debug
    // android_device = "telechips telechips m801";
    // debug
    // debug

    String android_rom_name = DISPLAY;

    if (FDBL) {
        android_rom_name = android_rom_name + "; FD";
    }

    if (Navit_DonateVersion_Installed == false) {
        UserAgentString = "Mozilla/5.0 (Linux; U; " + "Z" + NavitAppVersion + "; " + android_version + "; "
                + android_device + " " + android_rom_name + ")";
        UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "Z" + NavitAppVersion + "; "
                + android_version + "; " + android_device + " " + android_rom_name + ")";
    } else {
        if (Navit_Largemap_DonateVersion_Installed == false) {
            UserAgentString = "Mozilla/5.0 (Linux; U; " + "donateZ" + NavitAppVersion + "; " + android_version
                    + "; " + android_device + " " + android_rom_name + ")";
            UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "donateZ" + NavitAppVersion + "; "
                    + android_version + "; " + android_device + " " + android_rom_name + ")";
        } else

        {
            UserAgentString = "Mozilla/5.0 (Linux; U; " + "LMdonateLMZ" + NavitAppVersion + "; "
                    + android_version + "; " + android_device + " " + android_rom_name + ")";
            UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "LMdonateLMZ" + NavitAppVersion
                    + "; " + android_version + "; " + android_device + " " + android_rom_name + ")";
        }
    }
    // System.out.println("UA=" + UserAgentString);

    // --------- enable GPS ? --------------
    // --------- enable GPS ? --------------
    //      try
    //      {
    //         final LocationManager llmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //         if (!llmanager.isProviderEnabled(LocationManager.GPS_PROVIDER))
    //         {
    //            buildAlertMessageNoGps();
    //         }
    //      }
    //      catch (Exception e)
    //      {
    //         e.printStackTrace();
    //      }
    // --------- enable GPS ? --------------
    // --------- enable GPS ? --------------

    unsupported = false;
    try {
        if (android_device.toLowerCase().contains("telechips")) {
            if (android_device.toLowerCase().contains("m801")) {
                // if the donate version is already installed, dont disable the app
                if (Navit_DonateVersion_Installed == false) {
                    if (Navit_Largemap_DonateVersion_Installed == false) {
                        // activate [Weltbild] Cat Nova again (19.12.2011)
                        // ** // unsupported = true;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        // this hangs the emulator, if emulator < 2.3 (only works in emulator >= 2.3)!!
        if (!NAVIT_IS_EMULATOR) {
            sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        }
    } catch (Exception e3) {
        e3.printStackTrace();
    }

    //      try
    //      {
    //         vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    //      }
    //      catch (Exception e)
    //      {
    //         e.printStackTrace();
    //      }
    //sensorManager_ = sensorManager;

    // light sensor -------------------
    try {
        lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        lightsensor_max_value = lightSensor.getMaximumRange();
        lightSensorEventListener = new SensorEventListener() {
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }

            @Override
            public void onSensorChanged(SensorEvent event) {
                try {
                    if (p.PREF_auto_night_mode) {
                        if (event.sensor.getType() == Sensor.TYPE_LIGHT) {

                            if (Navit.DEBUG_LUX_VALUE) {
                                debug_cur_lux_value = event.values[0];
                                NavitGraphics.NavitAOverlay_s.postInvalidate();
                            }

                            // System.out.println("Current Reading(Lux): cur=" + event.values[0] + " max=" + lightsensor_max_value);

                            if (night_mode == false) {
                                if (event.values[0] < p.PREF_night_mode_lux) {
                                    night_mode = true;
                                    set_night_mode(1);
                                    draw_map();
                                }
                            } else if (night_mode == true) {
                                if (event.values[0] > (p.PREF_night_mode_lux + p.PREF_night_mode_buffer)) {
                                    night_mode = false;
                                    set_night_mode(0);
                                    draw_map();
                                }
                            }
                        }
                    } else {
                        try {
                            sensorManager.unregisterListener(lightSensorEventListener);
                            System.out.println("stop lightsensor");
                        } catch (Exception e) {
                        }

                        try {
                            night_mode = false;
                            set_night_mode(0);
                            draw_map();
                        } catch (Exception e) {
                        }
                    }
                } catch (Exception e) {
                    // e.printStackTrace();
                }
            }

        };
    } catch (Exception e) {
    }
    // light sensor -------------------

    generic_alert_box = new AlertDialog.Builder(this);
    /*
     * show info box for first time users
     */
    AlertDialog.Builder infobox = new AlertDialog.Builder(this);
    //. english text: Welcome to ZANavi
    infobox.setTitle(Navit.get_text("__INFO_BOX_TITLE__")); //TRANS
    infobox.setCancelable(false);
    final TextView message = new TextView(this);
    message.setFadingEdgeLength(20);
    message.setVerticalFadingEdgeEnabled(true);
    message.setPadding(10, 5, 10, 5);
    message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    message.setGravity(Gravity.LEFT);
    // message.setScrollBarStyle(TextView.SCROLLBARS_INSIDE_OVERLAY);
    // message.setVerticalScrollBarEnabled(true);
    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
            RelativeLayout.LayoutParams.FILL_PARENT);
    rlp.leftMargin = 7;
    rlp.rightMargin = 7;

    Navit.Navit_Geocoder = null;
    try {
        // for online search
        Navit.Navit_Geocoder = new Geocoder(this);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //      if (api_version_int < 11)
    //      {
    //         //TRANS
    //         infobox.setPositiveButton(Navit.get_text("Ok"), new DialogInterface.OnClickListener()
    //         {
    //            public void onClick(DialogInterface arg0, int arg1)
    //            {
    //               Log.e("Navit", "Ok, user saw the infobox");
    //            }
    //         });
    //
    //         //TRANS
    //         infobox.setNeutralButton(Navit.get_text("More info"), new DialogInterface.OnClickListener()
    //         {
    //            public void onClick(DialogInterface arg0, int arg1)
    //            {
    //               Log.e("Navit", "user wants more info, show the website");
    //               // URL to ZANavi Manual (in english language)
    //               String url = "http://zanavi.cc/index.php/Manual";
    //               if (FDBL)
    //               {
    //                  url = "http://fd.zanavi.cc/manual";
    //               }
    //               Intent i = new Intent(Intent.ACTION_VIEW);
    //               i.setData(Uri.parse(url));
    //               startActivity(i);
    //            }
    //         });
    //      }

    info_popup_seen_count_end = false;
    File navit_first_startup = new File(FIRST_STARTUP_FILE);
    // if file does NOT exist, show the info box
    if (!navit_first_startup.exists()) {
        // set first-ever-startup flag
        first_ever_startup = true;
        info_popup_seen_count_end = true; // don't show on first ever start of the app
        startup_status = Navit_Status_COMPLETE_NEW_INSTALL;
        FileOutputStream fos_temp;
        try {
            info_popup_seen_count++;
            fos_temp = new FileOutputStream(navit_first_startup);
            fos_temp.write((int) info_popup_seen_count); // use to store info popup seen count
            fos_temp.flush();
            fos_temp.close();

            //            if (api_version_int < 11)
            //            {
            //               message.setLayoutParams(rlp);
            //               //. TRANSLATORS: multiline info text for first startup of application (see en_US for english text)
            //               final SpannableString s = new SpannableString(" " + Navit.get_text("__INFO_BOX_TEXT__")); //TRANS
            //               Linkify.addLinks(s, Linkify.WEB_URLS);
            //               message.setText(s);
            //               message.setMovementMethod(LinkMovementMethod.getInstance());
            //               infobox.setView(message);
            //               infobox.show();
            //            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        FileOutputStream fos_temp;
        FileInputStream fis_temp;
        try {
            fis_temp = new FileInputStream(navit_first_startup);
            info_popup_seen_count = fis_temp.read();
            fis_temp.close();

            if (info_popup_seen_count < 0) {
                info_popup_seen_count = 0;
            }

            // we wrote "A" -> (int)65 previously, so account for that
            if (info_popup_seen_count == 65) {
                info_popup_seen_count = 0;
            }

            if (info_popup_seen_count > info_popup_seen_count_max) {
                info_popup_seen_count_end = true;
            } else {
                info_popup_seen_count++;
                fos_temp = new FileOutputStream(navit_first_startup);
                fos_temp.write((int) info_popup_seen_count); // use to store info popup seen count
                fos_temp.flush();
                fos_temp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * show info box for first time users
     */

    //
    // ----------- info popup
    // ----------- info popup
    // ----------- info popup
    // ----------- info popup
    //

    intro_flag_info = false;
    if ((!info_popup_seen_count_end) && (startup_status == Navit_Status_NORMAL_STARTUP)) {
        intro_flag_info = true;
    }

    System.out.println("info_popup_seen_count=" + info_popup_seen_count);
    System.out.println("info_popup_seen_count_end=" + info_popup_seen_count_end + " intro_flag_info="
            + intro_flag_info + " startup_status=" + startup_status);

    // make handler statically available for use in "msg_to_msg_handler"
    Navit_progress_h = this.progress_handler;

    //      try
    //      {
    //         Navit.bigmap_bitmap = BitmapFactory.decodeResource(getResources(), R.raw.bigmap_colors_zanavi2);
    //      }
    //      catch (Exception e)
    //      {
    //         // when not enough memory is available, then disable large world overview map!
    //         System.gc();
    //         Navit.bigmap_bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    //      }
    //      // ------no----- // Navit.bigmap_bitmap.setDensity(120); // set our dpi!!

    try {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        ActivityResults = new NavitActivityResult[16];
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        NavitAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        e.printStackTrace();
    }

    PowerManager pm = null;
    try {
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        // -- // pm.wakeUp(SystemClock.uptimeMillis()); // -- //
        // **screen always full on** // wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen");
        // **screen can go off, cpu will stay on** // wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen");

        // this works so far, lets the screen dim, but it cpu and screen stays on
        wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen");
    } catch (Exception e) {
        e.printStackTrace();
        wl = null;
    }

    try {
        wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ZANaviNeedCpu");
    } catch (Exception e) {
        e.printStackTrace();
        wl_cpu = null;
    }

    try {
        wl_navigating = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "ZANaviNavigationOn");
    } catch (Exception e) {
        Log.e("Navit", "WakeLock NAV: create failed!!");
        e.printStackTrace();
        wl_navigating = null;
    }

    //      try
    //      {
    //         if (wl_navigating != null)
    //         {
    //            wl_navigating.acquire();
    //            Log.e("Navit", "WakeLock NAV: acquire 00");
    //         }
    //      }
    //      catch (Exception e)
    //      {
    //         Log.e("Navit", "WakeLock NAV: something wrong 00");
    //         e.printStackTrace();
    //      }

    //      try
    //      {
    //         if (wl != null)
    //         {
    //            try
    //            {
    //               wl.release();
    //            }
    //            catch (Exception e2)
    //            {
    //            }
    //            wl.acquire();
    //            Log.e("Navit", "WakeLock: acquire 1");
    //         }
    //      }
    //      catch (Exception e)
    //      {
    //         e.printStackTrace();
    //      }

    // -- extract overview maps --
    // -- extract overview maps --

    // File navit_worldmap2_file = new File(NAVIT_DATA_DIR + "/share/worldmap2.txt");
    File navit_worldmap2_file = new File(MAP_FILENAME_PATH + "/worldmap2.txt");
    if (!navit_worldmap2_file.exists()) {
        if (!extractRes("worldmap2", MAP_FILENAME_PATH + "/worldmap2.txt")) {
            Log.e("Navit", "Failed to extract worldmap2.txt");
        }
    }

    File navit_worldmap5_file = new File(MAP_FILENAME_PATH + "/worldmap5.txt");
    if (!navit_worldmap5_file.exists()) {
        if (!extractRes("worldmap5", MAP_FILENAME_PATH + "/worldmap5.txt")) {
            Log.e("Navit", "Failed to extract worldmap5.txt");
        }
    }
    // -- extract overview maps --
    // -- extract overview maps --

    Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language + "_"
            + NavitTextTranslations.sub_language);
    if (!extractRes(NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language,
            NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "_"
                    + NavitTextTranslations.sub_language + "/LC_MESSAGES/navit.mo")) {
        Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language + "_"
                + NavitTextTranslations.sub_language);
    }

    Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language + "_"
            + NavitTextTranslations.sub_language.toLowerCase());
    if (!extractRes(
            NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase(),
            NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "_"
                    + NavitTextTranslations.sub_language + "/LC_MESSAGES/navit.mo")) {
        Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language + "_"
                + NavitTextTranslations.sub_language.toLowerCase());
    }

    Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language);
    if (!extractRes(NavitTextTranslations.main_language,
            NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "/LC_MESSAGES/navit.mo")) {
        Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language);
    }

    // DEBUG - check if language file is on SDCARD -
    try {
        File debug_mo_src = new File("/sdcard/zanavi/debug/navit.mo");
        File debug_mo_dest = new File(
                NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "/LC_MESSAGES/navit.mo");
        //* File navit_debug_dir = new File("/sdcard/zanavi/debug/");
        //* navit_debug_dir.mkdirs();
        copyFile(debug_mo_src, debug_mo_dest);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // DEBUG - check if language file is on SDCARD -

    File navit_config_xml_file = new File(NAVIT_DATA_SHARE_DIR + "/navit.xml");
    if ((!navit_config_xml_file.exists()) || (NAVIT_ALWAYS_UNPACK_XMLFILE)) {
        xmlconfig_unpack_file = true;
        Log.e("Navit", "navit.xml does not exist, unpacking in any case");
    }

    my_display_density = "mdpi";
    // ldpi display (120 dpi)

    NavitGraphics.Global_want_dpi = Navit.metrics.densityDpi;
    NavitGraphics.Global_want_dpi_other = Navit.metrics.densityDpi;

    if (Navit.metrics.densityDpi <= 120) {
        my_display_density = "ldpi";
        if (xmlconfig_unpack_file) {
            if (!extractRes("navitldpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) {
                Log.e("Navit", "Failed to extract navit.xml for ldpi device(s)");
            }
        }
    }
    // mdpi display (160 dpi)
    else if ((Navit.metrics.densityDpi > 120) && (Navit.metrics.densityDpi <= 160)) {
        my_display_density = "mdpi";
        if (xmlconfig_unpack_file) {
            if (!extractRes("navitmdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) {
                Log.e("Navit", "Failed to extract navit.xml for mdpi device(s)");
            }
        }
    }
    // hdpi display (240 dpi)
    else if ((Navit.metrics.densityDpi > 160) && (Navit.metrics.densityDpi < 320))
    //else if (Navit.metrics.densityDpi == 240)
    {
        my_display_density = "hdpi";
        if (xmlconfig_unpack_file) {
            if (!extractRes("navithdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) {
                Log.e("Navit", "Failed to extract navit.xml for hdpi device(s)");
            }
        }
    }
    // xhdpi display (320 dpi)
    else if (Navit.metrics.densityDpi >= 320) {
        // set the map display DPI down. otherwise everything will be very small and unreadable
        // and performance will be very low
        if (p.PREF_shrink_on_high_dpi) {
            NavitGraphics.Global_want_dpi = NavitGraphics.Global_Scaled_DPI_normal;
        }
        NavitGraphics.Global_want_dpi_other = NavitGraphics.Global_Scaled_DPI_normal;

        Log.e("Navit", "found xhdpi device, this is not fully supported yet");
        Log.e("Navit", "using hdpi values for compatibility");
        my_display_density = "hdpi";
        if (xmlconfig_unpack_file) {
            if (!extractRes("navithdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) {
                Log.e("Navit", "Failed to extract navit.xml for xhdpi device(s)");
            }
        }
    } else {
        /* default, meaning we just dont know what display this is */
        if (xmlconfig_unpack_file) {
            if (!extractRes("navitmdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) {
                Log.e("Navit", "Failed to extract navit.xml (default version)");
            }
        }
    }
    // Debug.startMethodTracing("calc");

    int have_dpi = Navit.metrics.densityDpi;

    System.out.println("Global_want_dpi[001]=" + NavitGraphics.Global_want_dpi + ":" + Navit.metrics.densityDpi
            + ":" + NavitGraphics.Global_dpi_factor + ":" + NavitGraphics.Global_dpi_factor_better);

    if (NavitGraphics.Global_want_dpi == have_dpi) {
        NavitGraphics.Global_dpi_factor = 1;
        NavitGraphics.preview_coord_factor = 1;
    } else
    // this was missing??????!!!!!!!!!??????!!!!!!
    {
        NavitGraphics.Global_dpi_factor = ((float) NavitGraphics.Global_want_dpi / (float) have_dpi);
        NavitGraphics.preview_coord_factor = ((float) have_dpi / (float) NavitGraphics.Global_want_dpi);
    }

    System.out.println("Global_want_dpi[002]=" + NavitGraphics.Global_dpi_factor + ":"
            + NavitGraphics.preview_coord_factor);

    // gggggggggggggggggggggggggg new !!!!!!!!!!!!!!!!!!!!

    // --> dont use!! NavitMain(this, langu, android.os.Build.VERSION.SDK_INT);
    Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));

    // -- report share dir back to C-code --
    //Message msg2 = new Message();
    //Bundle b2 = new Bundle();
    //b2.putInt("Callback", 82);
    //b2.putString("s", NAVIT_DATA_DIR + "/share/");
    //msg2.setData(b2);
    //N_NavitGraphics.callback_handler.sendMessage(msg2);
    // -- report share dir back to C-code --

    // -- report data dir back to C-code --
    //msg2 = new Message();
    //b2 = new Bundle();
    //b2.putInt("Callback", 84);
    //b2.putString("s", NAVIT_DATA_DIR + "/");
    //msg2.setData(b2);
    //N_NavitGraphics.callback_handler.sendMessage(msg2);
    // -- report share dir back to C-code --

    draw_osd_thread = new drawOSDThread();
    draw_osd_thread.start();

    cwthr = new CWorkerThread();
    cwthr.start();

    // --new--
    cwthr.StartMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), "" + Navit.metrics.densityDpi,
            NAVIT_DATA_DIR, NAVIT_DATA_SHARE_DIR);

    // --old--
    // NavitMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density);
    // --old--
    // NavitActivity(3);

    // CAUTION: don't use android.os.Build.VERSION.SDK_INT if <uses-sdk android:minSdkVersion="3" />
    // You will get exception on all devices with Android 1.5 and lower
    // because Build.VERSION.SDK_INT is since SDK 4 (Donut 1.6)

    //      (see: http://developer.android.com/guide/appendix/api-levels.html)
    //      Platform Version               API Level
    //      =============================================
    //      Android 4.0.3               15
    //      Android 4.0, 4.0.1, 4.0.2      14
    //      Android 3.2                  13
    //      Android 3.1                  12
    //      Android 3.0                  11
    //      Android 2.3.3                10
    //      Android 2.3.1                 9
    //      Android 2.2                   8
    //      Android 2.1                   7
    //      Android 2.0.1                 6
    //      Android 2.0                   5
    //      Android 1.6                   4
    //      Android 1.5                   3
    //      Android 1.1                   2
    //      Android 1.0                   1

    Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    //try
    //{
    //   Thread.sleep(2000);
    //}
    //catch (InterruptedException e)
    //{
    //}

    //getPrefs();
    //activatePrefs();

    // unpack some localized Strings
    // a test now, later we will unpack all needed strings for java, here at this point!!
    //String x = NavitGraphics.getLocalizedString("Austria");
    //Log.e("Navit", "x=" + x);
    Navit.show_mem_used();

    /*
     * GpsStatus.Listener listener = new GpsStatus.Listener()
     * {
     * public void onGpsStatusChanged(int event)
     * {
     * //System.out.println("xxxxx");
     * if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS)
     * {
     * }
     * }
     * };
     */

    try {
        Intent sintent = new Intent();
        sintent.setPackage("com.zoffcc.applications.zanavi_msg");
        sintent.setAction("com.zoffcc.applications.zanavi_msg.ZanaviCloudService");
        // ComponentName cname = startService(sintent);
        // Log.i("NavitPlugin", "start Service res=" + cname);
        // System.out.println("NavitPlugin:bind to Service");
        boolean res_bind = bindService(sintent, serviceConnection, Context.BIND_AUTO_CREATE);
        // Log.i("NavitPlugin", "bind to Service res=" + res_bind);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------
    try {
        intro_flag_indexmissing = false;
        allow_use_index_search();
        if (Navit_index_on_but_no_idx_files) {
            if (!NavitMapDownloader.download_active_start) {
                intro_flag_indexmissing = true;
            }
        }

    } catch (Exception e) {
    }

    try {
        intro_flag_nomaps = false;
        if (!have_maps_installed()) {
            if ((!NavitMapDownloader.download_active) && (!NavitMapDownloader.download_active_start)) {
                intro_flag_nomaps = true;
            }
        }
    } catch (Exception e) {
    }

    intro_flag_firststart = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PREF_KEY_FIRST_START,
            true);
    if (intro_flag_firststart) {
        intro_flag_update = false;
    }

    if (EasyPermissions.hasPermissions(this, perms)) {
        // have permissions!
        intro_flag_permissions = false;
    } else {
        // ask for permissions
        intro_flag_permissions = true;
    }
    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------

    // -------------- INTRO --------------
    // -------------- INTRO --------------
    // -------------- INTRO --------------

    intro_show_count = 0;

    //      // -------------- INTRO --------------
    //      // -------------- INTRO --------------
    //      // -------------- INTRO --------------

    // if (Navit.METHOD_DEBUG) Navit.my_func_name(1);
}