Example usage for java.io File setWritable

List of usage examples for java.io File setWritable

Introduction

In this page you can find the example usage for java.io File setWritable.

Prototype

public boolean setWritable(boolean writable) 

Source Link

Document

A convenience method to set the owner's write permission for this abstract pathname.

Usage

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductTransfer.java

private void upload(String url, final String username, final String password, final File dest,
        final boolean compute_checksum) {
    String remote_base_dir;/*from  w ww . jav  a  2s  . c  o  m*/
    try {
        remote_base_dir = (new URL(url)).getPath();
    } catch (MalformedURLException e1) {
        logger.error("Problem during upload", e1);
        return;
    }

    final String remote_base = remote_base_dir;

    Scanner scanner = scannerFactory.getScanner(url, username, password, null);
    // Get all files supported
    scanner.setUserPattern(".*");
    scanner.setForceNavigate(true);

    scanner.getScanList().addListener(new Listener<URLExt>() {
        @Override
        public void addedElement(Event<URLExt> e) {
            URLExt element = e.getElement();
            String remote_path = element.getUrl().getPath();
            String local_filename = ScannerFactory.getFileFromPath(remote_path);

            String local_path_dir = "";

            if (!remote_base.equals(remote_path))
                local_path_dir = remote_path.replaceFirst(ScannerFactory.getParentPath(remote_base), "");
            else
                local_path_dir = local_filename;

            File local_path = new File(dest, local_path_dir);

            if (!local_path.getParentFile().exists()) {
                logger.info("Creating directory \"" + local_path.getParentFile().getPath() + "\".");
                local_path.getParentFile().mkdirs();
                local_path.getParentFile().setWritable(true);
            }

            BufferedInputStream bis = null;
            InputStream is = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            int retry = 3;
            boolean source_remove = cfgManager.getFileScannersCronConfiguration().isSourceRemove();

            if (!element.isDirectory()) {
                DrbNode node = DrbFactory.openURI(element.getUrl().toExternalForm());
                long start = System.currentTimeMillis();
                do {
                    try {
                        logger.info(
                                "Transfering remote file \"" + remote_path + "\" into \"" + local_path + "\".");

                        if ((node instanceof DrbNodeSpi) && (((DrbNodeSpi) node).hasImpl(File.class))) {
                            File source = (File) ((DrbNodeSpi) node).getImpl(File.class);
                            {
                                if (source_remove)
                                    moveFile(source, local_path, compute_checksum);
                                else
                                    copyFile(source, local_path, compute_checksum);
                            }
                        } else
                        // Case of Use Transfer class to run
                        if ((node instanceof DrbNodeSpi) && (((DrbNodeSpi) node).hasImpl(Transfer.class))) {
                            fos = new FileOutputStream(local_path);
                            bos = new BufferedOutputStream(fos);

                            Transfer t = (Transfer) ((DrbNodeSpi) node).getImpl(Transfer.class);
                            t.copy(bos);
                            try {
                                if (cfgManager.getFileScannersCronConfiguration().isSourceRemove())
                                    t.remove();
                            } catch (IOException ioe) {
                                logger.error("Unable to remove " + local_path.getPath(), ioe);
                            }
                        } else {
                            if ((node instanceof DrbNodeSpi)
                                    && (((DrbNodeSpi) node).hasImpl(InputStream.class))) {
                                is = (InputStream) ((DrbNodeSpi) node).getImpl(InputStream.class);
                            } else
                                is = element.getUrl().openStream();

                            bis = new BufferedInputStream(is);
                            fos = new FileOutputStream(local_path);
                            bos = new BufferedOutputStream(fos);

                            IOUtils.copyLarge(bis, bos);
                        }
                        // Prepare message
                        long stop = System.currentTimeMillis();
                        long delay_ms = stop - start;
                        long size = local_path.length();
                        String message = " in " + delay_ms + "ms";
                        if ((size > 0) && (delay_ms > 0))
                            message += " at " + ((size / (1024 * 1024)) / ((float) delay_ms / 1000.0)) + "MB/s";

                        logger.info("Copy of " + node.getName() + " completed" + message);
                        retry = 0;
                    } catch (Exception excp) {
                        if ((retry - 1) <= 0) {
                            logger.error("Cannot copy " + node.getName() + " aborted.");
                            throw new RuntimeException("Transfer Aborted.", excp);
                        } else {
                            logger.warn("Cannot copy " + node.getName() + " retrying... (" + excp.getMessage()
                                    + ")");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e1) {
                                // Do nothing.
                            }
                        }
                    } finally {
                        try {
                            if (bos != null)
                                bos.close();
                            if (fos != null)
                                fos.close();
                            if (bis != null)
                                bis.close();
                            if (is != null)
                                is.close();
                        } catch (IOException exp) {
                            logger.error("Error while closing copy streams.");
                        }
                    }
                } while (--retry > 0);
            } else {
                if (!local_path.exists()) {
                    logger.info("Creating directory \"" + local_path.getPath() + "\".");
                    local_path.mkdirs();
                    local_path.setWritable(true);
                }
                return;
            }
        }

        @Override
        public void removedElement(Event<URLExt> e) {
        }
    });
    try {
        scanner.scan();
        // Remove root product if required.
        if (cfgManager.getFileScannersCronConfiguration().isSourceRemove()) {
            try {
                DrbNode node = DrbFactory.openURI(url);
                if (node instanceof DrbNodeSpi) {
                    DrbNodeSpi spi = (DrbNodeSpi) node;
                    if (spi.hasImpl(File.class)) {
                        FileUtils.deleteQuietly((File) spi.getImpl(File.class));
                    } else if (spi.hasImpl(Transfer.class)) {
                        ((Transfer) spi.getImpl(Transfer.class)).remove();
                    } else {
                        logger.error("Root product note removed (TBC)");
                    }
                }
            } catch (Exception e) {
                logger.warn("Cannot remove input source (" + e.getMessage() + ").");
            }
        }
    } catch (Exception e) {
        if (e instanceof InterruptedException)
            logger.error("Process interrupted by user");
        else
            logger.error("Error while uploading product", e);

        // If something get wrong during upload: do not keep any residual 
        // data locally.
        logger.warn("Remove residual uploaded data :" + dest.getPath());
        FileUtils.deleteQuietly(dest);
        throw new UnsupportedOperationException("Error during scan.", e);
    }
}

