Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

In this page you can find the example usage for java.io OutputStreamWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.panet.imeta.repository.Repository.java

private void exportTransformations(ProgressMonitorListener monitor, RepositoryDirectory dirTree,
        OutputStreamWriter writer) throws KettleException {
    try {// w  ww .  j  av  a  2s  . co  m
        if (monitor != null)
            monitor.subTask("Exporting the transformations...");

        // Loop over all the directory id's
        long dirids[] = dirTree.getDirectoryIDs();
        System.out.println(
                "Going through " + dirids.length + " directories in directory [" + dirTree.getPath() + "]");

        for (int d = 0; d < dirids.length
                && (monitor == null || (monitor != null && !monitor.isCanceled())); d++) {
            RepositoryDirectory repdir = dirTree.findDirectory(dirids[d]);

            System.out.println("Directory ID #" + d + " : " + dirids[d] + " : " + repdir);

            String trans[] = getTransformationNames(dirids[d]);
            for (int i = 0; i < trans.length
                    && (monitor == null || (monitor != null && !monitor.isCanceled())); i++) {
                try {
                    TransMeta ti = new TransMeta(this, trans[i], repdir);
                    System.out.println("Loading/Exporting transformation [" + repdir.getPath() + " : "
                            + trans[i] + "]  (" + ti.getDirectory().getPath() + ")");
                    if (monitor != null)
                        monitor.subTask("Exporting transformation [" + trans[i] + "]");

                    writer.write(ti.getXML() + Const.CR);
                } catch (KettleException ke) {
                    log.logError(toString(), "An error occurred reading transformation [" + trans[i]
                            + "] from directory [" + repdir + "] : " + ke.getMessage());
                    log.logError(toString(), "Transformation [" + trans[i] + "] from directory [" + repdir
                            + "] was not exported because of a loading error!");
                }
            }

            // OK, then export the transformations in the sub-directories as
            // well!
            if (repdir.getID() != dirTree.getID())
                exportTransformations(null, repdir, writer);
        }
        if (monitor != null)
            monitor.worked(1);

    } catch (Exception e) {
        throw new KettleException("Error while exporting repository transformations", e);
    }
}

From source file:carnero.cgeo.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/* w w  w  . ja v  a2s.  c om*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(cgSettings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(cgSettings.tag + "|" + requestId, "[" + method + " | " + httpCode
                        + "] Failed to download " + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java

/**
 * Adds an ignore file exclusion to the .tfignore file in the specified
 * directory, creating the file if necessary.
 *
 * @param exclusion/*from   ww  w . ja  v a  2s . c  om*/
 *        ignore glob to add to the .tfignore file (must not be
 *        <code>null</code> or empty)
 * @param ignoreFileDirectory
 *        directory whose .tfignore file should be used (must not be
 *        <code>null</code> or empty)
 * @throws FileNotFoundException
 *         if the specified ignore file directory does not exist or is not a
 *         directory
 * @throws IOException
 *         if there was an error reading or writing the ignore file
 * @return the full path to the .tfignore file that was modified
 */
