Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:carnero.cgeo.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*  ww w.j a  v  a 2  s .  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.panet.imeta.repository.Repository.java

public synchronized void exportAllObjects(ProgressMonitorListener monitor, String xmlFilename,
        RepositoryDirectory root, String exportType) throws KettleException {
    OutputStream os = null;//  w w w  .  j a  v  a2 s .  c  o m
    OutputStreamWriter writer = null;
    try {
        os = new BufferedOutputStream(KettleVFS.getOutputStream(xmlFilename, false));
        writer = new OutputStreamWriter(os);

        if (monitor != null)
            monitor.beginTask("Exporting the repository to XML...", 3);

        root = ((null == root) ? getDirectoryTree() : root);

        writer.write(XMLHandler.getXMLHeader());
        writer.write("<repository>" + Const.CR + Const.CR);

        if (exportType.equals("all") || exportType.equals("trans")) {
            // Dump the transformations...
            writer.write("<transformations>" + Const.CR);
            exportTransformations(monitor, root, writer);
            writer.write("</transformations>" + Const.CR);
        }

        if (exportType.equals("all") || exportType.equals("jobs")) {
            // Now dump the jobs...
            writer.write("<jobs>" + Const.CR);
            exportJobs(monitor, root, writer);
            writer.write("</jobs>" + Const.CR);
        }

        writer.write("</repository>" + Const.CR + Const.CR);

        if (monitor != null)
            monitor.worked(1);

        if (monitor != null)
            monitor.subTask("Saving XML to file [" + xmlFilename + "]");

        if (monitor != null)
            monitor.worked(1);

    } catch (IOException e) {
        System.out.println("Couldn't create file [" + xmlFilename + "]");
    } finally {
        try {
            if (writer != null)
                writer.close();
            if (os != null)
                os.close();
        } catch (Exception e) {
            System.out.println("Exception closing XML file writer to [" + xmlFilename + "]");
        }
    }

    if (monitor != null)
        monitor.done();
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

public void getRawTextFromUrlIfNeeded(DocumentPojo doc, SourceRssConfigPojo feedConfig) throws IOException {
    if (null != doc.getFullText()) { // Nothing to do
        return;//w  w w .  ja v  a 2 s.  co m
    }
    Scanner s = null;
    OutputStreamWriter wr = null;
    try {
        URL url = new URL(doc.getUrl());
        URLConnection urlConnect = null;
        String postContent = null;
        if (null != feedConfig) {
            urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
            if (null != feedConfig.getUserAgent()) {
                urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
            } // TESTED (by hand)
            if (null != feedConfig.getHttpFields()) {
                for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                    if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                        postContent = httpFieldPair.getValue();
                        urlConnect.setDoInput(true);
                        urlConnect.setDoOutput(true);
                    } else {
                        urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                    }
                }
            } //TESTED (by hand)
        } else {
            urlConnect = url.openConnection();
        }
        InputStream urlStream = null;
        try {
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } catch (SecurityException se) {
            throw se;
        } catch (Exception e) { // Try one more time, this time exception out all the way
            securityManager.setSecureFlag(false); // (some file stuff - so need to re-enable)
            if (null != feedConfig) {
                urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
                if (null != feedConfig.getUserAgent()) {
                    urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
                } // TESTED
                if (null != feedConfig.getHttpFields()) {
                    for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                        if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                            urlConnect.setDoInput(true); // (need to do this again)
                            urlConnect.setDoOutput(true);
                        } else {
                            urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                        }
                    }
                } //TESTED
            } else {
                urlConnect = url.openConnection();
            }
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } finally {
            securityManager.setSecureFlag(false); // (turn security check for local URL/file access off)
        }
        // Grab any interesting header fields
        Map<String, List<String>> headers = urlConnect.getHeaderFields();
        BasicDBObject metadataHeaderObj = null;
        for (Map.Entry<String, List<String>> it : headers.entrySet()) {
            if (null != it.getKey()) {
                if (it.getKey().startsWith("X-") || it.getKey().startsWith("Set-")
                        || it.getKey().startsWith("Location")) {
                    if (null == metadataHeaderObj) {
                        metadataHeaderObj = new BasicDBObject();
                    }
                    metadataHeaderObj.put(it.getKey(), it.getValue());
                }
            }
        } //TESTED
          // Grab the response code
        try {
            HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
            int responseCode = httpUrlConnect.getResponseCode();
            if (200 != responseCode) {
                if (null == metadataHeaderObj) {
                    metadataHeaderObj = new BasicDBObject();
                }
                metadataHeaderObj.put("responseCode", String.valueOf(responseCode));
            }
        } //TESTED
        catch (Exception e) {
        } // interesting, not an HTTP connect ... shrug and carry on
        if (null != metadataHeaderObj) {
            doc.addToMetadata("__FEED_METADATA__", metadataHeaderObj);
        } //TESTED
        s = new Scanner(urlStream, "UTF-8");
        doc.setFullText(s.useDelimiter("\\A").next());
    } catch (MalformedURLException me) { // This one is worthy of a more useful error message
        throw new MalformedURLException(me.getMessage()
                + ": Likely because the document has no full text (eg JSON) and you are calling a contentMetadata block without setting flags:'m' or 'd'");
    } finally { //(release resources)
        if (null != s) {
            s.close();
        }
        if (null != wr) {
            wr.close();
        }
    }

}