From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java

private void upload(String url, final String username, final String password, final File dest) {
    String remote_base_dir;/*from  w  w  w .ja va2  s.com*/
    try {
        remote_base_dir = (new URL(url)).getPath();
    } catch (MalformedURLException e1) {
        LOGGER.error("Problem during upload", e1);
        return;
    }

    final String remoteBaseDir = remote_base_dir;

    Scanner scanner = scannerFactory.getScanner(url, username, password, null);
    // Get all files supported
    scanner.setUserPattern(".*");
    scanner.setForceNavigate(true);

    scanner.getScanList().addListener(new Listener<URLExt>() {
        @Override
        public void addedElement(Event<URLExt> e) {
            URLExt element = e.getElement();
            String remote_path = element.getUrl().getPath();

            String remoteBase = remoteBaseDir;
            if (remoteBase.endsWith("/")) {
                remoteBase = remoteBase.substring(0, remoteBase.length() - 1);
            }
            String local_path_dir = remote_path
                    .replaceFirst(remoteBase.substring(0, remoteBase.lastIndexOf("/") + 1), "");

            File local_path = new File(dest, local_path_dir);

            if (!local_path.getParentFile().exists()) {
                LOGGER.info("Creating directory \"" + local_path.getParentFile().getPath() + "\".");
                local_path.getParentFile().mkdirs();
                local_path.getParentFile().setWritable(true);
            }

            BufferedInputStream bis = null;
            InputStream is = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            int retry = 3;
            boolean source_remove = cfgManager.getFileScannersCronConfiguration().isSourceRemove();

            if (!element.isDirectory()) {
                DrbNode node = DrbFactory.openURI(element.getUrl().toExternalForm());
                long start = System.currentTimeMillis();
                do {
                    try {
                        LOGGER.info(
                                "Transfering remote file \"" + remote_path + "\" into \"" + local_path + "\".");

                        if ((node instanceof DrbNodeSpi) && (((DrbNodeSpi) node).hasImpl(File.class))) {
                            File source = (File) ((DrbNodeSpi) node).getImpl(File.class);
                            {
                                if (source_remove)
                                    moveFile(source, local_path);
                                else
                                    copyFile(source, local_path);
                            }
                        } else
                        // Case of Use Transfer class to run
                        if ((node instanceof DrbNodeSpi) && (((DrbNodeSpi) node).hasImpl(Transfer.class))) {
                            fos = new FileOutputStream(local_path);
                            bos = new BufferedOutputStream(fos);

                            Transfer t = (Transfer) ((DrbNodeSpi) node).getImpl(Transfer.class);
                            t.copy(bos);
                            try {
                                if (cfgManager.getFileScannersCronConfiguration().isSourceRemove())
                                    t.remove();
                            } catch (IOException ioe) {
                                LOGGER.error("Unable to remove " + local_path.getPath(), ioe);
                            }
                        } else {
                            if ((node instanceof DrbNodeSpi)
                                    && (((DrbNodeSpi) node).hasImpl(InputStream.class))) {
                                is = (InputStream) ((DrbNodeSpi) node).getImpl(InputStream.class);
                            } else
                                is = element.getUrl().openStream();

                            bis = new BufferedInputStream(is);
                            fos = new FileOutputStream(local_path);
                            bos = new BufferedOutputStream(fos);

                            IOUtils.copyLarge(bis, bos);
                        }
                        // Prepare message
                        long stop = System.currentTimeMillis();
                        long delay_ms = stop - start;
                        long size = local_path.length();
                        String message = " in " + delay_ms + "ms";
                        if ((size > 0) && (delay_ms > 0))
                            message += " at " + ((size / (1024 * 1024)) / ((float) delay_ms / 1000.0)) + "MB/s";

                        LOGGER.info("Copy of " + node.getName() + " completed" + message);
                        retry = 0;
                    } catch (Exception excp) {
                        if ((retry - 1) <= 0) {
                            LOGGER.error("Cannot copy " + node.getName() + " aborted.");
                            throw new RuntimeException("Transfer Aborted.", excp);
                        } else {
                            LOGGER.warn("Cannot copy " + node.getName() + " retrying... (" + excp.getMessage()
                                    + ")");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e1) {
                                // Do nothing.
                            }
                        }
                    } finally {
                        try {
                            if (bos != null)
                                bos.close();
                            if (fos != null)
                                fos.close();
                            if (bis != null)
                                bis.close();
                            if (is != null)
                                is.close();
                        } catch (IOException exp) {
                            LOGGER.error("Error while closing copy streams.");
                        }
                    }
                } while (--retry > 0);
            } else {
                if (!local_path.exists()) {
                    LOGGER.info("Creating directory \"" + local_path.getPath() + "\".");
                    local_path.mkdirs();
                    local_path.setWritable(true);
                }
                return;
            }
        }

        @Override
        public void removedElement(Event<URLExt> e) {
        }
    });
    try {
        scanner.scan();
        // Remove root product if required.
        if (cfgManager.getFileScannersCronConfiguration().isSourceRemove()) {
            try {
                DrbNode node = DrbFactory.openURI(url);
                if (node instanceof DrbNodeSpi) {
                    DrbNodeSpi spi = (DrbNodeSpi) node;
                    if (spi.hasImpl(File.class)) {
                        FileUtils.deleteQuietly((File) spi.getImpl(File.class));
                    } else if (spi.hasImpl(Transfer.class)) {
                        ((Transfer) spi.getImpl(Transfer.class)).remove();
                    } else {
                        LOGGER.error("Root product note removed (TBC)");
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("Cannot remove input source (" + e.getMessage() + ").");
            }
        }
    } catch (Exception e) {
        if (e instanceof InterruptedException)
            LOGGER.error("Process interrupted by user");
        else
            LOGGER.error("Error while uploading product", e);

        // If something get wrong during upload: do not keep any residual
        // data locally.
        LOGGER.warn("Remove residual uploaded data :" + dest.getPath());
        FileUtils.deleteQuietly(dest);
        throw new UnsupportedOperationException("Error during scan.", e);
    }
}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 *//*from  w  w w . j  a v  a2 s  .  c  om*/
private void lisFichierConfig() throws IOException {
    //        MenuItem menuItem=new MenuItem("test");
    //        menuItem.setOnAction(null);
    //        derniersProjets.getItems().addAll(menuItem);
    //        derniersProjets.setDisable(false);
    File fichConfig = new File(repertConfig.getAbsolutePath() + File.separator + "panovisu.cfg");
    if (fichConfig.exists()) {
        FileReader fr;
        try {
            fr = new FileReader(fichConfig);
            String texte;
            try (BufferedReader br = new BufferedReader(fr)) {
                texte = "";
                String ligneTexte;
                String langue = "fr";
                String pays = "FR";
                String repert = repertAppli;
                while ((texte = br.readLine()) != null) {
                    String tpe = texte.split("=")[0];
                    String valeur = texte.split("=")[1];
                    switch (tpe) {
                    case "langue":
                        langue = valeur;
                        break;
                    case "pays":
                        pays = valeur;
                        break;
                    case "repert":
                        repert = valeur;
                        break;
                    case "style":
                        styleCSS = valeur;
                        break;

                    }

                }
                locale = new Locale(langue, pays);
                File repert1 = new File(repert);
                if (repert1.exists()) {
                    repertoireProjet = repert;
                    currentDir = repert;
                    repertSauveChoisi = true;
                } else {
                    repertoireProjet = repertAppli;
                    currentDir = repertAppli;
                }
                setUserAgentStylesheet("file:css/" + styleCSS + ".css");
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        fichConfig.createNewFile();
        locale = new Locale("fr", "FR");
        setUserAgentStylesheet("file:css/clair.css");
        repertoireProjet = repertAppli;
        String contenuFichier = "langue=" + locale.toString().split("_")[0] + "\n";
        contenuFichier += "pays=" + locale.toString().split("_")[1] + "\n";
        contenuFichier += "repert=" + repertoireProjet + "\n";
        contenuFichier += "style=clair\n";
        fichConfig.setWritable(true);
        FileWriter fw = null;
        try {
            fw = new FileWriter(fichConfig);
        } catch (IOException ex) {
            Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
        }
        BufferedWriter bw = new BufferedWriter(fw);
        try {
            bw.write(contenuFichier);
        } catch (IOException ex) {
            Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            bw.close();
        } catch (IOException ex) {
            Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @param fichShp//from w  w w .  java  2  s  .  com
 * @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:editeurpanovisu.EditeurPanovisu.java

private static void creeDiaporamaHTML(Diaporama diapo, int iNumero) throws IOException {
    String strDiapoRepert = getStrRepertTemp() + "/diaporama";
    File fileDiapoRepert = new File(strDiapoRepert);
    if (!fileDiapoRepert.exists()) {
        fileDiapoRepert.mkdirs();//from  ww  w.j  av  a  2 s.c om
        copieRepertoire(getStrRepertAppli() + File.separator + "diaporama", fileDiapoRepert.getAbsolutePath());
    }
    String strImageDiapoRepert = getStrRepertTemp() + "/diaporama/images";
    File fileImagesDiapoRepert = new File(strImageDiapoRepert);
    if (!fileImagesDiapoRepert.exists()) {
        fileImagesDiapoRepert.mkdirs();
    }
    String strVignetteDiapoRepert = getStrRepertTemp() + "/diaporama/vignettes";
    File fileVignetteDiapoRepert = new File(strVignetteDiapoRepert);
    if (!fileVignetteDiapoRepert.exists()) {
        fileVignetteDiapoRepert.mkdirs();
    }
    for (int i = 0; i < diapo.getiNombreImages(); i++) {
        copieFichierRepertoire(diapo.getStrFichiersImage(i), strImageDiapoRepert);
        Image img = new Image("file:" + diapo.getStrFichiersImage(i), 400, 300, true, true);
        ReadWriteImage.writeJpeg(img, fileVignetteDiapoRepert + File.separator + diapo.getStrFichiers(i), 0.75f,
                false, 0);

    }
    String strDiapoNom = "diapo" + iNumero + ".html";
    int intervalle = (int) (diapo.getDelaiDiaporama() * 1000);
    String strContenuHTML = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
            + "\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n" + "\n"
            + "    <!--\n" + "            Supersized - Fullscreen Slideshow jQuery Plugin\n"
            + "            Version : 3.2.7\n"
            + "            Site   : www.buildinternet.com/project/supersized\n" + "            \n"
            + "            Author   : Sam Dunn\n"
            + "            Company : One Mighty Roar (www.onemightyroar.com)\n"
            + "            License : MIT License / GPL License\n" + "    -->\n" + "\n" + "    <head>\n" + "\n"
            + "        <title>Supersized - Full Screen Background Slideshow jQuery Plugin</title>\n"
            + "        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />\n" + "\n"
            + "        <link rel=\"stylesheet\" href=\"css/supersized.css\" type=\"text/css\" media=\"screen\" />\n"
            + "        <link rel=\"stylesheet\" href=\"theme/supersized.shutter.css\" type=\"text/css\" media=\"screen\" />\n"
            + "\n"
            + "        <script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\"></script>\n"
            + "        <script type=\"text/javascript\" src=\"js/jquery.easing.min.js\"></script>\n" + "\n"
            + "        <script type=\"text/javascript\" src=\"js/supersized.3.2.7.min.js\"></script>\n"
            + "        <script type=\"text/javascript\" src=\"theme/supersized.shutter.min.js\"></script>\n"
            + "\n" + "        <script type=\"text/javascript\">\n" + "\n"
            + "            jQuery(function ($) {\n" + "\n" + "                $.supersized({\n"
            + "                    // Functionality\n"
            + "                    slideshow: 1, // Slideshow on/off\n"
            + "                    autoplay: 1, // Slideshow starts playing automatically\n"
            + "                    start_slide: 1, // Start slide (0 is random)\n"
            + "                    stop_loop: 0, // Pauses slideshow on last slide\n"
            + "                    random: 0, // Randomize slide order (Ignores start slide)\n"
            + "                    slide_interval: " + intervalle + ", // Length between transitions\n"
            + "                    transition: 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left\n"
            + "                    transition_speed: 1200, // Speed of transition\n"
            + "                    new_window: 1, // Image links open in new window/tab\n"
            + "                    pause_hover: 0, // Pause slideshow on hover\n"
            + "                    keyboard_nav: 1, // Keyboard navigation on/off\n"
            + "                    performance: 2, // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)\n"
            + "                    image_protect: 1, // Disables image dragging and right click with Javascript\n"
            + "\n" + "                    // Size & Position                     \n"
            + "                    min_width: 0, // Min width allowed (in pixels)\n"
            + "                    min_height: 0, // Min height allowed (in pixels)\n"
            + "                    vertical_center: 1, // Vertically center background\n"
            + "                    horizontal_center: 1, // Horizontally center background\n"
            + "                    fit_always: 1, // Image will never exceed browser width or height (Ignores min. dimensions)\n"
            + "                    fit_portrait: 1, // Portrait images will not exceed browser height\n"
            + "                    fit_landscape: 0, // Landscape images will not exceed browser width\n" + "\n"
            + "                    // Components                     \n"
            + "                    slide_links: 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank')\n"
            + "                    thumb_links: 1, // Individual thumb links for each slide\n"
            + "                    thumbnail_navigation: 0, // Thumbnail navigation\n"
            + "                    slides: [// Slideshow Images\n";
    for (int i = 0; i < diapo.getiNombreImages(); i++) {
        strContenuHTML += "                        {" + "image: 'images/" + diapo.getStrFichiers(i) + "', "
                + "title: '"
                + diapo.getStrLibellesImages(i).replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;")
                        .replace("\"", "&quot;")
                + "', " + "thumb: 'vignettes/" + diapo.getStrFichiers(i) + "', " + "url: ''" + "},\n";
    }
    strContenuHTML += "                    ],\n" + "                    // Theme Options            \n"
            + "                    progress_bar: 1, // Timer for each slide                     \n"
            + "                    mouse_scrub: 0\n" + "\n" + "                });\n" + "            });\n"
            + "\n" + "        </script>\n" + "        <style type=\"text/css\">\n"
            + "            #prevslide,#nextslide,#controls,#controls-wrapper,#progress-back,#thumb-tray{\n"
            + "                opacity : 0.4;\n" + "                transition : 0.5 ease;\n"
            + "            }\n" + "            #supersized li{\n" + "                background: "
            + diapo.getStrCouleurFondDiaporama() + ";\n" + "            }\n" + "        </style>\n" + "\n"
            + "    </head>\n" + "\n" + "    <body>\n" + "\n" + "\n" + "        <!--Thumbnail Navigation-->\n"
            + "        <div id=\"prevthumb\"></div>\n" + "        <div id=\"nextthumb\"></div>\n" + "\n"
            + "        <!--Arrow Navigation-->\n" + "        <a id=\"prevslide\" class=\"load-item\"></a>\n"
            + "        <a id=\"nextslide\" class=\"load-item\"></a>\n" + "\n"
            + "        <div id=\"thumb-tray\" class=\"load-item\">\n"
            + "            <div id=\"thumb-back\"></div>\n" + "            <div id=\"thumb-forward\"></div>\n"
            + "        </div>\n" + "\n" + "        <!--Time Bar-->\n"
            + "<!--        <div id=\"progress-back\" class=\"load-item\">\n"
            + "            <div id=\"progress-bar\"></div>\n" + "        </div>-->\n" + "\n"
            + "        <!--Control Bar-->\n" + "        <div id=\"controls-wrapper\" class=\"load-item\">\n"
            + "            <div id=\"controls\">\n" + "\n"
            + "                <a id=\"play-button\"><img id=\"pauseplay\" src=\"img/pause.png\"/></a>\n" + "\n"
            + "                <!--Slide counter-->\n" + "                <div id=\"slidecounter\">\n"
            + "                    <span class=\"slidenumber\"></span> / <span class=\"totalslides\"></span>\n"
            + "                </div>\n" + "\n" + "                <!--Slide captions displayed here-->\n"
            + "                <div id=\"slidecaption\"></div>\n" + "\n"
            + "                <!--Thumb Tray button-->\n"
            + "                <a id=\"tray-button\"><img id=\"tray-arrow\" src=\"img/button-tray-up.png\"/></a>\n"
            + "\n" + "                <!--Navigation-->\n"
            + "                <!--                <ul id=\"slide-list\"></ul>-->\n" + "\n"
            + "            </div>\n" + "        </div>\n" + "        <script type=\"text/javascript\">\n"
            + "            $(function () {\n" + "                $(\"body\").mouseover(function () {\n"
            + "                    $(\"#prevslide,#nextslide\").css({opacity: 0.6});\n"
            + "                    $(\"#controls-wrapper\").css({opacity: 0.8});\n"
            + "                    $(\"#thumb-tray,#controls,#progress-back\").css({opacity: 1.0});\n"
            + "                })\n" + "                $(\"body\").mouseout(function () {\n"
            + "                    $(\"#prevslide,#nextslide\").css({opacity: 0.2});\n"
            + "                    $(\"#progress-back,#thumb-tray,#controls,#controls-wrapper\").css({opacity: 0.0});\n"
            + "                });\n" + "            });\n" + "        </script>\n" + "\n" + "    </body>\n"
            + "</html>";
    File fileIndexHTML = new File(strDiapoRepert + File.separator + strDiapoNom);
    fileIndexHTML.setWritable(true);
    OutputStreamWriter oswFichierHTML = new OutputStreamWriter(new FileOutputStream(fileIndexHTML), "UTF-8");
    try (BufferedWriter bwFichierHTML = new BufferedWriter(oswFichierHTML)) {
        bwFichierHTML.write(strContenuHTML);
    }

}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @throws IOException Exception d'entre sortie
 *///from   w  w  w .  j a v a 2s  .com
private static void sauveHistoFichiers() throws IOException {
    File fileFichConfig = new File(
            EditeurPanovisu.fileRepertConfig.getAbsolutePath() + File.separator + "derniersprojets.cfg");
    if (!fileFichConfig.exists()) {
        fileFichConfig.createNewFile();
    }
    fileFichConfig.setWritable(true);
    String strContenuFichier = "";
    for (int i = 0; i < nombreHistoFichiers; i++) {
        strContenuFichier += strHistoFichiers[i] + "\n";
    }
    OutputStreamWriter oswFichierHisto = null;
    try {
        oswFichierHisto = new OutputStreamWriter(new FileOutputStream(fileFichConfig), "UTF-8");

    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedWriter bwFichierHisto = new BufferedWriter(oswFichierHisto);
    try {
        bwFichierHisto.write(strContenuFichier);

    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        bwFichierHisto.close();

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

}

From source file:editeurpanovisu.EditeurPanovisu.java

private static void sauvePreferences() throws IOException {
    File fileFichPreferences = new File(
            EditeurPanovisu.fileRepertConfig.getAbsolutePath() + File.separator + "preferences.cfg");
    if (!fileFichPreferences.exists()) {
        fileFichPreferences.createNewFile();
    }// w  w  w.j  a  va  2 s.com
    fileFichPreferences.setWritable(true);
    String strContenuFichier = "typeFichiersTransf=" + getStrTypeFichierTransf() + "\n";
    strContenuFichier += "tailleLoupe=" + getiTailleLoupe() + "\n";
    strContenuFichier += "afficheLoupe=" + isAfficheLoupe() + "\n";
    strContenuFichier += "largeurE2C=" + getLargeurE2C() + "\n";
    strContenuFichier += "hauteurE2C=" + getHauteurE2C() + "\n";
    strContenuFichier += "netteteTransf=" + isbNetteteTransf() + "\n";
    strContenuFichier += "niveauNetteteTransf=" + getNiveauNetteteTransf() + "\n";
    OutputStreamWriter oswFichierHisto = null;
    try {
        oswFichierHisto = new OutputStreamWriter(new FileOutputStream(fileFichPreferences), "UTF-8");

    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedWriter bwFichierHisto = new BufferedWriter(oswFichierHisto);
    try {
        bwFichierHisto.write(strContenuFichier);

    } catch (IOException ex) {
        Logger.getLogger(ConfigDialogController.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        bwFichierHisto.close();

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

}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @throws IOException Exception d'entre sortie
 *//*from  w w w .j  a va  2 s.  c  o  m*/
private static void modeleSauver() throws IOException {
    File fileTemplate;
    FileChooser fcRepertChoix = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("fichier Modle panoVisu (*.tpl)",
            "*.tpl");
    fcRepertChoix.getExtensionFilters().add(extFilter);
    File fileRepert = new File(getStrRepertAppli() + File.separator + "templates");
    if (!fileRepert.exists()) {
        fileRepert.mkdirs();
    }
    fcRepertChoix.setInitialDirectory(fileRepert);
    fileTemplate = fcRepertChoix.showSaveDialog(null);

    if (fileTemplate != null) {
        String strContenuFichier = getGestionnaireInterface().strGetTemplate();
        fileTemplate.setWritable(true);
        OutputStreamWriter oswTemplate = new OutputStreamWriter(new FileOutputStream(fileTemplate), "UTF-8");
        try (BufferedWriter bwTemplate = new BufferedWriter(oswTemplate)) {
            bwTemplate.write(strContenuFichier);
        }
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(rbLocalisation.getString("main.dialog.sauveModele"));
        alert.setHeaderText(null);
        alert.setContentText(rbLocalisation.getString("main.dialog.sauveModeleMessage"));
        alert.showAndWait();
    }

}

From source file:com.storm.function.GsxtFunction.java

@SuppressWarnings("deprecation")
public String getSerializedAllIn(WebParam webParam) throws Exception {
    ChannelLogger LOGGER = ChannelLoggerFactory.getLogger(GsxtFunction.class, webParam.getLogback());
    Gson gson = new GsonBuilder().create();
    Map<String, String> resultMap = new LinkedHashMap<String, String>();

    try {/*  w  ww . j  a va 2  s  . com*/
        LOGGER.info("==================GsxtFunction.getSerializedAllIn start!======================");
        SerializedAllIn serializedAllIn = new SerializedAllIn(); //
        WebClient webClient = WebCrawler.getInstance().getWebClient();

        String searchPageUrl = webParam.getSearchPage();
        if (StringUtils.isEmpty(searchPageUrl)) {
            LOGGER.error("The searchPageUrl is not defined!");
            return null;
        }

        //?cookie
        clearCookies(webClient, new URL(searchPageUrl));

        WebRequest webRequest = new WebRequest(new URL(searchPageUrl), HttpMethod.GET);
        HtmlPage searchPage = webClient.getPage(webRequest);
        String searchPageHtml = searchPage.asXml();
        LOGGER.info("searchPageHtml:" + searchPageHtml);

        if (searchPageHtml.contains("???")
                || searchPageHtml.contains("?")) { //???? ??
            resultMap.put("statusCodeDef", StatusCodeDef.FREQUENCY_LIMITED);
            resultMap.put("searchPageHtml", IPUtil.getHostAndIpStr() + searchPageHtml);
            return gson.toJson(resultMap);
        }

        //imageUrl
        HtmlImage image = searchPage.getFirstByXPath(webParam.getCodeImageId());
        Map<String, String> webParamParams = webParam.getParams();

        File parentDirFile = new File(StormTopologyConfig.getNfs_filepath());
        parentDirFile.setReadable(true); //
        parentDirFile.setWritable(true); //
        if (!parentDirFile.exists()) {
            parentDirFile.mkdirs();
        }
        String imageName = UUID.randomUUID() + ".jpg";
        File codeImageFile = new File(StormTopologyConfig.getNfs_filepath() + "/" + imageName);
        codeImageFile.setReadable(true); //
        codeImageFile.setWritable(true); //
        LOGGER.info(
                "The codeImageFile of GsxtFunction.getSerializedAllIn is:" + codeImageFile.getAbsolutePath());

        if (searchPageUrl.contains("gsxt.cqgs.gov.cn")) { //?
            Page page = webClient.getPage("http://gsxt.cqgs.gov.cn/sc.action?width=130&height=40&fs=23");
            InputStream is = page.getWebResponse().getContentAsStream();
            FileUtils.copyInputStreamToFile(is, codeImageFile);
            LOGGER.info("----codeImageFile saved!----");
            LOGGER.info("The codeImageFile of GsxtFunction.getSerializedAllIn is:{}",
                    codeImageFile.getAbsolutePath());
            serializedAllIn
                    .setImageUrl("http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName);
            LOGGER.info("The serializedAllIn.imageUrl is: " + serializedAllIn.getImageUrl());
        } else {
            if (image == null && webParamParams != null
                    && !StringUtils.isEmpty(webParamParams.get("imagecodeIframeSrc"))) { //?? ???iframe-parent
                HtmlPage imagecodeIframePage = webClient.getPage(webParamParams.get("imagecodeIframeSrc"));
                image = imagecodeIframePage.getFirstByXPath(webParam.getCodeImageId());
            } else if (image != null && StringUtils.isEmpty(image.getAttribute("src"))) { //???src???
                image.click();

                HtmlElement hyzBtn1 = searchPage.getFirstByXPath("//div[@id='woaicss_con1']/ul/li[2]/div[2]/a");//???
                HtmlElement hyzBtn2 = searchPage
                        .getFirstByXPath("//div[@id='codeWindow']/div/ul/li[2]/div[2]/a");//?
                if (StringUtils.isEmpty(image.getAttribute("src")) && hyzBtn1 != null) { //??
                    hyzBtn1.click();
                } else if (StringUtils.isEmpty(image.getAttribute("src")) && hyzBtn2 != null) {
                    hyzBtn2.click();
                }
            }

            if (searchPageHtml.contains("??")) { //
                LOGGER.info("====================?====================");
                HtmlElement hyzBtn3 = searchPage.getFirstByXPath("//a[@id='kaptchaText']"); //?
                hyzBtn3.click();
            }

            if (image == null) {
                resultMap.put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                resultMap.put("searchPageHtml", IPUtil.getHostAndIpStr() + searchPageHtml);
                resultMap.put("isImageNull", "true");
                return gson.toJson(resultMap);
            }

            try {
                image.saveAs(codeImageFile);
                LOGGER.info("----codeImageFile saved!----");
                LOGGER.info("The codeImageFile of GsxtFunction.getSerializedAllIn is:{}",
                        codeImageFile.getAbsolutePath());
                serializedAllIn
                        .setImageUrl("http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName);
                LOGGER.info("The serializedAllIn.imageUrl is: " + serializedAllIn.getImageUrl());
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("----codeImageFile saveAs fail----");
                resultMap.put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                resultMap.put("searchPageHtml",
                        IPUtil.getHostAndIpStr() + "?saveAs?");
                return gson.toJson(resultMap);
            }
        }

        //cookies
        Set<Cookie> cookies = webClient.getCookieManager().getCookies(new URL(searchPageUrl));
        serializedAllIn.setCookies(cookies);

        //webResponse
        WebResponse webResponse = searchPage.getWebResponse();
        serializedAllIn.setWebResponse(webResponse);

        //??
        String serializedAllInFileName = UUID.randomUUID().toString() + StatusCodeDef.SERIALIZED_FILE_SUFFIX;
        File serializedAllInFile = new File(
                StormTopologyConfig.getNfs_filepath() + "/" + serializedAllInFileName);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serializedAllInFile));
        oos.writeObject(serializedAllIn);
        oos.close();
        LOGGER.info("The serializedAllInFileName is: " + serializedAllInFileName);

        // ???  ??URL
        resultMap.put("ip", ip);
        resultMap.put("hostName", hostName);
        resultMap.put("statusCodeDef", StatusCodeDef.SCCCESS);
        resultMap.put("codeImageUrl", serializedAllIn.getImageUrl());
        resultMap.put("serializedFileName", serializedAllInFileName);
    } finally {
        LOGGER.returnRedisResource();
    }

    return gson.toJson(resultMap);
}

From source file:com.storm.function.GsxtFunction.java

private HtmlPage getSearchPageByUrl(WebClient webClient, WebParam webParam) throws Exception {
    ChannelLogger LOGGER = ChannelLoggerFactory.getLogger(GsxtFunction.class, webParam.getLogback());
    HtmlPage searchPage = null;/*from w  w  w  .  j  a v a  2  s . c  om*/

    try {
        String searchPageUrl = webParam.getSearchPage();
        if (StringUtils.isEmpty(searchPageUrl)) {
            LOGGER.error("The searchPageUrl is not defined!");
            return null;
        }
        //?cookie
        clearCookies(webClient, new URL(searchPageUrl));

        String searchPageHtml = "";
        WebRequest webRequest = new WebRequest(new URL(searchPageUrl), HttpMethod.GET);
        if ("shanxi".equals(webParam.getParams().get("area").toString())) {
            WebWindow window = webClient.openWindow(new URL(searchPageUrl), "shanxi");
            searchPage = webClient.getPage(window, webRequest);
        } else {
            searchPage = webClient.getPage(webRequest);
        }
        searchPageHtml = searchPage.asXml();
        LOGGER.info("searchPageHtml:" + searchPageHtml);

        if (searchPageHtml.contains("???")) { //???? ??
            webParam.getParams().put("statusCodeDef", StatusCodeDef.FREQUENCY_LIMITED);
            webParam.getParams().put("searchPageHtml", IPUtil.getHostAndIpStr() + searchPageHtml);
            return searchPage;
        }

        // ???
        if (!StringUtils.isEmpty(webParam.getParams().get("area"))
                && "ningxia".equals(webParam.getParams().get("area"))
                && searchPageHtml.contains("?")) {
            webParam.getParams().put("statusCodeDef", StatusCodeDef.FREQUENCY_LIMITED);
            webParam.getParams().put("searchPageHtml", IPUtil.getHostAndIpStr() + searchPageHtml);
            return searchPage;
        }

        //imageUrl
        HtmlImage image = searchPage.getFirstByXPath(webParam.getCodeImageId());
        Map<String, String> webParamParams = webParam.getParams();

        File parentDirFile = new File(StormTopologyConfig.getNfs_filepath());
        parentDirFile.setReadable(true); //
        parentDirFile.setWritable(true); //
        if (!parentDirFile.exists()) {
            parentDirFile.mkdirs();
        }
        String imageName = null;
        if ("chongqing".equals(webParam.getParams().get("area").toString())) {
            imageName = UUID.randomUUID() + ".png";
        } else {
            imageName = UUID.randomUUID() + ".jpg";
        }
        File codeImageFile = new File(StormTopologyConfig.getNfs_filepath() + "/" + imageName);
        codeImageFile.setReadable(true); //
        codeImageFile.setWritable(true); //

        if (searchPageUrl.contains("gsxt.cqgs.gov.cn")) { //?
            Page page = webClient.getPage("http://gsxt.cqgs.gov.cn/sc.action?width=130&height=40&fs=23");
            InputStream is = null;
            try {
                is = page.getWebResponse().getContentAsStream();
                FileUtils.copyInputStreamToFile(is, codeImageFile);
                LOGGER.info("----codeImageFile saved!----");
                LOGGER.info("The codeImageFile of GsxtFunction.getSearchPageByUrl is:{}",
                        codeImageFile.getAbsolutePath());
                String imageUrl = "http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName;
                LOGGER.info("The imageUrl is: " + imageUrl);
                webParam.getParams().put("imageUrl", imageUrl);
                webParam.getParams().put("statusCodeDef", StatusCodeDef.SCCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("----codeImageFile saved fail!----");
                webParam.getParams().put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                webParam.getParams().put("searchPageHtml",
                        IPUtil.getHostAndIpStr() + "?copyInputStreamToFile?");
            }
        } else if (searchPageUrl.contains("fjaic.gov.cn")) { //?
            Page page = webClient.getPage(
                    "http://wsgs.fjaic.gov.cn/creditpub/captcha?preset=str-01,math-01&ra=" + Math.random());
            InputStream is = null;
            try {
                is = page.getWebResponse().getContentAsStream();
                FileUtils.copyInputStreamToFile(is, codeImageFile);
                LOGGER.info("----codeImageFile saved!----");
                LOGGER.info("The codeImageFile of GsxtFunction.getSearchPageByUrl is:{}",
                        codeImageFile.getAbsolutePath());
                String imageUrl = "http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName;
                LOGGER.info("The imageUrl is: " + imageUrl);
                webParam.getParams().put("imageUrl", imageUrl);
                webParam.getParams().put("statusCodeDef", StatusCodeDef.SCCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("----codeImageFile saved fail!----");
                webParam.getParams().put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                webParam.getParams().put("searchPageHtml",
                        IPUtil.getHostAndIpStr() + "?copyInputStreamToFile?");
            }
        } else if (searchPageUrl.contains("gsxt.hnaic.gov.cn")) { //?
            Page page = webClient
                    .getPage("http://gsxt.hnaic.gov.cn/notice/captcha?preset=&ra=" + Math.random());
            InputStream is = null;
            try {
                is = page.getWebResponse().getContentAsStream();
                FileUtils.copyInputStreamToFile(is, codeImageFile);
                LOGGER.info("----codeImageFile saved!----");
                LOGGER.info("The codeImageFile of GsxtFunction.getSearchPageByUrl is:{}",
                        codeImageFile.getAbsolutePath());
                String imageUrl = "http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName;
                LOGGER.info("The imageUrl is: " + imageUrl);
                webParam.getParams().put("imageUrl", imageUrl);
                webParam.getParams().put("statusCodeDef", StatusCodeDef.SCCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("----codeImageFile saved fail!----");
                webParam.getParams().put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                webParam.getParams().put("searchPageHtml",
                        IPUtil.getHostAndIpStr() + "?copyInputStreamToFile?");
            }
        } else if (searchPageUrl.contains("218.95.241.36")) { //?
            Page page = webClient
                    .getPage("http://218.95.241.36/validateCode.jspx?type=0&id=0.9730435636142166");
            InputStream is = null;
            try {
                is = page.getWebResponse().getContentAsStream();
                FileUtils.copyInputStreamToFile(is, codeImageFile);
                LOGGER.info("----codeImageFile saved!----");
                LOGGER.info("The codeImageFile of GsxtFunction.getSearchPageByUrl is:{}",
                        codeImageFile.getAbsolutePath());
                String imageUrl = "http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName;
                LOGGER.info("The imageUrl is: " + imageUrl);
                webParam.getParams().put("imageUrl", imageUrl);
                webParam.getParams().put("statusCodeDef", StatusCodeDef.SCCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("----codeImageFile saved fail!----");
                webParam.getParams().put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                webParam.getParams().put("searchPageHtml",
                        IPUtil.getHostAndIpStr() + "?copyInputStreamToFile?");
            }
        } else {
            if (image == null && webParamParams != null
                    && !StringUtils.isEmpty(webParamParams.get("imagecodeIframeSrc"))) { //?? ???iframe-parent
                HtmlPage imagecodeIframePage = webClient.getPage(webParamParams.get("imagecodeIframeSrc"));
                image = imagecodeIframePage.getFirstByXPath(webParam.getCodeImageId());
            } else if (image != null && StringUtils.isEmpty(image.getAttribute("src"))) { //???src???
                image.click();

                HtmlElement hyzBtn1 = searchPage.getFirstByXPath("//div[@id='woaicss_con1']/ul/li[2]/div[2]/a");//???
                HtmlElement hyzBtn2 = searchPage
                        .getFirstByXPath("//div[@id='codeWindow']/div/ul/li[2]/div[2]/a");//?
                if (StringUtils.isEmpty(image.getAttribute("src")) && hyzBtn1 != null) { //??
                    hyzBtn1.click();
                } else if (StringUtils.isEmpty(image.getAttribute("src")) && hyzBtn2 != null) {
                    hyzBtn2.click();
                }
            } else if (searchPageUrl.contains("218.57.139.24")) { //?
                HtmlElement zdmBtn = searchPage.getFirstByXPath("//a[@onclick='zdm()']");
                if (zdmBtn != null) {
                    zdmBtn.click();
                }
            }

            if (image == null) {
                webParam.getParams().put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                webParam.getParams().put("searchPageHtml", IPUtil.getHostAndIpStr() + searchPageHtml);
                webParam.getParams().put("isImageNull", "true");
                return searchPage;
            }

            try {
                image.saveAs(codeImageFile);
                LOGGER.info("----codeImageFile saved!----");
                LOGGER.info("The codeImageFile of GsxtFunction.getSearchPageByUrl is:"
                        + codeImageFile.getAbsolutePath());
                String imageUrl = "http://" + StormTopologyConfig.getNfs_nginx_server() + "/" + imageName;
                LOGGER.info("The imageUrl is: " + imageUrl);
                webParam.getParams().put("imageUrl", imageUrl);
                webParam.getParams().put("statusCodeDef", StatusCodeDef.SCCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("----codeImageFile saveAs fail!----");
                webParam.getParams().put("statusCodeDef", StatusCodeDef.IMAGECODE_ERROR);
                webParam.getParams().put("searchPageHtml",
                        IPUtil.getHostAndIpStr() + "?saveAs?");
            }
        }
    } finally {
        LOGGER.returnRedisResource();
    }

    return searchPage;
}