public String addIgnoreFileExclusion(final String exclusion, final String ignoreFileDirectory)
        throws FileNotFoundException, IOException {
    Check.notNullOrEmpty(exclusion, "exclusion"); //$NON-NLS-1$
    Check.notNullOrEmpty(ignoreFileDirectory, "ignoreFileDirectory"); //$NON-NLS-1$

    final File ignoreFileDirectoryFile = new File(ignoreFileDirectory);

    if (!ignoreFileDirectoryFile.exists() || !ignoreFileDirectoryFile.isDirectory()) {
        throw new FileNotFoundException(
                MessageFormat.format(Messages.getString("Workspace.PathDoesNotExistOrIsNotDirectoryFormat"), //$NON-NLS-1$
                        ignoreFileDirectoryFile));
    }

    final File ignoreFile = new File(ignoreFileDirectoryFile, LocalItemExclusionEvaluator.IGNORE_FILE_NAME);

    if (!isLocalPathMapped(ignoreFile.getAbsolutePath())) {
        throw new ItemNotMappedException(
                MessageFormat.format(Messages.getString("Workspace.ItemNotMappedExceptionFormat"), ignoreFile)); //$NON-NLS-1$
    }

    final boolean exists = ignoreFile.exists();

    if (!exists) {
        // Write the file out in UTF-8 (.NET impl writes BOM but we don't
        // control that in Java)
        FileOutputStream outputStream = null;
        OutputStreamWriter streamWriter = null;
        try {
            outputStream = new FileOutputStream(ignoreFile, false);
            streamWriter = new OutputStreamWriter(outputStream, "UTF-8"); //$NON-NLS-1$

            streamWriter.write(getTFIgnoreHeader());
            streamWriter.write(NewlineUtils.PLATFORM_NEWLINE);
            streamWriter.write(NewlineUtils.PLATFORM_NEWLINE);
            streamWriter.write(exclusion);
            streamWriter.write(NewlineUtils.PLATFORM_NEWLINE);
        } finally {
            if (streamWriter != null) {
                IOUtils.closeSafely(streamWriter);
            }
            if (outputStream != null) {
                IOUtils.closeSafely(outputStream);
            }
        }
    } else {
        // Discover the current encoding of the file and use that to write
        // out the data

        final FileEncoding tfsEncoding = FileEncodingDetector.detectEncoding(ignoreFile.getAbsolutePath(),
                FileEncoding.AUTOMATICALLY_DETECT);

        Charset charset = CodePageMapping.getCharset(tfsEncoding.getCodePage(), false);

        if (charset == null) {
            /*
             * getCharset() couldn't find a Java Charset for the code page.
             * This can happen if the file was detected as
             * FileEncoding.BINARY.
             */
            charset = CodePageMapping.getCharset(FileEncoding.getDefaultTextEncoding().getCodePage());
        }

        boolean writeNewLine = false;

        final FileInputStream inputStream = new FileInputStream(ignoreFile);
        try {
            final String existingContent = IOUtils.toString(inputStream, charset.name());

            if (existingContent.length() > 0) {
                // Covers Unix (bare \n) and Windows (\r\n).
                final char lastCharacter = existingContent.charAt(existingContent.length() - 1);
                if (lastCharacter != '\n') {
                    writeNewLine = true;
                }
            }
        } finally {
            if (inputStream != null) {
                IOUtils.closeSafely(inputStream);
            }
        }

        // Write the file out in UTF-8 (.NET impl writes BOM but we don't
        // control that in Java)
        FileOutputStream outputStream = null;
        OutputStreamWriter streamWriter = null;
        try {
            // Append
            outputStream = new FileOutputStream(ignoreFile, true);
            streamWriter = new OutputStreamWriter(outputStream, charset);

            if (writeNewLine) {
                streamWriter.write(NewlineUtils.PLATFORM_NEWLINE);
            }

            streamWriter.write(exclusion);
            streamWriter.write(NewlineUtils.PLATFORM_NEWLINE);
        } finally {
            if (streamWriter != null) {
                IOUtils.closeSafely(streamWriter);
            }
            if (outputStream != null) {
                IOUtils.closeSafely(outputStream);
            }
        }
    }

    if (WorkspaceLocation.LOCAL == this.getLocation()) {
        /*
         * In case the caller calls QueryPendingChanges immediately after
         * this call (as the Promote Candidate Changes dialog does) and the
         * watcher does not pick up the change in time.
         */
        getWorkspaceWatcher().markPathChanged(ignoreFile.getAbsolutePath());
    }

    if (!exists) {
        // Always UTF-8 encoding if the file didn't already exist
        pendAdd(new String[] { ignoreFile.getAbsolutePath() }, false, FileEncoding.UTF_8, LockLevel.UNCHANGED,
                GetOptions.NONE, PendChangesOptions.NONE);
    }

    return ignoreFile.getAbsolutePath();
}

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