From source file:datafu.hourglass.jobs.StagedOutputJob.java

/**
 * Writes Hadoop counters and other task statistics to a file in the file system.
 * /* w w  w .  jav  a2s .  c  o  m*/
 * @param fs
 * @throws IOException
 */
private void writeCounters(final FileSystem fs) throws IOException {
    final Path actualOutputPath = FileOutputFormat.getOutputPath(this);

    SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    String suffix = timestampFormat.format(new Date());

    if (_countersParentPath != null) {
        if (!fs.exists(_countersParentPath)) {
            _log.info("Creating counter parent path " + _countersParentPath);
            fs.mkdirs(_countersParentPath, FsPermission.valueOf("-rwxrwxr-x"));
        }
        // make the name as unique as possible in this case because this may be a directory
        // where other counter files will be dropped
        _countersPath = new Path(_countersParentPath, ".counters." + suffix);
    } else {
        _countersPath = new Path(actualOutputPath, ".counters." + suffix);
    }

    _log.info(String.format("Writing counters to %s", _countersPath));
    FSDataOutputStream counterStream = fs.create(_countersPath);
    BufferedOutputStream buffer = new BufferedOutputStream(counterStream, 256 * 1024);
    OutputStreamWriter writer = new OutputStreamWriter(buffer);
    for (String groupName : getCounters().getGroupNames()) {
        for (Counter counter : getCounters().getGroup(groupName)) {
            writeAndLog(writer, String.format("%s=%d", counter.getName(), counter.getValue()));
        }
    }

    JobID jobID = this.getJobID();

    org.apache.hadoop.mapred.JobID oldJobId = new org.apache.hadoop.mapred.JobID(jobID.getJtIdentifier(),
            jobID.getId());

    long minStart = Long.MAX_VALUE;
    long maxFinish = 0;
    long setupStart = Long.MAX_VALUE;
    long cleanupFinish = 0;
    DescriptiveStatistics mapStats = new DescriptiveStatistics();
    DescriptiveStatistics reduceStats = new DescriptiveStatistics();
    boolean success = true;

    JobClient jobClient = new JobClient(this.conf);

    Map<String, String> taskIdToType = new HashMap<String, String>();

    TaskReport[] setupReports = jobClient.getSetupTaskReports(oldJobId);
    if (setupReports.length > 0) {
        _log.info("Processing setup reports");
        for (TaskReport report : jobClient.getSetupTaskReports(oldJobId)) {
            taskIdToType.put(report.getTaskID().toString(), "SETUP");
            if (report.getStartTime() == 0) {
                _log.warn("Skipping report with zero start time");
                continue;
            }
            setupStart = Math.min(setupStart, report.getStartTime());
        }
    } else {
        _log.error("No setup reports");
    }

    TaskReport[] mapReports = jobClient.getMapTaskReports(oldJobId);
    if (mapReports.length > 0) {
        _log.info("Processing map reports");
        for (TaskReport report : mapReports) {
            taskIdToType.put(report.getTaskID().toString(), "MAP");
            if (report.getFinishTime() == 0 || report.getStartTime() == 0) {
                _log.warn("Skipping report with zero start or finish time");
                continue;
            }
            minStart = Math.min(minStart, report.getStartTime());
            mapStats.addValue(report.getFinishTime() - report.getStartTime());
        }
    } else {
        _log.error("No map reports");
    }

    TaskReport[] reduceReports = jobClient.getReduceTaskReports(oldJobId);
    if (reduceReports.length > 0) {
        _log.info("Processing reduce reports");
        for (TaskReport report : reduceReports) {
            taskIdToType.put(report.getTaskID().toString(), "REDUCE");
            if (report.getFinishTime() == 0 || report.getStartTime() == 0) {
                _log.warn("Skipping report with zero start or finish time");
                continue;
            }
            maxFinish = Math.max(maxFinish, report.getFinishTime());
            reduceStats.addValue(report.getFinishTime() - report.getStartTime());
        }
    } else {
        _log.error("No reduce reports");
    }

    TaskReport[] cleanupReports = jobClient.getCleanupTaskReports(oldJobId);
    if (cleanupReports.length > 0) {
        _log.info("Processing cleanup reports");
        for (TaskReport report : cleanupReports) {
            taskIdToType.put(report.getTaskID().toString(), "CLEANUP");
            if (report.getFinishTime() == 0) {
                _log.warn("Skipping report with finish time of zero");
                continue;
            }
            cleanupFinish = Math.max(cleanupFinish, report.getFinishTime());
        }
    } else {
        _log.error("No cleanup reports");
    }

    if (minStart == Long.MAX_VALUE) {
        _log.error("Could not determine map-reduce start time");
        success = false;
    }
    if (maxFinish == 0) {
        _log.error("Could not determine map-reduce finish time");
        success = false;
    }

    if (setupStart == Long.MAX_VALUE) {
        _log.error("Could not determine setup start time");
        success = false;
    }
    if (cleanupFinish == 0) {
        _log.error("Could not determine cleanup finish time");
        success = false;
    }

    // Collect statistics on successful/failed/killed task attempts, categorized by setup/map/reduce/cleanup.
    // Unfortunately the job client doesn't have an easier way to get these statistics.
    Map<String, Integer> attemptStats = new HashMap<String, Integer>();
    _log.info("Processing task attempts");
    for (TaskCompletionEvent event : getTaskCompletionEvents(jobClient, oldJobId)) {
        String type = taskIdToType.get(event.getTaskAttemptId().getTaskID().toString());
        String status = event.getTaskStatus().toString();

        String key = String.format("%s_%s_ATTEMPTS", status, type);
        if (!attemptStats.containsKey(key)) {
            attemptStats.put(key, 0);
        }
        attemptStats.put(key, attemptStats.get(key) + 1);
    }

    if (success) {
        writeAndLog(writer, String.format("SETUP_START_TIME_MS=%d", setupStart));
        writeAndLog(writer, String.format("CLEANUP_FINISH_TIME_MS=%d", cleanupFinish));
        writeAndLog(writer, String.format("COMPLETE_WALL_CLOCK_TIME_MS=%d", cleanupFinish - setupStart));

        writeAndLog(writer, String.format("MAP_REDUCE_START_TIME_MS=%d", minStart));
        writeAndLog(writer, String.format("MAP_REDUCE_FINISH_TIME_MS=%d", maxFinish));
        writeAndLog(writer, String.format("MAP_REDUCE_WALL_CLOCK_TIME_MS=%d", maxFinish - minStart));

        writeAndLog(writer, String.format("MAP_TOTAL_TASKS=%d", (long) mapStats.getN()));
        writeAndLog(writer, String.format("MAP_MAX_TIME_MS=%d", (long) mapStats.getMax()));
        writeAndLog(writer, String.format("MAP_MIN_TIME_MS=%d", (long) mapStats.getMin()));
        writeAndLog(writer, String.format("MAP_AVG_TIME_MS=%d", (long) mapStats.getMean()));
        writeAndLog(writer, String.format("MAP_STD_TIME_MS=%d", (long) mapStats.getStandardDeviation()));
        writeAndLog(writer, String.format("MAP_SUM_TIME_MS=%d", (long) mapStats.getSum()));

        writeAndLog(writer, String.format("REDUCE_TOTAL_TASKS=%d", (long) reduceStats.getN()));
        writeAndLog(writer, String.format("REDUCE_MAX_TIME_MS=%d", (long) reduceStats.getMax()));
        writeAndLog(writer, String.format("REDUCE_MIN_TIME_MS=%d", (long) reduceStats.getMin()));
        writeAndLog(writer, String.format("REDUCE_AVG_TIME_MS=%d", (long) reduceStats.getMean()));
        writeAndLog(writer, String.format("REDUCE_STD_TIME_MS=%d", (long) reduceStats.getStandardDeviation()));
        writeAndLog(writer, String.format("REDUCE_SUM_TIME_MS=%d", (long) reduceStats.getSum()));

        writeAndLog(writer, String.format("MAP_REDUCE_SUM_TIME_MS=%d",
                (long) mapStats.getSum() + (long) reduceStats.getSum()));

        for (Map.Entry<String, Integer> attemptStat : attemptStats.entrySet()) {
            writeAndLog(writer, String.format("%s=%d", attemptStat.getKey(), attemptStat.getValue()));
        }
    }

    writer.close();
    buffer.close();
    counterStream.close();
}

From source file:ome.formats.OMEROMetadataStoreClient.java

/**
 * Creates a temporary file on disk containing all metadata in the
 * Bio-Formats metadata hash table for the current series.
 * @param suffix String that will be appended to the end of the temporary
 * file path./* www.j  a  v  a2 s  . c om*/
 * @return Temporary file created.
 */
private File createSeriesMetadataFile(String suffix) {
    Hashtable<?, ?> globalMetadata = reader.getGlobalMetadata();
    Hashtable<?, ?> seriesMetadata = reader.getSeriesMetadata();
    if (globalMetadata.size() == 0 && seriesMetadata.size() == 0) {
        return null;
    }
    FileOutputStream stream = null;
    OutputStreamWriter writer = null;
    try {
        File metadataFile = TempFileManager.createTempFile(ORIGINAL_METADATA_KEY, suffix);
        stream = new FileOutputStream(metadataFile);
        writer = new OutputStreamWriter(stream);
        metadataFile.deleteOnExit();
        writer.write("[GlobalMetadata]\n");
        for (Object key : globalMetadata.keySet()) {
            String s = key.toString() + "=" + globalMetadata.get(key).toString() + "\n";
            writer.write(s);
        }
        writer.write("[SeriesMetadata]\n");
        for (Object key : seriesMetadata.keySet()) {
            String s = key.toString() + "=" + seriesMetadata.get(key).toString() + "\n";
            writer.write(s);
        }
        return metadataFile;
    } catch (IOException e) {
        log.error("Unable to create series metadata file.", e);
        return null;
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            log.error("Unable to close writer or stream.", e);
        }
    }
}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @param fichShp/*from   w  w w . j  ava2 s .c  o  m*/
 * @throws FileNotFoundException Exception fichier non trouv
 * @throws IOException Exception d'entre sortie
 */