@SuppressLint("NewApi")
public boolean onOptionsItemSelected_wrapper(int id) {
    // Handle item selection
    switch (id) {
    case 1://from   w w w.j a v  a2s  . c o  m
        // zoom in
        Message msg = new Message();
        Bundle b = new Bundle();
        b.putInt("Callback", 1);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
        // if we zoom, hide the bubble
        if (N_NavitGraphics.NavitAOverlay != null) {
            N_NavitGraphics.NavitAOverlay.hide_bubble();
        }
        Log.e("Navit", "onOptionsItemSelected -> zoom in");
        break;
    case 2:
        // zoom out
        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 2);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
        // if we zoom, hide the bubble
        if (N_NavitGraphics.NavitAOverlay != null) {
            N_NavitGraphics.NavitAOverlay.hide_bubble();
        }
        Log.e("Navit", "onOptionsItemSelected -> zoom out");
        break;
    case 3:
        // map download menu
        Intent map_download_list_activity = new Intent(this, NavitDownloadSelectMapActivity.class);
        this.startActivityForResult(map_download_list_activity, Navit.NavitDownloaderPriSelectMap_id);
        break;
    case 5:
        toggle_poi_pref();
        set_poi_layers();
        draw_map();
        break;
    case 6:
        // ok startup address search activity (online google maps search)
        Navit.use_index_search = false;
        Intent search_intent = new Intent(this, NavitAddressSearchActivity.class);
        search_intent.putExtra("title", Navit.get_text("Enter: City and Street")); //TRANS
        search_intent.putExtra("address_string", Navit_last_address_search_string);
        //search_intent.putExtra("hn_string", Navit_last_address_hn_string);
        search_intent.putExtra("type", "online");
        String pm_temp = "0";
        if (Navit_last_address_partial_match) {
            pm_temp = "1";
        }
        search_intent.putExtra("partial_match", pm_temp);
        this.startActivityForResult(search_intent, NavitAddressSearch_id_online);
        break;
    case 7:
        // ok startup address search activity (offline binfile search)
        Navit.use_index_search = Navit.allow_use_index_search();
        Intent search_intent2 = new Intent(this, NavitAddressSearchActivity.class);
        search_intent2.putExtra("title", Navit.get_text("Enter: City and Street")); //TRANS
        search_intent2.putExtra("address_string", Navit_last_address_search_string);
        search_intent2.putExtra("hn_string", Navit_last_address_hn_string);
        search_intent2.putExtra("type", "offline");
        search_intent2.putExtra("search_country_id", Navit_last_address_search_country_id);

        String pm_temp2 = "0";
        if (Navit_last_address_partial_match) {
            pm_temp2 = "1";
        }

        search_intent2.putExtra("partial_match", pm_temp2);
        this.startActivityForResult(search_intent2, NavitAddressSearch_id_offline);
        break;
    case 8:
        // map delete menu
        Intent map_delete_list_activity2 = new Intent(this, NavitDeleteSelectMapActivity.class);
        this.startActivityForResult(map_delete_list_activity2, Navit.NavitDeleteSecSelectMap_id);
        break;
    case 9:
        // stop navigation (this menu should only appear when navigation is actually on!)
        Message msg2 = new Message();
        Bundle b2 = new Bundle();
        b2.putInt("Callback", 7);
        msg2.setData(b2);
        NavitGraphics.callback_handler.sendMessage(msg2);
        Log.e("Navit", "stop navigation");
        break;
    case 10:
        // open settings menu
        Intent settingsActivity = new Intent(getBaseContext(), NavitPreferences.class);
        startActivity(settingsActivity);
        break;
    case 11:
        //zoom_to_route
        zoom_to_route();
        break;
    case 12:

        // --------- make app crash ---------
        // --------- make app crash ---------
        // --------- make app crash ---------
        // ** // DEBUG // ** // crash_app_java(1);
        // ** // DEBUG // ** // crash_app_C();
        // --------- make app crash ---------
        // --------- make app crash ---------
        // --------- make app crash ---------

        // announcer off
        Navit_Announcer = false;
        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 34);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
        try {
            invalidateOptionsMenu();
        } catch (Exception e) {
        }
        break;
    case 13:
        // announcer on
        Navit_Announcer = true;
        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 35);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
        try {
            invalidateOptionsMenu();
        } catch (Exception e) {
        }
        break;
    case 14:
        // show recent destination list
        Intent i2 = new Intent(this, NavitRecentDestinationActivity.class);
        this.startActivityForResult(i2, Navit.NavitRecentDest_id);
        break;
    case 15:
        // show current target on googlemaps
        String current_target_string = NavitGraphics.CallbackGeoCalc(4, 1, 1);
        // Log.e("Navit", "got target  1: "+current_target_string);
        if (current_target_string.equals("x:x")) {
            Log.e("Navit", "no target set!");
        } else {
            try {
                String tmp[] = current_target_string.split(":", 2);
                googlemaps_show(tmp[0], tmp[1], "ZANavi Target");
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Navit", "problem with target!");
            }
        }
        break;
    case 16:
        // show online manual
        Log.e("Navit", "user wants online help, show the website lang="
                + NavitTextTranslations.main_language.toLowerCase());
        // URL to ZANavi Manual (in english language)
        String url = "http://zanavi.cc/index.php/Manual";
        if (FDBL) {
            url = "http://fd.zanavi.cc/manual";
        }
        if (NavitTextTranslations.main_language.toLowerCase().equals("de")) {
            // show german manual
            url = "http://zanavi.cc/index.php/Manual/de";
            if (FDBL) {
                url = "http://fd.zanavi.cc/manualde";
            }
        }

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
        break;
    case 17:
        // show age of maps (online)
        Intent i3 = new Intent(Intent.ACTION_VIEW);
        i3.setData(Uri.parse(NavitMapDownloader.ZANAVI_MAPS_AGE_URL));
        startActivity(i3);
        break;
    case 18:
        Intent intent_latlon = new Intent(Intent.ACTION_MAIN);
        //intent_latlon.setAction("android.intent.action.POINTPICK");
        intent_latlon.setPackage("com.cruthu.latlongcalc1");
        intent_latlon.setClassName("com.cruthu.latlongcalc1", "com.cruthu.latlongcalc1.LatLongMain");
        //intent_latlon.setClassName("com.cruthu.latlongcalc1", "com.cruthu.latlongcalc1.LatLongPointPick");
        try {
            startActivity(intent_latlon);
        } catch (Exception e88) {
            e88.printStackTrace();
            // show install page
            try {
                // String urlx = "http://market.android.com/details?id=com.cruthu.latlongcalc1";
                String urlx = "market://details?id=com.cruthu.latlongcalc1";
                Intent ix = new Intent(Intent.ACTION_VIEW);
                ix.setData(Uri.parse(urlx));
                startActivity(ix);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        break;
    case 19:
        // GeoCoordEnterDialog
        Intent it001 = new Intent(this, GeoCoordEnterDialog.class);
        this.startActivityForResult(it001, Navit.NavitGeoCoordEnter_id);
        break;
    case 20:
        // convert GPX file
        Intent intent77 = new Intent(getBaseContext(), FileDialog.class);
        File a = new File(p.PREF_last_selected_dir_gpxfiles);
        try {
            // convert the "/../" in the path to normal absolut dir
            intent77.putExtra(FileDialog.START_PATH, a.getCanonicalPath());
            //can user select directories or not
            intent77.putExtra(FileDialog.CAN_SELECT_DIR, false);
            // disable the "new" button
            intent77.putExtra(FileDialog.SELECTION_MODE, SelectionMode.MODE_OPEN);
            //alternatively you can set file filter
            //intent.putExtra(FileDialog.FORMAT_FILTER, new String[] { "gpx" });
            startActivityForResult(intent77, Navit.NavitGPXConvChooser_id);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        break;
    case 21:
        // add traffic block (like blocked road, or construction site) at current location of crosshair
        try {
            String traffic = "";
            if (Navit.GFX_OVERSPILL) {
                traffic = NavitGraphics.CallbackGeoCalc(7,
                        (int) (NavitGraphics.Global_dpi_factor
                                * (NavitGraphics.mCanvasWidth / 2 + NavitGraphics.mCanvasWidth_overspill)),
                        (int) (NavitGraphics.Global_dpi_factor
                                * (NavitGraphics.mCanvasHeight / 2 + NavitGraphics.mCanvasHeight_overspill)));
            } else {
                traffic = NavitGraphics.CallbackGeoCalc(7,
                        (int) (NavitGraphics.Global_dpi_factor * NavitGraphics.mCanvasWidth / 2),
                        (int) (NavitGraphics.Global_dpi_factor * NavitGraphics.mCanvasHeight / 2));
            }

            // System.out.println("traffic=" + traffic);
            File traffic_file_dir = new File(MAP_FILENAME_PATH);
            traffic_file_dir.mkdirs();
            File traffic_file = new File(MAP_FILENAME_PATH + "/traffic.txt");
            FileOutputStream fOut = null;
            OutputStreamWriter osw = null;
            try {
                fOut = new FileOutputStream(traffic_file, true);
                osw = new OutputStreamWriter(fOut);
                osw.write("type=traffic_distortion maxspeed=0" + "\n"); // item header
                osw.write(traffic); // item coordinates
                osw.close();
                fOut.close();
            } catch (Exception ef) {
                ef.printStackTrace();
            }

            // update route, if a route is set
            msg = new Message();
            b = new Bundle();
            b.putInt("Callback", 73);
            msg.setData(b);
            NavitGraphics.callback_handler.sendMessage(msg);

            // draw map no-async
            msg = new Message();
            b = new Bundle();
            b.putInt("Callback", 64);
            msg.setData(b);
            NavitGraphics.callback_handler.sendMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    case 22:
        // clear all traffic blocks
        try {
            File traffic_file = new File(MAP_FILENAME_PATH + "/traffic.txt");
            traffic_file.delete();

            // update route, if a route is set
            msg = new Message();
            b = new Bundle();
            b.putInt("Callback", 73);
            msg.setData(b);
            NavitGraphics.callback_handler.sendMessage(msg);

            // draw map no-async
            msg = new Message();
            b = new Bundle();
            b.putInt("Callback", 64);
            msg.setData(b);
            NavitGraphics.callback_handler.sendMessage(msg);
        } catch (Exception e) {
        }
        break;
    case 23:
        // clear all GPX maps
        try {
            File gpx_file = new File(MAP_FILENAME_PATH + "/gpxtracks.txt");
            gpx_file.delete();

            // draw map no-async
            msg = new Message();
            b = new Bundle();
            b.putInt("Callback", 64);
            msg.setData(b);
            NavitGraphics.callback_handler.sendMessage(msg);
        } catch (Exception e) {
        }
        break;
    case 24:
        // show feedback form
        Intent i4 = new Intent(this, NavitFeedbackFormActivity.class);
        this.startActivityForResult(i4, Navit.NavitSendFeedback_id);
        break;
    case 25:
        // share the current destination with your friends         
        String current_target_string2 = NavitGraphics.CallbackGeoCalc(4, 1, 1);
        if (current_target_string2.equals("x:x")) {
            Log.e("Navit", "no target set!");
        } else {
            try {
                String tmp[] = current_target_string2.split(":", 2);

                if (Navit.OSD_route_001.arriving_time_valid) {
                    share_location(tmp[0], tmp[1], Navit.get_text("Meeting Point"),
                            Navit.get_text("Meeting Point"), Navit.OSD_route_001.arriving_time, true);
                } else {
                    share_location(tmp[0], tmp[1], Navit.get_text("Meeting Point"),
                            Navit.get_text("Meeting Point"), "", true);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Navit", "problem with target!");
            }
        }
        break;
    case 26:
        // donate
        Log.e("Navit", "start donate app");
        donate();
        break;
    case 27:
        // donate
        Log.e("Navit", "donate bitcoins");
        donate_bitcoins();
        break;
    case 28:
        // replay GPS file
        Intent intent771 = new Intent(getBaseContext(), FileDialog.class);
        File a1 = new File(Navit.NAVIT_DATA_DEBUG_DIR);
        try {
            // convert the "/../" in the path to normal absolut dir
            intent771.putExtra(FileDialog.START_PATH, a1.getCanonicalPath());
            //can user select directories or not
            intent771.putExtra(FileDialog.CAN_SELECT_DIR, false);
            // disable the "new" button
            intent771.putExtra(FileDialog.SELECTION_MODE, SelectionMode.MODE_OPEN);
            //alternatively you can set file filter
            intent771.putExtra(FileDialog.FORMAT_FILTER, new String[] { "txt", "yaml" });
            startActivityForResult(intent771, Navit.NavitReplayFileConvChooser_id);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        break;
    case 29:
        // About Screen
        Intent it002 = new Intent(this, ZANaviAboutPage.class);
        this.startActivityForResult(it002, Navit.ZANaviAbout_id);
        break;
    case 88:
        // dummy entry, just to make "breaks" in the menu
        break;
    case 601:
        // DEBUG: activate demo vehicle and set position to position to screen center

        Navit.DemoVehicle = true;

        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 101);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);

        final Thread demo_v_001 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000); // wait 1 seconds before we start

                    try {
                        float lat = 0;
                        float lon = 0;

                        String lat_lon = "";
                        if (Navit.GFX_OVERSPILL) {
                            lat_lon = NavitGraphics.CallbackGeoCalc(1, NavitGraphics.Global_dpi_factor
                                    * (NG__map_main.view.getWidth() / 2 + NavitGraphics.mCanvasWidth_overspill),
                                    NavitGraphics.Global_dpi_factor * (NG__map_main.view.getHeight() / 2
                                            + NavitGraphics.mCanvasHeight_overspill));
                        } else {
                            lat_lon = NavitGraphics.CallbackGeoCalc(1,
                                    NavitGraphics.Global_dpi_factor * NG__map_main.view.getWidth() / 2,
                                    NavitGraphics.Global_dpi_factor * NG__map_main.view.getHeight() / 2);
                        }
                        String tmp[] = lat_lon.split(":", 2);
                        //System.out.println("tmp=" + lat_lon);
                        lat = Float.parseFloat(tmp[0]);
                        lon = Float.parseFloat(tmp[1]);
                        //System.out.println("ret=" + lat_lon + " lat=" + lat + " lon=" + lon);
                        Location l = null;
                        l = new Location("ZANavi Demo 001");
                        l.setLatitude(lat);
                        l.setLongitude(lon);
                        l.setBearing(0.0f);
                        l.setSpeed(0);
                        l.setAccuracy(4.0f); // accuracy 4 meters
                        // NavitVehicle.update_compass_heading(0.0f);
                        NavitVehicle.set_mock_location__fast(l);
                    } catch (Exception e) {
                    }

                    Message msg = new Message();
                    Bundle b = new Bundle();
                    b.putInt("Callback", 52);
                    b.putString("s", "45"); // speed in km/h of Demo-Vehicle
                    // b.putString("s", "20");

                    msg.setData(b);
                    NavitGraphics.callback_handler.sendMessage(msg);
                } catch (Exception e) {
                }
            }
        };
        demo_v_001.start();

        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 51);

        if (Navit.GFX_OVERSPILL) {
            b.putInt("x", (int) (NavitGraphics.Global_dpi_factor
                    * ((Navit.NG__map_main.view.getWidth() / 2) + NavitGraphics.mCanvasWidth_overspill)));
            b.putInt("y", (int) (NavitGraphics.Global_dpi_factor
                    * ((Navit.NG__map_main.view.getHeight() / 2) + NavitGraphics.mCanvasHeight_overspill)));
        } else {
            b.putInt("x", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getWidth() / 2));
            b.putInt("y", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getHeight() / 2));
        }
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);

        break;
    case 602:
        // DEBUG: toggle textview with spoken and translated string (to help with translation)
        try {
            if (NavitGraphics.NavitMsgTv2_.getVisibility() == View.VISIBLE) {
                NavitGraphics.NavitMsgTv2_.setVisibility(View.GONE);
                NavitGraphics.NavitMsgTv2_.setEnabled(false);
                NavitGraphics.NavitMsgTv2sc_.setVisibility(View.GONE);
                NavitGraphics.NavitMsgTv2sc_.setEnabled(false);
            } else {
                NavitGraphics.NavitMsgTv2sc_.setVisibility(View.VISIBLE);
                NavitGraphics.NavitMsgTv2sc_.setEnabled(true);
                NavitGraphics.NavitMsgTv2_.setVisibility(View.VISIBLE);
                NavitGraphics.NavitMsgTv2_.setEnabled(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    case 603:
        // DEBUG: show all possible navigation commands (also translated)
        NavitGraphics.generate_all_speech_commands();
        break;
    case 604:
        // DEBUG: activate FAST driving demo vehicle and set position to screen center

        Navit.DemoVehicle = true;

        msg = new Message();

        b = new Bundle();
        b.putInt("Callback", 52);
        b.putString("s", "800"); // speed in ~km/h of Demo-Vehicle
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);

        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 51);
        if (Navit.GFX_OVERSPILL) {
            b.putInt("x", (int) (NavitGraphics.Global_dpi_factor
                    * ((Navit.NG__map_main.view.getWidth() / 2) + NavitGraphics.mCanvasWidth_overspill)));
            b.putInt("y", (int) (NavitGraphics.Global_dpi_factor
                    * ((Navit.NG__map_main.view.getHeight() / 2) + NavitGraphics.mCanvasHeight_overspill)));
        } else {
            b.putInt("x", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getWidth() / 2));
            b.putInt("y", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getHeight() / 2));
        }
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);

        try {
            float lat = 0;
            float lon = 0;

            lat = 0;
            lon = 0;
            String lat_lon = "";
            if (Navit.GFX_OVERSPILL) {
                lat_lon = NavitGraphics.CallbackGeoCalc(1,
                        NavitGraphics.Global_dpi_factor
                                * (NG__map_main.view.getWidth() / 2 + NavitGraphics.mCanvasWidth_overspill),
                        NavitGraphics.Global_dpi_factor
                                * (NG__map_main.view.getHeight() / 2 + NavitGraphics.mCanvasHeight_overspill));
            } else {
                lat_lon = NavitGraphics.CallbackGeoCalc(1,
                        NavitGraphics.Global_dpi_factor * NG__map_main.view.getWidth() / 2,
                        NavitGraphics.Global_dpi_factor * NG__map_main.view.getHeight() / 2);
            }

            String tmp[] = lat_lon.split(":", 2);
            //System.out.println("tmp=" + lat_lon);
            lat = Float.parseFloat(tmp[0]);
            lon = Float.parseFloat(tmp[1]);
            //System.out.println("ret=" + lat_lon + " lat=" + lat + " lon=" + lon);
            Location l = null;
            l = new Location("ZANavi Demo 001");
            l.setLatitude(lat);
            l.setLongitude(lon);
            l.setBearing(0.0f);
            l.setSpeed(0);
            l.setAccuracy(4.0f); // accuracy 4 meters
            // NavitVehicle.update_compass_heading(0.0f);
            NavitVehicle.set_mock_location__fast(l);
        } catch (Exception e) {
        }

        break;
    case 605:
        // DEBUG: toggle Routgraph on/off
        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 71);
        Navit.Routgraph_enabled = 1 - Navit.Routgraph_enabled;
        b.putString("s", "" + Navit.Routgraph_enabled);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
        break;
    case 606:
        // DEBUG: spill contents of index file(s)
        msg = new Message();
        b = new Bundle();
        b.putInt("Callback", 83);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
        break;
    case 607:
        export_map_points_to_sdcard();
        break;
    case 608:
        import_map_points_from_sdcard();
        break;
    case 609:
        // run yaml tests
        new Thread() {
            public void run() {
                try {
                    ZANaviDebugReceiver.DR_run_all_yaml_tests();
                } catch (Exception e) {
                }
            }
        }.start();
        break;
    case 99:
        try {
            if (wl_navigating != null) {
                //if (wl_navigating.isHeld())
                //{
                wl_navigating.release();
                Log.e("Navit", "WakeLock Nav: release 1");
                //}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // exit
        this.onPause();
        this.onStop();
        this.exit();
        //msg = new Message();
        //b = new Bundle();
        //b.putInt("Callback", 5);
        //b.putString("cmd", "quit();");
        //msg.setData(b);
        //N_NavitGraphics.callback_handler.sendMessage(msg);
        break;
    }
    return true;
}