@SuppressWarnings("null")
private static void sauverBarre(String fichShp) throws FileNotFoundException, IOException {
    OutputStreamWriter oswFichierBarre = null;
    try {
        String strZones = "";
        for (int i = 0; i < iNombreZones; i++) {
            ZoneTelecommande zone = zones[i];
            strZones += "[area=>id:" + zone.getStrIdZone() + ";";
            strZones += "shape:" + zone.getStrTypeZone() + ";";
            strZones += "coords:" + zone.getStrCoordonneesZone() + "]\n";
        }
        File fileIndexHTML = new File(fichShp);
        if (!fileIndexHTML.exists()) {
            fileIndexHTML.createNewFile();
        }
        fileIndexHTML.setWritable(true);
        oswFichierBarre = new OutputStreamWriter(new FileOutputStream(fileIndexHTML), "UTF-8");
        try (BufferedWriter bwFichierBarre = new BufferedWriter(oswFichierBarre)) {
            bwFichierBarre.write(strZones);

        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            oswFichierBarre.close();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected boolean LoadDXF(String filename) {
    if (ChooseImageConversionOptions(true) == false)
        return false;

    // where to save temp output file?
    final String destinationFile = GetTempDestinationFile();
    final String srcFile = filename;

    TabToLog();/*from   w w w  .j  a va2 s  . c om*/

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        public boolean ok = false;

        @SuppressWarnings("unchecked")
        @Override
        public Void doInBackground() {
            Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n");

            Parser parser = ParserBuilder.createDefaultParser();

            double dxf_x2 = 0;
            double dxf_y2 = 0;
            OutputStreamWriter out = null;

            try {
                out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8");
                DrawingTool tool = machineConfiguration.GetCurrentTool();
                out.write(machineConfiguration.GetConfigLine() + ";\n");
                out.write(machineConfiguration.GetBobbinLine() + ";\n");
                out.write("G00 G90;\n");
                tool.WriteChangeTo(out);
                tool.WriteOff(out);

                parser.parse(srcFile, DXFParser.DEFAULT_ENCODING);
                DXFDocument doc = parser.getDocument();
                Bounds b = doc.getBounds();
                double width = b.getMaximumX() - b.getMinimumX();
                double height = b.getMaximumY() - b.getMinimumY();
                double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f;
                double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f;
                double sy = machineConfiguration.GetPaperHeight() * 10 / height;
                double sx = machineConfiguration.GetPaperWidth() * 10 / width;
                double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin;
                sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1);
                // count all entities in all layers
                Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator();
                int entity_total = 0;
                int entity_count = 0;
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();
                    Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n");
                    Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_iter.hasNext()) {
                        String entity_type = (String) entity_iter.next();
                        List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type);
                        Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type
                                + "</font>\n");
                        entity_total += entity_list.size();
                    }
                }
                // set the progress meter
                pm.setMinimum(0);
                pm.setMaximum(entity_total);

                // convert each entity
                layer_iter = doc.getDXFLayerIterator();
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();

                    Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_type_iter.hasNext()) {
                        String entity_type = (String) entity_type_iter.next();
                        List<DXFEntity> entity_list = layer.getDXFEntities(entity_type);

                        if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFLine entity = (DXFLine) entity_list.get(i);
                                Point start = entity.getStartPoint();
                                Point end = entity.getEndPoint();

                                double x = (start.getX() - cx) * sx;
                                double y = (start.getY() - cy) * sy;
                                double x2 = (end.getX() - cx) * sx;
                                double y2 = (end.getY() - cy) * sy;

                                // is it worth drawing this line?
                                double dx = x2 - x;
                                double dy = y2 - y;
                                if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) {
                                    continue;
                                }

                                dx = dxf_x2 - x;
                                dy = dxf_y2 - y;

                                if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                    if (tool.DrawIsOn()) {
                                        tool.WriteOff(out);
                                    }
                                    tool.WriteMoveTo(out, (float) x, (float) y);
                                }
                                if (tool.DrawIsOff()) {
                                    tool.WriteOn(out);
                                }
                                tool.WriteMoveTo(out, (float) x2, (float) y2);
                                dxf_x2 = x2;
                                dxf_y2 = y2;
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFSpline entity = (DXFSpline) entity_list.get(i);
                                entity.setLineWeight(30);
                                DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity);
                                boolean first = true;
                                for (int j = 0; j < polyLine.getVertexCount(); ++j) {
                                    DXFVertex v = polyLine.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < polyLine.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFPolyline entity = (DXFPolyline) entity_list.get(i);
                                boolean first = true;
                                for (int j = 0; j < entity.getVertexCount(); ++j) {
                                    DXFVertex v = entity.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < entity.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        }
                    }
                }

                // entities finished.  Close up file.
                tool.WriteOff(out);
                tool.WriteMoveTo(out, 0, 0);

                ok = true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            if (ok) {
                LoadGCode(destinationFile);
                TabToDraw();
            }
            Halt();
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

From source file:Admin_Thesaurus.ImportData.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (SystemIsLockedForAdministrativeJobs(request, response)) {
        return;//from w  ww. j a  v  a2s  .  c o  m
    }
    String basePath = request.getSession().getServletContext().getRealPath("");

    // ---------------------- LOCK SYSTEM ----------------------
    ConfigDBadmin config = new ConfigDBadmin(basePath);
    DBAdminUtilities dbAdminUtils = new DBAdminUtilities();
    dbAdminUtils.LockSystemForAdministrativeJobs(config);

    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession();
    ServletContext context = session.getServletContext();
    SessionWrapperClass sessionInstance = new SessionWrapperClass();
    init(request, response, sessionInstance);

    PrintWriter out = response.getWriter();

    OutputStreamWriter logFileWriter = null;

    try {

        // check for previous logon but because of ajax usage respond with Session Invalidate str
        UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser");

        if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) {
            out.println("Session Invalidate");
            response.sendRedirect("Index");
            return;
        }

        //tools
        Utilities u = new Utilities();
        DBGeneral dbGen = new DBGeneral();
        DBImportData dbImport = new DBImportData();
        DBMergeThesauri dbMerge = new DBMergeThesauri();
        StringObject translatedMsgObj = new StringObject("");

        Vector<String> thesauriNames = new Vector<String>();

        CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config);
        StringObject resultObj = new StringObject("");

        String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus;

        //Parameters
        String xmlFilePath = request.getParameter("importXMLfilename");

        //String importSchemaName    = request.getParameter("schematype");
        String importSchemaName = ConstantParameters.xmlschematype_THEMAS;
        String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME");
        String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport
        String importHierarchyName = u
                .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName"));
        String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml");
        String language = context.getInitParameter("LocaleLanguage");
        String country = context.getInitParameter("LocaleCountry");
        String WebAppUsersFileName = request.getSession().getServletContext()
                .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath);

        String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName);
        String logFileNamePath = logPath;
        String webAppSaveResults_Folder = Parameters.Save_Results_Folder;
        String pathToSaveScriptingAndLocale = context
                .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml");
        Locale targetLocale = new Locale(language, country);

        if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null))
                || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) {
            UpDownFiles fup = new UpDownFiles();
            String[] formData = new String[10];
            FileItem[] dom = fup.prepareToUpBinary(request, formData);
            //Hashtable initParams = UpDownFiles.uploadParams;

            if (dom[0] != null) {

                String filename = xmlFilePath;
                ///String caption = (String) initParams.get("caption");

                filename = filename.substring(filename.lastIndexOf(File.separator) + 1);

                String fileType = filename.substring(filename.lastIndexOf(".") + 1);
                String userFileName = filename.substring(0, filename.lastIndexOf("."));

                filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType;

                String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename;
                xmlFilePath = fullPath;
                if (fup.writeBinary(dom[0], fullPath)) {
                    //mode = 1;
                } else {
                    //mode = -1;
                }
            } else {
                //mode = -1;
            }
        }

        QClass Q = new QClass();
        TMSAPIClass TA = new TMSAPIClass();
        IntegerObject sis_session = new IntegerObject();
        IntegerObject tms_session = new IntegerObject();

        //open connection and start transaction
        if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null,
                true) == QClass.APIFail) {
            Utils.StaticClass
                    .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
            return;
        }

        dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session);

        if (importMethodChoice.equals("thesaurusImport")) {

            //Format Name Of import Thesaurus
            importThesaurusName = importThesaurusName.trim();
            importThesaurusName = importThesaurusName.replaceAll(" ", "_");
            importThesaurusName = importThesaurusName.toUpperCase();

            if (thesauriNames.contains(importThesaurusName)) {

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure",
                        new String[] { importThesaurusName }));
                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus.");

                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                xml.append(getXMLMiddle(thesauriNames,
                        u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null)
                                + resultObj.getValue(),
                        importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            importThesaurusName = SessionUserInfo.selectedThesaurus;
            if (thesauriNames.contains(importThesaurusName) == false) {

                //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml");
                //StringObject resultMessageObj = new StringObject();
                StringObject resultMessageObj_2 = new StringObject();
                //Vector<String> errorArgs = new Vector<String>();

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist",
                        new String[] { importThesaurusName }));

                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists.");
                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                resultMessageObj_2
                        .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null));
                xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(),
                        importMethodChoice));
                //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        }

        //end query and close connection
        Q.free_all_sets();
        Q.TEST_end_query();
        dbGen.CloseDBConnection(Q, null, sis_session, null, false);
        Utils.StaticClass.closeDb();

        StringObject DBbackupFileNameCreated = new StringObject("");

        long startTime = Utilities.startTimer();
        String time = Utilities.GetNow();
        String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time;
        logFileNamePath += "/" + Filename + ".xml";

        try {
            OutputStream fout = new FileOutputStream(logFileNamePath);
            OutputStream bout = new BufferedOutputStream(fout);
            logFileWriter = new OutputStreamWriter(bout, "UTF-8");
            logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n"

            //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n");
            logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\""
                    + Parameters.PrimaryLang.toLowerCase() + "\">\r\n");
            logFileWriter.append("<title>"
                    + u.translateFromMessagesXML("root/ImportData/ReportTitle",
                            new String[] { importThesaurusName, time })
                    + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale
                    + "</pathToSaveScriptingAndLocale>\r\n");
            //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n");
            Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time
                    + " LogFile for data import in thesaurus: " + importThesaurusName + ".");

        } catch (Exception exc) {
            Utils.StaticClass.webAppSystemOutPrintln(
                    Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage());
            Utils.StaticClass.handleException(exc);
        }

        if (importMethodChoice.equals("thesaurusImport")) {

            if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            /*
             //open connection and start Transaction
             if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail)
             {
             Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
             return;
             }
             */
            if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }

        }

        commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName,
                out, Filename.concat(".html"));

        //ReportSuccessMessage            
        logFileWriter
                .append("\r\n<creationInfo>"
                        + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage",
                                new String[] { importThesaurusName, xmlFilePath,
                                        ((Utilities.stopTimer(startTime)) / 60) + "" })
                        + "</creationInfo>\r\n");

        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }

        //Now XSL should be found and java xsl transformation should be performed
        String XSL = context.getRealPath("/" + webAppSaveResults_Folder)
                + "/ImportCopyMergeThesaurus_Report.xsl";

        u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html"));

    } catch (Exception e) {

        Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet "
                + getServletName() + ". Message:" + e.getMessage());
        Utils.StaticClass.handleException(e);
        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }
    } finally {
        out.flush();
        out.close();
        sessionInstance.writeBackToSession(session);
    }
}

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 ava2s  . c  om
        // 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;
}